123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085 |
- #include <pthread.h>
- #include <time.h>
- #include <stdlib.h>
- #include <string.h>
- #include <unistd.h>
- #include <curl/curl.h>
- #ifdef USE_LUA
- #include <lua.hpp>
- #endif
- #ifdef _WIN32
- #include <fcntl.h>
- #include <winsock2.h>
- #include <ws2tcpip.h>
- #include <mswsock.h>
- #define CLOSESOCKET(x) closesocket(x)
- #else
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <netdb.h>
- #include <arpa/inet.h>
- #define CLOSESOCKET(x) close(x)
- #endif
- #include "BBS2chProxyConnection.h"
- #include "DataStorage.h"
- #include "hmac.h"
- #include "stringEncodingConverter.h"
- //#define DEBUG 1
- extern char *proxy_server;
- extern long proxy_port;
- extern long proxy_type;
- extern long timeout;
- extern char *user_agent;
- extern char *api_ua_dat;
- extern char *x_2ch_ua_dat;
- extern char *appKey;
- extern int allow_chunked;
- extern int curl_features;
- extern unsigned int curl_version_number;
- extern bool accept_https;
- extern int force_5chnet;
- extern int force_5chnet_https;
- extern int force_ipv4;
- extern char *bbsmenu_url;
- extern char *api_server;
- extern std::map<std::string, std::string> bbscgi_headers;
- extern int gikofix;
- extern CURLSH *curl_share;
- extern char *lua_script;
- extern void log_printf(int level, const char *format ...);
- #include "utils.h"
- #ifdef USE_LUA
- extern "C" {
- static int lua_hmacSHA256(lua_State *l)
- {
- static const char *table = "0123456789abcdef";
- size_t keyLength, dataLength;
- const char *key = luaL_checklstring(l, 1, &keyLength);
- const char *data = luaL_checklstring(l, 2, &dataLength);
- if (!key || !data) return 0;
- unsigned char digest[32];
- char digestStr[65];
- proxy2ch_HMAC_SHA256(key, keyLength, data, dataLength, digest);
- for (int i=0; i<32; i++) {
- unsigned char c = digest[i];
- unsigned char upper = (c >> 4) & 0xf;
- unsigned char lower = c & 0xf;
- digestStr[i*2] = table[upper];
- digestStr[i*2+1] = table[lower];
- }
- digestStr[64] = 0;
- lua_pushstring(l, digestStr);
- return 1;
- }
- static int lua_decodeURIComponent(lua_State *l)
- {
- size_t length;
- const char *input = luaL_checklstring(l, 1, &length);
- if (!input) return 0;
- bool decodePlus = true;
- if (!lua_isnoneornil(l, 2)) {
- decodePlus = (lua_toboolean(l, 2));
- }
- std::string output;
- for (int i=0;i<length;i++) {
- if (input[i] == '%') {
- if (i < length - 2) {
- char from[3];
- char *end;
- from[0] = input[i+1];
- from[1] = input[i+2];
- from[2] = 0;
- unsigned long n = strtoul(from, &end, 16);
- if (n < 256 && end == from+2) {
- output.append(1, n);
- i += 2;
- continue;
- }
- }
- }
- else if (decodePlus && input[i] == '+') {
- output.append(" ");
- continue;
- }
- output.append(1, input[i]);
- }
- lua_pushstring(l, output.c_str());
- return 1;
- }
- static int lua_encodeURIComponent(lua_State *l)
- {
- size_t length;
- const char *input = luaL_checklstring(l, 1, &length);
- if (!input) return 0;
- bool spaceAsPlus = true;
- if (!lua_isnoneornil(l, 2)) {
- spaceAsPlus = (lua_toboolean(l, 2));
- }
- std::string output;
- for (int i=0;i<length;i++) {
- unsigned char c = (unsigned char)input[i];
- if ((c >= '0' && c <= '9') ||
- (c >= 'A' && c <= 'Z') ||
- (c >= 'a' && c <= 'z') ||
- (c == '*') || (c == '-') || (c == '.') || (c == '_')) {
- output.append(1, c);
- }
- else if (c == ' ' && spaceAsPlus) {
- output.append("+");
- }
- else {
- char percentEncoded[4];
- snprintf(percentEncoded, 4, "%%%02X", c);
- output.append(percentEncoded);
- }
- }
- lua_pushstring(l, output.c_str());
- return 1;
- }
- static int lua_convertShiftJISToUTF8(lua_State *l)
- {
- size_t length;
- const char *input = luaL_checklstring(l, 1, &length);
- if (!input) return 0;
- if (length > 0) {
- char *output = convertShiftJISToUTF8(input, length);
- if (!output) lua_pushnil(l);
- else {
- lua_pushstring(l, output);
- free(output);
- }
- }
- else lua_pushstring(l, "");
- return 1;
- }
- }
- static std::string monaKey;
- void BBS2chProxyConnection::setMonaKey(const std::string &key) {
- pthread_mutex_lock(mutex);
- monaKey = key;
- pthread_mutex_unlock(mutex);
- }
- std::string BBS2chProxyConnection::getMonaKey() {
- if (monaKey.empty())
- return "00000000-0000-0000-0000-000000000000";
- return monaKey;
- }
- #endif
- void *BBS2chProxyConnection::launch(void *param)
- {
- reinterpret_cast<BBS2chProxyConnection *>(param)->connect();
- return (void *)NULL;
- }
- void BBS2chProxyConnection::run(void)
- {
- pthread_t thread;
- pthread_attr_t thread_attr;
- pthread_attr_init(&thread_attr);
- pthread_attr_setdetachstate(&thread_attr , PTHREAD_CREATE_DETACHED);
- if(0 != pthread_create(&thread , &thread_attr , &BBS2chProxyConnection::launch , this))
- perror("pthread_create");
- pthread_attr_destroy(&thread_attr);
- }
- void *BBS2chProxyConnection::tunnel_c2s(void *param)
- {
- char buf[2048];
- fd_set fds;
- int sock_c = reinterpret_cast<BBS2chProxyConnection *>(param)->sock_c;
- int sock_s = reinterpret_cast<BBS2chProxyConnection *>(param)->sock_s;
- #ifdef _WIN32
- struct timeval timeout;
- timeout.tv_sec = 0;
- timeout.tv_usec = 10000;
- #endif
-
- while(1) {
- #ifdef _WIN32
- FD_ZERO(&fds);
- FD_SET(sock_c,&fds);
- if(select(sock_c + 1,&fds,NULL,NULL,&timeout) < 0) break;
- if(FD_ISSET(sock_c,&fds)) {
- #endif
- int ret = recv(sock_c, buf, 2048, 0);
- if(ret > 0) send(sock_s, buf, ret, 0);
- else if(ret <= 0) break;
- #ifdef _WIN32
- }
- #endif
- }
- //fprintf(stderr,"tunnel_c2s end\n");
- CLOSESOCKET(sock_s);
- return NULL;
- }
- void *BBS2chProxyConnection::tunnel_s2c(void *param)
- {
- char buf[2048];
- fd_set fds;
- int sock_c = reinterpret_cast<BBS2chProxyConnection *>(param)->sock_c;
- int sock_s = reinterpret_cast<BBS2chProxyConnection *>(param)->sock_s;
-
- while(1) {
- int ret = recv(sock_s, buf, 2048, 0);
- if(ret > 0) send(sock_c, buf, ret, 0);
- else if(ret <= 0) break;
- }
- //fprintf(stderr,"tunnel_s2c end\n");
- CLOSESOCKET(sock_c);
- return NULL;
- }
- int BBS2chProxyConnection::tunnel(const char *addr, int port)
- {
- struct sockaddr_in server;
- memset(&server, 0, sizeof(server));
- server.sin_family = AF_INET;
- server.sin_addr.s_addr = inet_addr(addr);
- server.sin_port = htons(port);
- if(server.sin_addr.s_addr == 0xffffffff) {
- struct hostent *host;
- host = gethostbyname(addr);
- if (host == NULL) {
- sendResponse(400, "Bad Request", fpw);
- return -1;
- }
- server.sin_addr.s_addr = *(unsigned int *)host->h_addr_list[0];
- }
-
- log_printf(1,"Tunneling connection to %s:%d\n",addr,port);
-
- sock_s = socket(AF_INET, SOCK_STREAM, 0);
- if(-1 == ::connect(sock_s, (struct sockaddr *)&server, sizeof(server))) {
- perror("connect");
- sendResponse(400, "Bad Request", fpw);
- return -1;
- }
- send(sock_c, "HTTP/1.1 200 Connection established\r\n\r\n", 39, 0);
-
- pthread_t thread_c2s, thread_s2c;
- if(0 != pthread_create(&thread_c2s, NULL, &BBS2chProxyConnection::tunnel_c2s, this))
- perror("pthread_create");
- if(0 != pthread_create(&thread_s2c, NULL, &BBS2chProxyConnection::tunnel_s2c, this))
- perror("pthread_create");
- pthread_join(thread_c2s, NULL);
- pthread_join(thread_s2c, NULL);
-
- log_printf(1,"Tunneling connection to %s:%d finished\n",addr,port);
-
- return 0;
- }
- void BBS2chProxyConnection::connect(void)
- {
- char method[32], url[1024], protocol[32];
- int i;
- char *buf, *ptr;
- bool html2dat = false;
- bool html2dat_kako = false;
- regmatch_t match[7];
- long statusCode = 0;
-
- #ifdef _WIN32
- int sock_osfhandle = _open_osfhandle(sock_c, O_RDONLY);
- fpr = fdopen(sock_osfhandle, "rb");
- fpw = fdopen(sock_osfhandle, "wb");
- #else
- fpr = fdopen(sock_c, "rb");
- fpw = fdopen(sock_c, "wb");
- #endif
- if(!fpr || !fpw) {
- log_printf(0, "Error: cannot open file descripter for client\n");
- goto end;
- }
-
- buf = (char *)malloc(16384);
- if(!buf) goto end;
- ptr = buf;
-
- if(!fgets(buf,1024,fpr)) {
- sendResponse(400, "Bad Request", fpw);
- statusCode = 400;
- goto end;
- }
- i=0;
- while(*ptr != ' ' && *ptr != 0 && i < 32) method[i++] = *ptr++;
- if(*ptr == 0 || i == 32) {
- sendResponse(400, "Bad Request", fpw);
- statusCode = 400;
- goto end;
- }
- method[i] = 0;
- ptr++;
- i=0;
- while(*ptr != ' ' && *ptr != 0 && i < 1024) url[i++] = *ptr++;
- if(*ptr == 0 || i == 1024) {
- sendResponse(400, "Bad Request", fpw);
- statusCode = 400;
- goto end;
- }
- url[i] = 0;
- ptr++;
- i=0;
- while(*ptr != '\r' && *ptr != '\n' && *ptr != 0 && i < 32) protocol[i++] = *ptr++;
- if(*ptr == 0 || i == 32) {
- sendResponse(400, "Bad Request", fpw);
- statusCode = 400;
- goto end;
- }
- protocol[i] = 0;
- log_printf(1, "Received %s %s %s\n",method,url,protocol);
-
- if(strcasecmp(method,"GET") && strcasecmp(method,"POST") && strcasecmp(method,"HEAD") && strcasecmp(method,"CONNECT")) {
- sendResponse(400, "Bad Request", fpw);
- statusCode = 400;
- goto end;
- }
- if(!url[0]) {
- sendResponse(400, "Bad Request", fpw);
- statusCode = 400;
- goto end;
- }
- if(strncasecmp(protocol,"HTTP",4)) {
- sendResponse(400, "Bad Request", fpw);
- statusCode = 400;
- goto end;
- }
-
- if(!strcasecmp(method,"CONNECT")) {
- if(!accept_https) {
- sendResponse(400, "Bad Request", fpw);
- statusCode = 400;
- goto end;
- }
- while(fgets(buf,16384,fpr)) {
- if(!strcmp("\r\n",buf)) break;
- }
- int port = 443;
- char *ptr = strchr(url, ':');
- if(ptr) {
- *ptr = 0;
- port = atoi(ptr+1);
- }
- tunnel(url, port);
- goto end;
- }
- if(force_5chnet && !strncasecmp(url,"http://",7)) {
- char *ptr = url+8;
- char *end = ptr;
- while(*end != '/' && *end != 0) end++;
- ptr = strstr(ptr,".2ch.net");
- if(ptr && ptr < end && memcmp(ptr-4,"menu.",5)) {
- memcpy(ptr+1,"5ch",3);
- force5ch = true;
- log_printf(1, "Detected *.2ch.net URL, changed target URL to %s\n",url);
- }
- }
-
- if(regexec(®ex, url, 6, match, 0) != REG_NOMATCH) {
- if(appKey || strncasecmp(url+match[1].rm_so,"headline.",9)) html2dat = true;
- }
- else if(regexec(®ex_kako, url, 7, match, 0) != REG_NOMATCH) {
- html2dat_kako = true;
- }
- else if(regexec(®ex_offlaw, url, 5, match, 0) != REG_NOMATCH) {
- char *thread = strstr(url,"key=");
- if(thread) {
- match[6].rm_so = thread+4-url;
- match[6].rm_eo = thread+4-url;
- char *ptr = thread+4;
- while(*ptr != '&' && *ptr != 0) {
- ptr++;
- match[6].rm_eo++;
- }
- if(match[6].rm_so != match[6].rm_eo) html2dat_kako = true;
- }
- }
-
- if(html2dat || html2dat_kako) {
- char tmp[1024];
- regmatch_t *tid = html2dat ? match+5 : match+6;
- strcpy(tmp,url);
- tmp[match[2].rm_eo] = 0;
- tmp[match[4].rm_eo] = 0;
- tmp[tid->rm_eo] = 0;
- if(!appKey || html2dat_kako) {
- log_printf(1, "Retrieving thread via read.cgi...\n");
- snprintf(url,1024,"%s/%s/%s",tmp+match[1].rm_so,tmp+match[4].rm_so,tmp+tid->rm_so);
- threadKey = std::string(url);
- snprintf(url,1024,"%s://%s/test/read.cgi/%s/%s/",force_5chnet_https?"https":"http",tmp+match[1].rm_so,tmp+match[4].rm_so,tmp+tid->rm_so);
- statusCode = datProxy(url, method);
- }
- else {
- log_printf(1, "Retrieving thread via API...\n");
- tmp[match[1].rm_eo] = 0;
- snprintf(url,1024,"https://%s/v1/%s/%s/%s",api_server,tmp+match[1].rm_so,tmp+match[4].rm_so,tmp+tid->rm_so);
- statusCode = datProxyAPI(url, method);
- }
- }
- else {
- char urlMod[1024];
- strcpy(urlMod,url);
- if(force_5chnet_https) {
- const char *host = "5ch.net";
- char *ptr = strstr(url,host);
- if(!ptr) {
- host = "2ch.net";
- ptr = strstr(url,host);
- }
- if(!ptr) {
- host = "bbspink.com";
- ptr = strstr(url,host);
- }
- if(ptr) {
- char *start = url+7;
- char *end = strchr(start,'/');
- int hostLength = strlen(host);
- if(!end) end = url+strlen(url);
- if(ptr >= start && ptr < end && (*(ptr-1) == '.' || *(ptr-1) == '/') && (*(ptr+hostLength) == '/' || *(ptr+hostLength) == ':' || *(ptr+hostLength) == 0)) {
- log_printf(1, "This is %s URL, connecting with HTTPS\n",host);
- if(*(ptr+hostLength) == ':') {
- *(ptr+hostLength) = 0;
- snprintf(urlMod,1024,"https://%s%s",start,end);
- *(ptr+hostLength) = ':';
- }
- else snprintf(urlMod,1024,"https://%s",start);
- log_printf(2, "URL is: %s\n",urlMod);
- }
- }
- }
-
- if(bbsmenu_url && !strcmp(url, bbsmenu_url)) {
- log_printf(1, "Running as a BBS menu proxy...\n");
- statusCode = bbsmenuProxy(urlMod, method);
- }
- else {
- bool isPostRequest = !strcasecmp(method, "POST");
- if(isPostRequest && (strstr(urlMod,".5ch.net") || strstr(urlMod,".bbspink.com")) && strstr(urlMod,"/test/bbs.cgi")) bbscgi = true;
- log_printf(1, "Not a thread request, passthrough...\n");
- struct curl_slist *headers = NULL;
- bool hasExpect = false;
- char *postdata = NULL;
- std::string hostStr;
- std::string boardStr;
- std::string threadStr;
- bool isNotFormURLEncoded = false;
- #ifdef USE_LUA
- std::map<std::string, std::string> headersForLua;
- #endif
- while(fgets(buf,16384,fpr)) {
- if(bbscgi) {
- char *ptr = strchr(buf, ':');
- if(ptr) {
- std::string header(buf, ptr-buf);
- if(bbscgi_headers.find(header) != bbscgi_headers.end()) {
- log_printf(1, "Ignoring header \"%s\" because alternative value exists\n", header.c_str());
- continue;
- }
- }
- }
- //fprintf(fpw,"%s",buf);
- //fprintf(stderr,"%s",buf);
- if(!strcmp("\r\n",buf)) break;
- if(!strncasecmp("Connection:",buf,11)) continue;
- else if(!strncasecmp("Host:",buf,5)) {
- char *ptr;
- ptr = strchr(buf, '\r');
- if(!ptr) ptr = strchr(buf, '\n');
- if(!ptr) continue;
- *ptr = 0;
- ptr = strchr(buf+5, ':');
- if(ptr) *ptr = 0;
- ptr = buf+5;
- while(*ptr == ' ') ptr++;
- if(force_5chnet) {
- char *ptr2 = strstr(ptr, ".2ch.net");
- if(ptr2) {
- *(ptr2+1) = '5';
- }
- }
- hostStr = std::string(ptr);
- continue;
- }
- //else if(!strncasecmp("Authorization:",buf,14)) continue;
- //else if(!strncasecmp("WWW-Authenticate:",buf,17)) continue;
- else if(user_agent && !strncasecmp("User-Agent:",buf,11)) continue;
- else if(bbscgi && !strncasecmp("Content-Length:",buf,15)) {
- char *ptr = buf + 15;
- while(*ptr == ' ') ptr++;
- content_length = atoi(ptr);
- continue;
- }
- else {
- char *ptr;
- ptr = strchr(buf, '\r');
- if(!ptr) ptr = strchr(buf, '\n');
- if(!ptr) continue;
- *ptr = 0;
- if(bbscgi && force_5chnet && !strncasecmp("Referer:",buf,8)) {
- char *ptr2 = strstr(buf+8, ".2ch.net");
- if(ptr2) {
- *(ptr2+1) = '5';
- }
- }
- headers = curl_slist_append(headers, buf);
- if(!strncasecmp("Content-Length:",buf,15)) {
- char *ptr = buf + 15;
- while(*ptr == ' ') ptr++;
- content_length = atoi(ptr);
- }
- else if(!strncasecmp("Expect:",buf,7)) {
- hasExpect = true;
- }
- else if(!strncasecmp("Content-Type:",buf,13)) {
- ptr = buf + 13;
- while(*ptr == ' ') ptr++;
- if(strncasecmp("application/x-www-form-urlencoded", ptr, 33)) {
- isNotFormURLEncoded = true;
- }
- }
- #ifdef USE_LUA
- if(bbscgi && lua_script) {
- ptr = strchr(buf, ':');
- if(ptr) {
- std::string header(buf, ptr-buf);
- ptr++;
- while(*ptr == ' ') ptr++;
- headersForLua.insert(std::make_pair(header, std::string(ptr)));
- }
- }
- #endif
- }
- }
- #ifdef USE_LUA
- if(bbscgi && lua_script && user_agent) {
- headersForLua.insert(std::make_pair("User-Agent", std::string(user_agent)));
- }
- #endif
- if(bbscgi && !isNotFormURLEncoded && content_length) {
- postdata = (char *)calloc(content_length+1, 1);
- content_length = fread(postdata,1,content_length,fpr);
- if(gikofix && content_length > 0) {
- char *ptr = postdata+content_length-1;
- while(*ptr == '\r' || *ptr == '\n') {
- *ptr-- = 0;
- }
- }
- }
- if(bbscgi && (!bbscgi_headers.empty() || lua_script)) {
- std::map<std::string, std::string> fields;
- if(postdata) {
- const char *ptr = postdata;
- while(1) {
- const char *tmp = ptr;
- while(*tmp != '=' && *tmp != 0) tmp++;
- if(*tmp == 0) break;
- std::string key(ptr, tmp-ptr);
- tmp++;
- ptr = tmp;
- while(*tmp != '&' && *tmp != 0) tmp++;
- std::string value(ptr, tmp-ptr);
- fields.insert(std::make_pair(key, value));
- if(*tmp == 0) break;
- ptr = tmp + 1;
- }
- }
- boardStr = fields["bbs"];
- threadStr = fields["key"];
- for(std::map<std::string, std::string>::iterator it = bbscgi_headers.begin(); it!=bbscgi_headers.end(); it++) {
- /* we cannot use a reference here, because the original string shouldn't be replaced */
- std::string value = it->second;
- if(!hostStr.empty()) {
- std::string::size_type pos = value.find("%HOST%");
- while(pos != std::string::npos) {
- value.replace(pos, 6, hostStr);
- pos = value.find("%HOST%", pos+hostStr.length());
- }
- }
- if(!boardStr.empty()) {
- std::string::size_type pos = value.find("%BOARD%");
- while(pos != std::string::npos) {
- value.replace(pos, 7, boardStr);
- pos = value.find("%BOARD%", pos+boardStr.length());
- }
- }
- if(!threadStr.empty()) {
- std::string::size_type pos = value.find("%THREAD%");
- while(pos != std::string::npos) {
- value.replace(pos, 8, threadStr);
- pos = value.find("%THREAD%", pos+threadStr.length());
- }
- }
- snprintf(buf,16384,"%s: %s",it->first.c_str(),value.c_str());
- headers = curl_slist_append(headers, buf);
- log_printf(1, "Appended custom header \"%s\"\n", buf);
- #ifdef USE_LUA
- if(lua_script) headersForLua[it->first] = value;
- #endif
- }
- }
- #ifdef USE_LUA
- if(bbscgi && lua_script) {
- lua_State* l = luaL_newstate();
- luaL_openlibs(l);
- if(luaL_loadfile(l, lua_script) != LUA_OK) {
- log_printf(0, "Lua: Failed to open script %s:\n %s\n", lua_script, lua_tostring(l, -1));
- goto lua_end;
- }
- lua_newtable(l);
- lua_pushstring(l, "hmacSHA256");
- lua_pushcfunction(l, lua_hmacSHA256);
- lua_settable(l, -3);
- lua_pushstring(l, "decodeURIComponent");
- lua_pushcfunction(l, lua_decodeURIComponent);
- lua_settable(l, -3);
- lua_pushstring(l, "encodeURIComponent");
- lua_pushcfunction(l, lua_encodeURIComponent);
- lua_settable(l, -3);
- lua_pushstring(l, "convertShiftJISToUTF8");
- lua_pushcfunction(l, lua_convertShiftJISToUTF8);
- lua_settable(l, -3);
- lua_pushstring(l, "monaKey");
- lua_pushstring(l, getMonaKey().c_str());
- lua_settable(l, -3);
- lua_setglobal(l, "proxy2ch");
- if(lua_pcall(l, 0, 0, 0) != LUA_OK) {
- log_printf(0, "Lua: Failed to run script %s:\n %s\n", lua_script, lua_tostring(l, -1));
- goto lua_end;
- }
- lua_getglobal(l, "willSendRequestToBbsCgi");
- if(!lua_isfunction(l, -1)) {
- log_printf(0, "Lua: willSendRequestToBbsCgi function does not exist in the script\n");
- goto lua_end;
- }
- lua_newtable(l);
- lua_pushstring(l, "headers");
- lua_newtable(l);
- for(std::map<std::string, std::string>::iterator it = headersForLua.begin(); it!=headersForLua.end(); it++) {
- lua_pushstring(l, it->first.c_str());
- lua_pushstring(l, it->second.c_str());
- lua_settable(l, -3);
- }
- lua_settable(l, -3);
- lua_pushstring(l, "body");
- lua_pushstring(l, postdata);
- lua_settable(l, -3);
- lua_pushstring(l, hostStr.c_str());
- lua_pushstring(l, boardStr.c_str());
- lua_pushstring(l, threadStr.c_str());
- if(lua_pcall(l, 4, 1, 0) != LUA_OK) {
- log_printf(0, "Lua: Failed to call willSendRequestToBbsCgi function:\n %s\n", lua_tostring(l, -1));
- goto lua_end;
- }
- if(!lua_istable(l, -1)) {
- log_printf(0, "Lua: A return type of willSendRequestToBbsCgi function should be a table\n");
- goto lua_end;
- }
- lua_pushstring(l, "body");
- lua_rawget(l, -2);
- if(lua_isstring(l, -1)) {
- size_t length;
- const char *newBody = lua_tolstring(l, -1, &length);
- if(length > content_length) {
- postdata = (char *)realloc(postdata, length+1);
- }
- strcpy(postdata, newBody);
- log_printf(1, "Lua: Set request body \"%s\"\n", newBody);
- }
- lua_pop(l, 1);
- lua_pushstring(l, "headers");
- lua_rawget(l, -2);
- if(lua_istable(l, -1)) {
- curl_slist_free_all(headers);
- headers = NULL;
- lua_pushnil(l);
- while(lua_next(l, -2)) {
- if(lua_isstring(l, -1) && lua_isstring(l, -2)) {
- std::string header = lua_tostring(l, -2);
- header += ": ";
- header += lua_tostring(l, -1);
- headers = curl_slist_append(headers, header.c_str());
- log_printf(1, "Lua: Set request header \"%s\"\n", header.c_str());
- }
- lua_pop(l, 1);
- }
- }
- lua_end:
- lua_close(l);
- }
- #endif
- if(!hasExpect) headers = curl_slist_append(headers, "Expect:");
-
- CURL *curl = curl_easy_init();
- if(curl) {
- CURLcode res;
- if(curl_share) curl_easy_setopt(curl, CURLOPT_SHARE, curl_share);
- curl_easy_setopt(curl, CURLOPT_URL, urlMod);
- curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
- curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
- curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, header_callback_proxy);
- curl_easy_setopt(curl, CURLOPT_HEADERDATA, this);
- curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback_proxy);
- curl_easy_setopt(curl, CURLOPT_WRITEDATA, this);
- if(postdata) {
- curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postdata);
- } else {
- if(content_length && isPostRequest) {
- /* set Content-Length explicitly via API to work properly with curl >= 7.66.0 */
- curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, content_length);
- }
- curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_callback_proxy);
- curl_easy_setopt(curl, CURLOPT_READDATA, this);
- }
- curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
- curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
- //curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
- if(force_ipv4) curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
- if(!strncasecmp(protocol,"HTTP/1.0",8) && !strncasecmp(urlMod, "http://", 7)) {
- curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
- }
- else {
- /* force use HTTP 1.1 because CURL_HTTP_VERSION_2TLS is used on curl (w/ nghttp2) >= 7.62.0 */
- curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
- }
- curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
- if(user_agent) {
- curl_easy_setopt(curl, CURLOPT_USERAGENT, user_agent);
- }
- if(isPostRequest) {
- curl_easy_setopt(curl, CURLOPT_POST, 1L);
- }
- else if(!strcasecmp(method, "HEAD")) {
- curl_easy_setopt(curl, CURLOPT_NOBODY, 1L);
- }
- if(proxy_server) {
- curl_easy_setopt(curl, CURLOPT_PROXY, proxy_server);
- curl_easy_setopt(curl, CURLOPT_PROXYPORT, proxy_port);
- curl_easy_setopt(curl, CURLOPT_PROXYTYPE, proxy_type);
- }
- res = curl_easy_perform(curl);
- if(res != CURLE_OK) {
- log_printf(0,"curl error: %s (%s)\n",curl_easy_strerror(res),urlMod);
- if(!status) sendResponse(503, "Service Unavailable", fpw);
- statusCode = 503;
- }
- else {
- if(chunked) {
- fprintf(fpw,"0\r\n\r\n");
- }
- curl_easy_getinfo(curl,CURLINFO_RESPONSE_CODE, &statusCode);
- }
- curl_easy_cleanup(curl);
- fflush(fpw);
- }
- curl_slist_free_all(headers);
- if(postdata) free(postdata);
- }
- }
-
- end:
- if(statusCode) log_printf(1, "Returned status code %d to client\n",statusCode);
- if(buf) free(buf);
- if(fpr) fclose(fpr);
- if(fpw) fclose(fpw);
- close(sock_c);
- delete this;
- }
- int BBS2chProxyConnection::datProxy(const char *url, const char *method)
- {
- DataStorage *html = NULL;
- long statusCode = 0;
- long rangeStart = 0, rangeEnd = 0;
- time_t lastModified = 0;
- time_t ifModifiedSince = 0;
- char *buf = (char *)malloc(16384);
- char userAgentFromHeader[1024] = "";
- if(!buf) goto last;
-
- while(fgets(buf,16384,fpr)) {
- //fprintf(stderr,"%s",buf);
- if(!strcmp("\r\n",buf)) break;
- if(!strncasecmp("Range:",buf,6)) {
- if(strstr(buf+7,"bytes=") && !strchr(buf+7, ',')) {
- char *ptr = buf+13;
- if(*ptr == '-') {
- rangeStart = atoi(ptr);
- }
- else {
- rangeStart = strtol(ptr, &ptr, 10);
- if(*ptr == '-') ptr++;
- if(*ptr && *ptr != '\r') {
- rangeEnd = strtol(ptr, NULL, 10);
- if(rangeEnd && rangeStart > rangeEnd) {
- sendResponse(416, "Requested range not satisfiable", fpw);
- statusCode = 416;
- goto last;
- }
- }
- }
- //fprintf(stderr, "range=%ld-%ld\n",rangeStart,rangeEnd);
- }
- else {
- sendResponse(416, "Requested range not satisfiable", fpw);
- statusCode = 416;
- goto last;
- }
- }
- else if(!strncasecmp("If-Modified-Since:",buf,18)) {
- struct tm time_ = {};
- strptime(buf+19,httpTimestampFmt,&time_);
- ifModifiedSince = mktime(&time_);
- }
- else if(!strncasecmp("User-Agent:",buf,11)) {
- int i=0;
- char *ptr = buf+12;
- while(*ptr != '\r' && *ptr != '\n' && i < 1023) userAgentFromHeader[i++] = *ptr++;
- userAgentFromHeader[i] = 0;
- }
- }
- if(rangeStart > 0) {
- PBBS2chProxyThreadInfo info;
- pthread_mutex_lock(mutex);
- BBS2chProxyThreadCache::iterator it = threadCache->find(threadKey);
- if(it != threadCache->end()) {
- info = it->second;
- }
- pthread_mutex_unlock(mutex);
- log_printf(5,"range request from %ld bytes\n",rangeStart);
- if(info) {
- int from = info->lastResNum;
- int alreadyRead = info->cachedSize;
- int lastResLength = info->cachedData->length;
- log_printf(5,"hit %s: cached %d bytes, last res size %d\n",threadKey.c_str(),alreadyRead,lastResLength);
- if(rangeStart <= alreadyRead && rangeStart >= alreadyRead - lastResLength) {
- CURL *curl = curl_easy_init();
- if(curl) {
- CURLcode res;
- DataStorage *dat = new DataStorage();
- log_printf(5,"partial access from res num %d\n",from);
- snprintf(buf,16384,"%s%d-n",url,from);
- if(curl_share) curl_easy_setopt(curl, CURLOPT_SHARE, curl_share);
- curl_easy_setopt(curl, CURLOPT_URL, buf);
- curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
- curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
- curl_easy_setopt(curl, CURLOPT_ENCODING, "");
- curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback_download);
- curl_easy_setopt(curl, CURLOPT_WRITEDATA, dat);
- curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
- curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
- curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
- if(force_ipv4) curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
- if(proxy_server) {
- curl_easy_setopt(curl, CURLOPT_PROXY, proxy_server);
- curl_easy_setopt(curl, CURLOPT_PROXYPORT, proxy_port);
- curl_easy_setopt(curl, CURLOPT_PROXYTYPE, proxy_type);
- }
- if(user_agent) {
- curl_easy_setopt(curl, CURLOPT_USERAGENT, user_agent);
- }
- else if(userAgentFromHeader[0]) {
- curl_easy_setopt(curl, CURLOPT_USERAGENT, userAgentFromHeader);
- }
- res = curl_easy_perform(curl);
- if(res == CURLE_OK) {
- curl_easy_getinfo(curl,CURLINFO_RESPONSE_CODE, &statusCode);
- curl_easy_cleanup(curl);
- if(statusCode == 200 && dat->length) {
- DataStorage *updated = html2dat(dat, from, &lastModified, true);
- if(ifModifiedSince && lastModified && updated && updated->length == lastResLength) {
- struct tm time_ = {};
- gmtime_r(&lastModified,&time_);
- time_t tmp = mktime(&time_);
- if(ifModifiedSince >= tmp) {
- sendResponse(304, "Not Modified", fpw);
- log_printf(5,"not modified!\n");
- delete updated;
- delete dat;
- statusCode = 304;
- goto last;
- }
- }
- if(updated && updated->length && updated->length >= lastResLength) {
- html = new DataStorage(alreadyRead - lastResLength);
- html->appendBytes(updated->bytes, updated->length);
- if(!rangeEnd) rangeEnd = html->length - 1;
- if(rangeStart > rangeEnd) {
- sendResponse(416, "Requested range not satisfiable", fpw);
- delete updated;
- delete dat;
- statusCode = 416;
- goto last;
- }
- statusCode = 206;
- log_printf(5,"cache hit; reconstructed data length:%ld\n",(long)html->length);
- }
- else {
- log_printf(5,"cache misshit?\n");
- sendResponse(416, "Requested range not satisfiable", fpw);
- delete updated;
- delete dat;
- statusCode = 416;
- goto last;
- }
- delete updated;
- }
- }
- else {
- log_printf(0,"curl error: %s (%s)\n",curl_easy_strerror(res),buf);
- curl_easy_cleanup(curl);
- }
- delete dat;
- if(html) goto resp;
- }
- }
- else {
- log_printf(5,"invalid cache contents\n");
- pthread_mutex_lock(mutex);
- BBS2chProxyThreadCache::iterator it = threadCache->find(threadKey);
- if(it != threadCache->end()) {
- threadCache->erase(it);
- }
- pthread_mutex_unlock(mutex);
- }
- }
- }
-
- {
- CURL *curl = curl_easy_init();
- if(curl) {
- CURLcode res;
- DataStorage *dat = new DataStorage();
- if(curl_share) curl_easy_setopt(curl, CURLOPT_SHARE, curl_share);
- curl_easy_setopt(curl, CURLOPT_URL, url);
- curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
- curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
- curl_easy_setopt(curl, CURLOPT_ENCODING, "");
- curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback_download);
- curl_easy_setopt(curl, CURLOPT_WRITEDATA, dat);
- curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
- curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
- curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
- if(force_ipv4) curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
- if(proxy_server) {
- curl_easy_setopt(curl, CURLOPT_PROXY, proxy_server);
- curl_easy_setopt(curl, CURLOPT_PROXYPORT, proxy_port);
- curl_easy_setopt(curl, CURLOPT_PROXYTYPE, proxy_type);
- }
- if(user_agent) {
- curl_easy_setopt(curl, CURLOPT_USERAGENT, user_agent);
- }
- else if(userAgentFromHeader[0]) {
- curl_easy_setopt(curl, CURLOPT_USERAGENT, userAgentFromHeader);
- }
- res = curl_easy_perform(curl);
- if(res != CURLE_OK) {
- log_printf(0,"curl error: %s (%s)\n",curl_easy_strerror(res),url);
- sendResponse(503, "Service Unavailable", fpw);
- curl_easy_cleanup(curl);
- delete dat;
- statusCode = 503;
- goto last;
- }
- curl_easy_getinfo(curl,CURLINFO_RESPONSE_CODE, &statusCode);
- curl_easy_cleanup(curl);
-
- if(statusCode == 200) {
- html = html2dat(dat, 1, &lastModified, false);
- }
- delete dat;
- }
-
- if(!html || !html->length) {
- sendResponse(503, "Service Unavailable", fpw);
- statusCode = 503;
- goto last;
- }
- if((rangeStart || rangeEnd) && html && html->length) {
- if(!rangeEnd) rangeEnd = html->length - 1;
- if(rangeStart < 0) rangeStart = html->length + rangeStart;
- if(rangeStart < html->length && rangeEnd < html->length && rangeStart <= rangeEnd) {
- statusCode = 206;
- }
- else {
- if(ifModifiedSince && lastModified && rangeStart == html->length) {
- struct tm time_ = {};
- gmtime_r(&lastModified,&time_);
- time_t tmp = mktime(&time_);
- if(ifModifiedSince >= tmp) {
- sendResponse(304, "Not Modified", fpw);
- log_printf(5,"not modified!\n");
- statusCode = 304;
- goto last;
- }
- }
- sendResponse(416, "Requested range not satisfiable", fpw);
- statusCode = 416;
- goto last;
- }
- }
- }
- resp:
- if(statusCode == 206) sendBasicHeaders(statusCode,"Partial Content",fpw);
- else sendBasicHeaders(statusCode,"OK",fpw);
- if(0 > fprintf(fpw,"Content-Type: text/plain\r\n")) goto last;
- if(0 > fprintf(fpw,"Accept-Ranges: bytes\r\n")) goto last;
- if(statusCode == 206) {
- if(0 > fprintf(fpw,"Content-Range: bytes %ld-%ld/%ld\r\n",rangeStart,rangeEnd,(long)html->length)) goto last;
- //fprintf(stderr,"Content-Length: %ld\r\n",rangeEnd - rangeStart + 1);
- //fprintf(stderr,"Content-Range: bytes %ld-%ld/%ld\r\n",rangeStart,rangeEnd,(long)html->length);
- DataStorage *newHtml = new DataStorage();
- newHtml->appendBytes(html->bytes+rangeStart, rangeEnd - rangeStart + 1);
- delete html;
- html = newHtml;
- }
- if(0 > fprintf(fpw,"Content-Length: %ld\r\n",(long)html->length)) goto last;
- if(lastModified) {
- struct tm time_ = {};
- char date[256];
- gmtime_r(&lastModified,&time_);
- strftime(date,256,httpTimestampFmt,&time_);
- if(0 > fprintf(fpw,"Last-Modified: %s\r\n",date)) goto last;
- //fprintf(stderr,"Last-Modified: %s\r\n",date);
- }
- if(0 > fprintf(fpw,"\r\n")) goto last;
-
- if(html && statusCode >= 200 && statusCode < 300 && strcasecmp(method, "HEAD")) {
- if(html->length > fwrite(html->bytes,1,html->length,fpw)) goto last;
- }
- fflush(fpw);
-
- last:
- if(buf) free(buf);
- if(html) delete html;
- return statusCode;
- }
- DataStorage *BBS2chProxyConnection::html2dat_old(DataStorage *html, int startResNum, time_t *lastModified, bool useCache)
- {
- char *ptr = html->bytes;
- char *end = html->bytes + html->length - 1;
- DataStorage *txt = new DataStorage();
- int res = startResNum, i=0;
- char signature[32];
- char title[1024];
- int cachedSize = 0;
- bool bbspink = strstr(threadKey.c_str(),"bbspink.com") ? true : false;
-
- ptr = (char *)memmem_priv(ptr, end-ptr+1, "<title>", 7);
- if(!ptr) {
- delete txt;
- return NULL;
- }
- ptr += 7;
- while(1) {
- if(*ptr == '<') {
- if(!strncasecmp(ptr,"</title>",8)) {
- ptr += 8;
- break;
- }
- else title[i++] = *ptr++;
- }
- else title[i++] = *ptr++;
- }
- title[i] = 0;
-
- snprintf(signature,32,"<dt>%d ",res);
- ptr = (char *)memmem_priv(ptr, end-ptr+1, signature, strlen(signature));
- if(!ptr) {
- delete txt;
- return NULL;
- }
-
- unsigned char *buffer = (unsigned char *)malloc(65536+1024+1024+1024+2048);
- if(!buffer) {
- delete txt;
- return NULL;
- }
-
- unsigned char *body = buffer;
- char *mail = (char *)body + 65536;
- char *name = mail + 1024;
- char *date = name + 1024;
- char *encrypted = date + 1024;
-
- while(ptr < end) {
- //fprintf(stderr,"%s\n",signature);
- DataStorage *resData = new DataStorage();
- i=0;
- mail[0] = 0;
- ptr = strstr(ptr,signature);
- ptr += strlen(signature);
- while(*ptr != '<') ptr++;
- ptr++;
- const char *endStr;
- if(*ptr == 'a' || *ptr == 'A') {
- replay:
- // has mail
- while(*ptr != '"') ptr++;
- ptr++;
- if(!strncmp(ptr,"/cdn-cgi/l/email-protection#",28)) {
- ptr += 28;
- while(*ptr != '"' && *ptr != 'X') encrypted[i++] = *ptr++;
- encrypted[i] = 0;
- i = decryptMail((unsigned char *)mail,encrypted);
- int reconstruct_len = *ptr == 'X' ? i + 15 : i + 16;
- ptr -= reconstruct_len;
- char *start = ptr;
- memcpy(ptr, "<a href=\"mailto:", 16);
- ptr += 16;
- memcpy(ptr, mail, i);
- ptr = start;
- i=0;
- goto replay;
- }
- else {
- if(!strncmp(ptr,"mailto:",7)) ptr += 7;
- while(*ptr != '"') mail[i++] = *ptr++;
- mail[i] = 0;
- }
- endStr = "</a>";
- }
- else if(*ptr == 'b') {
- endStr = NULL;
- }
- else {
- endStr = "</font>";
- }
-
- if(endStr) {
- ptr = strstr(ptr,"<b>");
- ptr += 3;
- }
- else {
- ptr = strchr(ptr,'>');
- ptr++;
- }
-
- i=0;
- while(1) {
- if(*ptr == '<') {
- if(!strncasecmp(ptr,"</b>",4) && (!endStr || !strncasecmp(ptr+4,endStr,strlen(endStr)))) {
- ptr += 4;
- if(endStr) ptr += strlen(endStr);
- break;
- }
- else if(!strncmp(ptr,"<span class=\"__cf_email__\"",26)) {
- int j=0;
- ptr = strstr(ptr,"data-cfemail=\"");
- ptr += 14;
- while(*ptr != '"') encrypted[j++] = *ptr++;
- encrypted[j] = 0;
- j = decryptMail((unsigned char *)name+i,encrypted);
- i += j;
- ptr = strstr(ptr,"</script>");
- ptr += 9;
- }
- else name[i++] = *ptr++;
- }
- else name[i++] = *ptr++;
- }
-
- resData->appendBytes(name, i);
- resData->appendBytes("<>", 2);
- if(mail[0]) resData->appendBytes(mail ,strlen(mail));
- resData->appendBytes("<>", 2);
-
- ptr += 2;
- i=0;
- while(1) {
- if(*ptr == '<') {
- if(!strncasecmp(ptr,"<dd>",4)) {
- ptr += 4;
- break;
- }
- else if(!strncmp(ptr,"<a href=\"javascript:be(",23)) {
- memcpy(date+i,"BE:",3);
- ptr += 23;
- i += 3;
- while(*ptr != ')') date[i++] = *ptr++;
- date[i++] = '-';
- ptr = strchr(ptr,'?');
- ptr++;
- char *tmp = strstr(ptr,"</a>");
- memcpy(date+i,ptr,tmp-ptr);
- i += tmp-ptr;
- ptr = tmp + 4;
- }
- else date[i++] = *ptr++;
- }
- else date[i++] = *ptr++;
- }
-
- resData->appendBytes(date ,i);
- resData->appendBytes("<>", 2);
-
- i=0;
- while(1) {
- if(*ptr == '<') {
- if(!strncasecmp(ptr,"<br><br>\n",9)) {
- ptr += 9;
- break;
- }
- else if(!strncasecmp(ptr,"<dt>",4) || !strncasecmp(ptr,"</dl>",5)) {
- while(i>0 &&body[i-1] == '\n') i--;
- break;
- }
- else if(!strncmp(ptr,"<span class=\"__cf_email__\"",26) || !strncmp(ptr,"<a class=\"__cf_email__\"",23)) {
- int j=0;
- ptr = strstr(ptr,"data-cfemail=\"");
- ptr += 14;
- while(*ptr != '"') encrypted[j++] = *ptr++;
- encrypted[j] = 0;
- j = decryptMail(body+i,encrypted);
- i += j;
- ptr = strstr(ptr,"</script>");
- ptr += 9;
- }
- else if(!strncmp(ptr,"<a href=\"http",13)) {
- ptr = strchr(ptr,'>');
- ptr++;
- char *link = ptr;
- ptr = strstr(link,"</a>");
- memcpy(body+i,link,ptr-link);
- i += ptr-link;
- ptr += 4;
- }
- else if(!strncmp(ptr,"<img src=\"",10)) {
- ptr += 10;
- char *img = ptr;
- ptr = strstr(img,"\">");
- memcpy(body+i,img,ptr-img);
- if(memmem_priv(img,ptr-img,"/img.2ch.net",12) || memmem_priv(img,ptr-img,"/img.5ch.net",12) || memmem_priv(img,ptr-img,"/o.8ch.net",10) || memmem_priv(img,ptr-img,"/o.5ch.net",10)) {
- int length = ptr-img;
- while(*img != '/') {
- img++;
- length--;
- }
- memcpy(body+i,"sssp:",5);
- memcpy(body+i+5,img,length);
- i += length + 5;
- }
- else i += ptr-img;
- ptr += 2;
- }
- else if(!bbspink && !strncmp(ptr,"<br>",4)) {
- if(i>5 && !strncmp((char *)body+i-5,"<br> ",5)) {
- memcpy(body+i," <br>",5);
- i += 5;
- }
- else {
- memcpy(body+i,"<br>",4);
- i += 4;
- }
- ptr += 4;
- }
- else body[i++] = *ptr++;
- }
- else if(!bbspink && *ptr == ' ') {
- if(*(ptr+1) == ' ') ptr++;
- else body[i++] = *ptr++;
- }
- else body[i++] = *ptr++;
- }
-
- resData->appendBytes(body ,i);
- resData->appendBytes("<>", 2);
- if(res == 1) resData->appendBytes(title ,strlen(title));
- resData->appendBytes("\n" ,1);
-
- if(useCache && res == startResNum) {
- PBBS2chProxyThreadInfo info;
- bool hit = false;
- pthread_mutex_lock(mutex);
- BBS2chProxyThreadCache::iterator it = threadCache->find(threadKey);
- if(it != threadCache->end()) {
- info = it->second;
- threadCache->erase(it);
- }
- pthread_mutex_unlock(mutex);
- if(info) {
- log_printf(5,"cache hit");
- if(info->cachedData->length == resData->length) {
- log_printf(5,"... size match");
- if(!memcmp(info->cachedData->bytes,resData->bytes,resData->length)) {
- log_printf(5,"... content match");
- hit = true;
- cachedSize = info->cachedSize - resData->length;
- }
- }
- log_printf(5,"\n");
- }
- if(!hit) {
- delete resData;
- free(buffer);
- return NULL;
- }
- }
-
- txt->appendBytes(resData->bytes, resData->length);
- res++;
- while(*ptr == '\n' || *ptr == '\r') ptr++;
- snprintf(signature,32,"<dt>%d ",res);
- if(!memmem_priv(ptr, end-ptr+1, signature, strlen(signature))) {
- PBBS2chProxyThreadInfo info(new BBS2chProxyThreadInfo());
- info->lastResNum = res-1;
- info->cachedSize = txt->length+cachedSize;
- info->cachedData = resData;
- pthread_mutex_lock(mutex);
- threadCache->insert(std::make_pair(threadKey,info));
- pthread_mutex_unlock(mutex);
- log_printf(5,"cached thread %s (%ld bytes)\n",threadKey.c_str(),(long)resData->length);
-
- if(lastModified) {
- *lastModified = 0;
- char formattedDate[256];
- char *ptr;
- ptr = date;
- int year = strtol(ptr,&ptr,10);
- if(*ptr != '/') break;
- ptr++;
- int month = strtol(ptr,&ptr,10);
- if(*ptr != '/') break;
- ptr++;
- int day = strtol(ptr,&ptr,10);
- if(!*ptr) break;
- while(*ptr != ' ' && *ptr != 0) ptr++;
- if(!*ptr) break;
- ptr++;
- int hour = strtol(ptr,&ptr,10);
- if(*ptr != ':') break;
- ptr++;
- int minutes = strtol(ptr,&ptr,10);
- if(*ptr != ':') break;
- ptr++;
- int seconds = strtol(ptr,&ptr,10);
- if(!(month>0 && month<13) || !(day>0 && day<32)) break;
- if(year < 100) year += 2000;
- snprintf(formattedDate,256,"%d/%d/%d %02d:%02d:%02d JST",year,month,day,hour,minutes,seconds);
- //fprintf(stderr,"%s\n",formattedDate);
-
- struct tm time = {};
- strptime(formattedDate,threadTimestampFmt,&time);
- *lastModified = mktime(&time);
- //gmtime_r(lastModified,&time);
- //strftime(formattedDate,256,httpTimestampFmt,&time);
- //fprintf(stderr,"%s\n",formattedDate);
- }
- //fprintf(stderr,"not found,%ld\n",end-ptr+1);
- break;
- }
- delete resData;
- }
-
- free(buffer);
- return txt;
- }
- DataStorage *BBS2chProxyConnection::html2dat(DataStorage *html, int startResNum, time_t *lastModified, bool useCache)
- {
- char *ptr = html->bytes;
- char *end = html->bytes + html->length - 1;
- DataStorage *txt = new DataStorage();
- int res = startResNum, i=0;
- char signature[64];
- char title[1024];
- int cachedSize = 0;
- char signatureTag[32];
- char closeTag[32];
- int closeTagLen;
-
- ptr = (char *)memmem_priv(ptr, end-ptr+1, "<h1 class=\"title\">", 18);
- if(!ptr) {
- delete txt;
- return html2dat_old(html, startResNum, lastModified, useCache);
- }
- else {
- char *ptr2 = (char *)memmem_priv(ptr, end-ptr+1, " class=\"post\"", 13);
- if(ptr2) {
- char *tmp = ptr2;
- *ptr2 = 0;
- while(*ptr2 != '<') ptr2--;
- strcpy(signatureTag, ptr2);
- *tmp = ' ';
- }
- else {
- delete txt;
- return NULL;
- }
- /*char *ptr2 = (char *)memmem_priv(ptr, end-ptr+1, "<dl class=\"post\"", 16);
- if(ptr2) {
- delete txt;
- return html2dat_pink(html, startResNum, lastModified, useCache);
- }*/
- }
-
- ptr += 18;
- while(1) {
- if(*ptr == '<') {
- if(!strncasecmp(ptr,"</h1>",5)) {
- ptr += 5;
- break;
- }
- else title[i++] = *ptr++;
- }
- else if(*ptr == '\n') break;
- else title[i++] = *ptr++;
- }
- title[i] = 0;
-
- snprintf(signature,32,"%s class=\"post\" id=\"%d\"",signatureTag,res);
- ptr = (char *)memmem_priv(ptr, end-ptr+1, signature, strlen(signature));
- if(!ptr) {
- delete txt;
- return NULL;
- }
-
- unsigned char *buffer = (unsigned char *)malloc(65536+1024+1024+1024+2048);
- if(!buffer) {
- delete txt;
- return NULL;
- }
-
- unsigned char *body = buffer;
- char *mail = (char *)body + 65536;
- char *name = mail + 1024;
- char *date = name + 1024;
- char *encrypted = date + 1024;
-
- while(ptr < end) {
- //fprintf(stderr,"%s\n",signature);
- DataStorage *resData = new DataStorage();
- i=0;
- mail[0] = 0;
- ptr = strstr(ptr," class=\"name\"><b>");
- if(ptr) {
- char *tmp = ptr;
- *ptr = 0;
- while(*ptr != '<') ptr--;
- snprintf(closeTag,32,"</%s>",ptr+1);
- closeTagLen = strlen(closeTag);
- ptr = tmp + 17;
- }
- else {
- delete resData;
- break;
- }
-
- char endStr[64];
- if(!strncmp(ptr,"<a href=\"mailto:",16)) {
- replay:
- // has mail
- while(*ptr != '"') ptr++;
- ptr++;
- if(!strncmp(ptr,"/cdn-cgi/l/email-protection#",28)) {
- ptr += 28;
- while(*ptr != '"' && *ptr != 'X') encrypted[i++] = *ptr++;
- encrypted[i] = 0;
- i = decryptMail((unsigned char *)mail,encrypted);
- int reconstruct_len = *ptr == 'X' ? i + 15 : i + 16;
- ptr -= reconstruct_len;
- char *start = ptr;
- memcpy(ptr, "<a href=\"mailto:", 16);
- ptr += 16;
- memcpy(ptr, mail, i);
- ptr = start;
- i=0;
- goto replay;
- }
- else {
- if(!strncmp(ptr,"mailto:",7)) ptr += 7;
- while(1) {
- if(*ptr == '<' && !strncmp(ptr,"<a href=\"",9)) {
- ptr = strchr(ptr,'>');
- ptr++;
- char *link = ptr;
- ptr = strstr(link,"</a>");
- memcpy(mail+i,link,ptr-link);
- i += ptr-link;
- ptr += 4;
- }
- else if(*ptr == '"') break;
- else mail[i++] = *ptr++;
- }
- //while(*ptr != '"') mail[i++] = *ptr++;
- mail[i] = 0;
- }
- snprintf(endStr,64,"</a></b>%s",closeTag);
- while(*ptr != '>') ptr++;
- ptr++;
- }
- /* we do not have to handle this special case because read.cgi on bbspink doesn't
- emit font tags anymore and it conflicts with text decorations using "melon point" */
- /*else if(!strncmp(ptr,"<font",5)) {
- snprintf(endStr,64,"</font></b>%s",closeTag);
- while(*ptr != '>') ptr++;
- ptr++;
- }*/
- else {
- snprintf(endStr,64,"</b>%s",closeTag);
- }
-
- i=0;
- while(1) {
- if(*ptr == '<') {
- if(!strncmp(ptr,endStr,strlen(endStr))) {
- ptr += strlen(endStr);
- break;
- }
- else if(!strncmp(ptr,"<span class=\"__cf_email__\"",26)) {
- int j=0;
- ptr = strstr(ptr,"data-cfemail=\"");
- ptr += 14;
- while(*ptr != '"') encrypted[j++] = *ptr++;
- encrypted[j] = 0;
- j = decryptMail((unsigned char *)name+i,encrypted);
- i += j;
- ptr = strstr(ptr,"</script>");
- ptr += 9;
- }
- else if(!strncmp(ptr,"<a href=\"",9)) {
- ptr = strchr(ptr,'>');
- ptr++;
- char *link = ptr;
- ptr = strstr(link,"</a>");
- memcpy(name+i,link,ptr-link);
- i += ptr-link;
- ptr += 4;
- }
- else name[i++] = *ptr++;
- }
- else name[i++] = *ptr++;
- }
-
- resData->appendBytes(name, i);
- resData->appendBytes("<>", 2);
- if(mail[0]) resData->appendBytes(mail ,strlen(mail));
- resData->appendBytes("<>", 2);
-
- ptr = strstr(ptr," class=\"date\">");
- if(ptr) {
- char *tmp = ptr;
- *ptr = 0;
- while(*ptr != '<') ptr--;
- snprintf(closeTag,32,"</%s>",ptr+1);
- closeTagLen = strlen(closeTag);
- ptr = tmp + 14;
- }
- else {
- delete resData;
- break;
- }
-
- i=0;
- while(1) {
- if(*ptr == '<') {
- if(!strncasecmp(ptr,closeTag,closeTagLen)) {
- ptr += closeTagLen;
- break;
- }
- else date[i++] = *ptr++;
- }
- else date[i++] = *ptr++;
- }
-
- if(!strncmp(ptr,"<div class=\"uid",15) || !strncmp(ptr,"<span class=\"uid",16)) {
- char *tmp = ptr+1;
- while(*ptr != ' ') ptr++;
- *ptr = 0;
- snprintf(closeTag,32,"</%s>",tmp);
- closeTagLen = strlen(closeTag);
- ptr += 11;
- while(*ptr != '>') ptr++;
- ptr++;
- date[i++] = ' ';
- while(1) {
- if(*ptr == '<') {
- if(!strncasecmp(ptr,closeTag,closeTagLen)) {
- ptr += closeTagLen;
- break;
- }
- else date[i++] = *ptr++;
- }
- else date[i++] = *ptr++;
- }
- }
-
- if(!strncmp(ptr,"<div class=\"be",14) || !strncmp(ptr,"<span class=\"be",15)) {
- ptr += 14;
- while(*ptr != '>') ptr++;
- ptr++;
- if(!strncmp(ptr,"<a href=\"",9)) {
- ptr += 9;
- while(*ptr != '/' && *ptr != '"') ptr++;
- if(*ptr == '/' && (!strncmp(ptr,"//be.2ch.net/user/",18) || !strncmp(ptr,"//be.5ch.net/user/",18))) {
- memcpy(date+i," BE:",4);
- i += 4;
- ptr += 18;
- while(*ptr != '"') date[i++] = *ptr++;
- date[i++] = '-';
- ptr = strchr(ptr,'?');
- ptr++;
- char *tmp = strstr(ptr,"</a>");
- memcpy(date+i,ptr,tmp-ptr);
- i += tmp-ptr;
- ptr = tmp + 4;
- }
- }
- }
-
- resData->appendBytes(date ,i);
- resData->appendBytes("<>", 2);
-
- if(!strcmp(signatureTag,"<div")) {
- ptr = strstr(ptr,"<div class=\"message\">");
- if(!ptr) {
- delete resData;
- break;
- }
- else {
- ptr += 21;
- if(!strncasecmp(ptr,"<span class=\"escaped\">",22)) {
- if(!strncasecmp(ptr+22,"<span class=\"AA\">",17)) {
- strcpy(closeTag,"</span></span></div>");
- closeTagLen = 20;
- ptr += 22+17;
- }
- else {
- strcpy(closeTag,"</span></div>");
- closeTagLen = 13;
- ptr += 22;
- }
- }
- else {
- strcpy(closeTag,"</div>");
- closeTagLen = 6;
- }
- }
- }
- else {
- ptr = strstr(ptr,"<dd class=\"thread_in\">");
- if(!ptr) {
- delete resData;
- break;
- }
- strcpy(closeTag,"</dd>");
- closeTagLen = 5;
- ptr += 22;
- }
- i=0;
- while(1) {
- if(*ptr == '<') {
- if(!strncasecmp(ptr,closeTag,closeTagLen)) {
- ptr += closeTagLen;
- break;
- }
- else if(!strncmp(ptr,"<span class=\"__cf_email__\"",26) || !strncmp(ptr,"<a class=\"__cf_email__\"",23)) {
- int j=0;
- ptr = strstr(ptr,"data-cfemail=\"");
- ptr += 14;
- while(*ptr != '"') encrypted[j++] = *ptr++;
- encrypted[j] = 0;
- j = decryptMail(body+i,encrypted);
- i += j;
- ptr = strstr(ptr,"</script>");
- ptr += 9;
- }
- else if(!strncmp(ptr,"<a ",3)) {
- char *tmp = strchr(ptr,'>');
- char *href = (char *)memmem_priv(ptr,tmp-ptr,"href=\"",6);
- char *link = tmp+1;
- if(href && !strncmp(link,">>",8) && memmem_priv(href,link-href,"test/read.cgi/",14)) {
- while(ptr < link) {
- if(!strncmp(ptr," class=\"",8)) {
- ptr += 8;
- while(*ptr != '"' && *ptr != '>') ptr++;
- if(*ptr == '"') ptr++;
- }
- else body[i++] = *ptr++;
- }
- }
- else {
- ptr = strstr(link,"</a>");
- memcpy(body+i,link,ptr-link);
- i += ptr-link;
- ptr += 4;
- }
- }
- else if(!strncmp(ptr,"<img src=\"",10)) {
- ptr += 10;
- char *img = ptr;
- ptr = strstr(img,"\">");
- memcpy(body+i,img,ptr-img);
- if(memmem_priv(img,ptr-img,"/img.2ch.net",12) || memmem_priv(img,ptr-img,"/img.5ch.net",12) || memmem_priv(img,ptr-img,"/o.8ch.net",10) || memmem_priv(img,ptr-img,"/o.5ch.net",10)) {
- int length = ptr-img;
- while(*img != '/') {
- img++;
- length--;
- }
- memcpy(body+i,"sssp:",5);
- memcpy(body+i+5,img,length);
- i += length + 5;
- }
- else i += ptr-img;
- ptr += 2;
- }
- else if(!strncmp(ptr,"<br>",4)) {
- if(i>5 && !strncmp((char *)body+i-5,"<br> ",5)) {
- memcpy(body+i," <br>",5);
- i += 5;
- }
- else {
- memcpy(body+i,"<br>",4);
- i += 4;
- }
- ptr += 4;
- }
- else body[i++] = *ptr++;
- }
- else body[i++] = *ptr++;
- }
-
- resData->appendBytes(body ,i);
- resData->appendBytes("<>", 2);
- if(res == 1) resData->appendBytes(title ,strlen(title));
- resData->appendBytes("\n" ,1);
-
- if(useCache && res == startResNum) {
- PBBS2chProxyThreadInfo info;
- bool hit = false;
- pthread_mutex_lock(mutex);
- BBS2chProxyThreadCache::iterator it = threadCache->find(threadKey);
- if(it != threadCache->end()) {
- info = it->second;
- threadCache->erase(it);
- }
- pthread_mutex_unlock(mutex);
- if(info) {
- log_printf(5,"cache hit");
- if(info->cachedData->length == resData->length) {
- log_printf(5,"... size match");
- if(!memcmp(info->cachedData->bytes,resData->bytes,resData->length)) {
- log_printf(5,"... content match");
- hit = true;
- cachedSize = info->cachedSize - resData->length;
- }
- }
- log_printf(5,"\n");
- }
- if(!hit) {
- delete resData;
- free(buffer);
- return NULL;
- }
- }
-
- txt->appendBytes(resData->bytes, resData->length);
- res++;
- while(*ptr == '\n' || *ptr == '\r') ptr++;
- snprintf(signature,64,"%s class=\"post\" id=\"",signatureTag);
- ptr = (char *)memmem_priv(ptr, end-ptr+1, signature, strlen(signature));
- if(ptr) {
- int next = atoi(ptr+strlen(signature));
- if(next >= res) {
- while(next > res) {
- txt->appendBytes("broken<><>broken<> broken <>\n", 29);
- res++;
- }
- }
- else ptr = NULL;
- }
- if(!ptr) {
- PBBS2chProxyThreadInfo info(new BBS2chProxyThreadInfo());
- info->lastResNum = res-1;
- info->cachedSize = txt->length+cachedSize;
- info->cachedData = resData;
- pthread_mutex_lock(mutex);
- threadCache->insert(std::make_pair(threadKey,info));
- pthread_mutex_unlock(mutex);
- log_printf(5,"cached thread %s (%ld bytes)\n",threadKey.c_str(),(long)resData->length);
-
- if(lastModified) {
- *lastModified = 0;
- char formattedDate[256];
- char *ptr;
- ptr = date;
- int year = strtol(ptr,&ptr,10);
- if(*ptr != '/') break;
- ptr++;
- int month = strtol(ptr,&ptr,10);
- if(*ptr != '/') break;
- ptr++;
- int day = strtol(ptr,&ptr,10);
- if(!*ptr) break;
- while(*ptr != ' ' && *ptr != 0) ptr++;
- if(!*ptr) break;
- ptr++;
- int hour = strtol(ptr,&ptr,10);
- if(*ptr != ':') break;
- ptr++;
- int minutes = strtol(ptr,&ptr,10);
- if(*ptr != ':') break;
- ptr++;
- int seconds = strtol(ptr,&ptr,10);
- if(!(month>0 && month<13) || !(day>0 && day<32)) break;
- if(year < 100) year += 2000;
- snprintf(formattedDate,256,"%d/%d/%d %02d:%02d:%02d JST",year,month,day,hour,minutes,seconds);
- //fprintf(stderr,"%s\n",formattedDate);
-
- struct tm time = {};
- strptime(formattedDate,threadTimestampFmt,&time);
- *lastModified = mktime(&time);
- //gmtime_r(lastModified,&time);
- //strftime(formattedDate,256,httpTimestampFmt,&time);
- //fprintf(stderr,"%s\n",formattedDate);
- }
- //fprintf(stderr,"not found,%ld\n",end-ptr+1);
- break;
- }
- delete resData;
- }
-
- free(buffer);
- return txt;
- }
- int BBS2chProxyConnection::datProxyAPI(const char *url, const char *method)
- {
- long statusCode = 0;
- std::string postBody = auth->requestBodyForURL(url);
- if(postBody.empty()) {
- sendResponse(401, "Unauthorized", fpw);
- return 401;
- }
- CURL *curl = curl_easy_init();
- char *buf = (char *)malloc(16384);
- if(curl) {
- CURLcode res;
- struct curl_slist *headers = NULL;
- DataStorage *receivedHeader = new DataStorage();
- DataStorage *receivedBody = new DataStorage();
- while(fgets(buf,16384,fpr)) {
- //fprintf(stderr,"%s",buf);
- if(!strcmp("\r\n",buf)) break;
- else if(!strncasecmp("Range:",buf,6)
- || !strncasecmp("If-Modified-Since:",buf,18)
- || !strncasecmp("Accept-Encoding:",buf,16)) {
- char *ptr;
- ptr = strchr(buf, '\r');
- if(!ptr) ptr = strchr(buf, '\n');
- if(!ptr) continue;
- *ptr = 0;
- headers = curl_slist_append(headers, buf);
- }
- }
- if(x_2ch_ua_dat) headers = curl_slist_append(headers, x_2ch_ua_dat);
-
- if(curl_share) curl_easy_setopt(curl, CURLOPT_SHARE, curl_share);
- curl_easy_setopt(curl, CURLOPT_URL, url);
- curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
- curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
- curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
- curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback_download);
- curl_easy_setopt(curl, CURLOPT_WRITEDATA, receivedBody);
- curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, header_callback_download);
- curl_easy_setopt(curl, CURLOPT_HEADERDATA, receivedHeader);
- curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
- curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
- curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
- if(force_ipv4) curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
- if(proxy_server) {
- curl_easy_setopt(curl, CURLOPT_PROXY, proxy_server);
- curl_easy_setopt(curl, CURLOPT_PROXYPORT, proxy_port);
- curl_easy_setopt(curl, CURLOPT_PROXYTYPE, proxy_type);
- }
- curl_easy_setopt(curl, CURLOPT_USERAGENT, api_ua_dat?api_ua_dat:"");
- curl_easy_setopt(curl, CURLOPT_POST, 1L);
- #if LIBCURL_VERSION_NUM >= 0x071101
- curl_easy_setopt(curl, CURLOPT_COPYPOSTFIELDS, postBody.c_str());
- #else
- curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postBody.c_str());
- #endif
- //return;
- res = curl_easy_perform(curl);
- if(res == CURLE_OK) {
- curl_easy_getinfo(curl,CURLINFO_RESPONSE_CODE, &statusCode);
- receivedHeader->appendBytes("",1);
- char *ptr = strstr(receivedHeader->bytes,"\r\n\r\n");
- *(ptr+4) = 0;
- int threadStatus = 0;
- for(char *ptr2 = receivedHeader->bytes; ptr2<ptr;) {
- if(!strncasecmp(ptr2, "Thread-Status:", strlen("Thread-Status:"))) {
- ptr2 += strlen("Thread-Status:");
- while(*ptr2 == ' ') ptr2++;
- threadStatus = atoi(ptr2);
- break;
- }
- ptr2 = strstr(ptr2, "\r\n") + 2;
- }
- if(threadStatus == 1) {
- if(ptr+4-receivedHeader->bytes > fwrite(receivedHeader->bytes,1,ptr+4-receivedHeader->bytes,fpw)) goto last;
- fflush(fpw);
- if(receivedBody->length > fwrite(receivedBody->bytes,1,receivedBody->length,fpw)) goto last;
- fflush(fpw);
- goto last;
- }
- else if(threadStatus == 8) {
- sendBasicHeaders(302, "Found", fpw);
- if(0 > fprintf(fpw, "Location: http://www2.2ch.net/live.html\r\n")) goto last;
- if(0 > fprintf(fpw, "\r\n")) goto last;
- fflush(fpw);
- statusCode = 302;
- goto last;
- }
- else {
- if (statusCode < 400) {
- sendResponse(401, "Unauthorized", fpw);
- statusCode = 401;
- }
- else {
- sendResponse(503, "Service Unavailable", fpw);
- statusCode = 503;
- }
- receivedBody->appendBytes("",1);
- if(!strncasecmp(receivedBody->bytes,"ng (",4)) {
- log_printf(0,"API gateway returned error: %s\n",receivedBody->bytes);
- }
- }
- //fprintf(stderr,"%ld\n",statusCode);
- }
- else {
- log_printf(0,"curl error: %s\n",curl_easy_strerror(res));
- sendResponse(503, "Service Unavailable", fpw);
- statusCode = 503;
- }
- last:
- curl_easy_cleanup(curl);
- curl_slist_free_all(headers);
- delete receivedBody;
- delete receivedHeader;
- }
- free(buf);
- return statusCode;
- }
- int BBS2chProxyConnection::bbsmenuProxy(const char *url, const char *method)
- {
- long statusCode = 0;
- DataStorage *dat = new DataStorage();
- DataStorage *outHTML = new DataStorage();
- char *buf = (char *)malloc(16384);
- char userAgentFromHeader[1024] = "";
- CURL *curl = NULL;
- if(!buf) goto last;
-
- while(fgets(buf,16384,fpr)) {
- //fprintf(stderr,"%s",buf);
- if(!strcmp("\r\n",buf)) break;
- else if(!strncasecmp("User-Agent:",buf,11)) {
- int i=0;
- char *ptr = buf+12;
- while(*ptr != '\r' && *ptr != '\n' && i < 1023) userAgentFromHeader[i++] = *ptr++;
- userAgentFromHeader[i] = 0;
- }
- }
- curl = curl_easy_init();
- if(curl) {
- CURLcode res;
- if(curl_share) curl_easy_setopt(curl, CURLOPT_SHARE, curl_share);
- curl_easy_setopt(curl, CURLOPT_URL, url);
- curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
- curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
- curl_easy_setopt(curl, CURLOPT_ENCODING, "");
- curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback_download);
- curl_easy_setopt(curl, CURLOPT_WRITEDATA, dat);
- curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
- curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
- curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
- if(force_ipv4) curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
- if(proxy_server) {
- curl_easy_setopt(curl, CURLOPT_PROXY, proxy_server);
- curl_easy_setopt(curl, CURLOPT_PROXYPORT, proxy_port);
- curl_easy_setopt(curl, CURLOPT_PROXYTYPE, proxy_type);
- }
- if(user_agent) {
- curl_easy_setopt(curl, CURLOPT_USERAGENT, user_agent);
- }
- else if(userAgentFromHeader[0]) {
- curl_easy_setopt(curl, CURLOPT_USERAGENT, userAgentFromHeader);
- }
- res = curl_easy_perform(curl);
- if(res == CURLE_OK) {
- curl_easy_getinfo(curl,CURLINFO_RESPONSE_CODE, &statusCode);
- if(statusCode == 200 && dat->length) {
- dat->appendBytes("",1);
- dat->length--;
- char *ptr = dat->bytes;
- while(*ptr) {
- if(!strncasecmp(ptr,"<a href=",8)) {
- char *start = ptr;
- char *end = strchr(ptr+8,'>');
- ptr = strstr(ptr+8,"://");
- if(ptr && ptr < end) {
- char *protocol = ptr;
- char *end2 = strchr(ptr+3,'/');
- ptr = strstr(protocol+3,"5ch.net");
- if(ptr && ptr < end2 && (*(ptr-1)=='.' || *(ptr-1)=='/')) {
- memcpy(ptr,"2ch",3);
- if(*(protocol-1) == 's') outHTML->appendBytes(start, protocol-start-1);
- else outHTML->appendBytes(start, protocol-start);
- outHTML->appendBytes(protocol, end-protocol);
- ptr = end;
- continue;
- }
- ptr = strstr(protocol+3,"bbspink.com");
- if(ptr && ptr < end2 && (*(ptr-1)=='.' || *(ptr-1)=='/')) {
- if(*(protocol-1) == 's') outHTML->appendBytes(start, protocol-start-1);
- else outHTML->appendBytes(start, protocol-start);
- outHTML->appendBytes(protocol, end-protocol);
- ptr = end;
- continue;
- }
- }
- ptr = start;
- }
- outHTML->appendBytes(ptr++, 1);
- }
- }
- }
- else {
- log_printf(0,"curl error: %s (%s)\n",curl_easy_strerror(res),buf);
- statusCode = 503;
- }
- }
- if(statusCode == 200) {
- sendBasicHeaders(statusCode,"OK",fpw);
- if(0 > fprintf(fpw,"Content-Type: text/html\r\n")) goto last;
- if(0 > fprintf(fpw,"Content-Length: %ld\r\n",(long)outHTML->length)) goto last;
- if(0 > fprintf(fpw,"\r\n")) goto last;
- if(strcasecmp(method, "HEAD")) {
- if(outHTML->length > fwrite(outHTML->bytes,1,outHTML->length,fpw)) goto last;
- }
- fflush(fpw);
- }
- else {
- sendResponse(503, "Service Unavailable", fpw);
- statusCode = 503;
- }
-
- last:
- if(curl) curl_easy_cleanup(curl);
- if(buf) free(buf);
- if(dat) delete dat;
- if(outHTML) delete outHTML;
- return statusCode;
- }
|