BBS2chProxyConnection.cpp 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334
  1. #include <string>
  2. #include <vector>
  3. #include <map>
  4. #include <set>
  5. #include <sstream>
  6. #include <stdexcept>
  7. #include <algorithm>
  8. #include <pthread.h>
  9. #include <time.h>
  10. #include <stdlib.h>
  11. #include <string.h>
  12. #include <unistd.h>
  13. #include <curl/curl.h>
  14. #ifdef USE_LUA
  15. #include <lua.hpp>
  16. #endif
  17. #ifdef _WIN32
  18. #include <fcntl.h>
  19. #include <winsock2.h>
  20. #include <ws2tcpip.h>
  21. #include <mswsock.h>
  22. #define CLOSESOCKET(x) closesocket(x)
  23. #else
  24. #include <sys/socket.h>
  25. #include <netinet/in.h>
  26. #include <netdb.h>
  27. #include <arpa/inet.h>
  28. #define CLOSESOCKET(x) close(x)
  29. #endif
  30. #include "BBS2chProxyConnection.h"
  31. #include "DataStorage.h"
  32. #include "hmac.h"
  33. #include "stringEncodingConverter.h"
  34. #include "BBS2chProxyRawSocket.h"
  35. #ifdef USE_MITM
  36. #include "BBS2chProxySecureSocket.h"
  37. #endif
  38. //#define DEBUG 1
  39. extern char *proxy_server;
  40. extern long proxy_port;
  41. extern long proxy_type;
  42. extern long timeout;
  43. extern char *user_agent;
  44. extern char *api_ua_dat;
  45. extern char *x_2ch_ua_dat;
  46. extern char *appKey;
  47. extern char *hmacKey;
  48. extern int allow_chunked;
  49. extern int curl_features;
  50. extern unsigned int curl_version_number;
  51. extern bool accept_https;
  52. extern int force_5chnet;
  53. extern int force_5chnet_https;
  54. extern int force_ipv4;
  55. extern char *bbsmenu_url;
  56. extern char *api_server;
  57. extern std::map<std::string, std::string> bbscgi_headers;
  58. extern int gikofix;
  59. extern CURLSH *curl_share;
  60. extern char *lua_script;
  61. extern unsigned int api_mode;
  62. extern std::vector<std::string> bbscgi_postorder;
  63. extern unsigned int bbscgi_utf8;
  64. #ifdef USE_MITM
  65. extern unsigned int mitm_mode;
  66. #endif
  67. extern void log_printf(int level, const char *format ...);
  68. #include "utils.h"
  69. static std::string monaKey;
  70. static std::map<std::string, double> monaKeyIssueTime;
  71. static std::set<std::string> expiredMonaKeys;
  72. static regex_t regex;
  73. static regex_t regex_kako;
  74. static regex_t regex_offlaw;
  75. #ifdef USE_LUA
  76. extern "C" {
  77. static int lua_hmacSHA256(lua_State *l)
  78. {
  79. static const char *table = "0123456789abcdef";
  80. size_t keyLength, dataLength;
  81. const char *key = luaL_checklstring(l, 1, &keyLength);
  82. const char *data = luaL_checklstring(l, 2, &dataLength);
  83. if (!key || !data) return 0;
  84. unsigned char digest[32];
  85. char digestStr[65];
  86. proxy2ch_HMAC_SHA256(key, keyLength, data, dataLength, digest);
  87. for (int i=0; i<32; i++) {
  88. unsigned char c = digest[i];
  89. unsigned char upper = (c >> 4) & 0xf;
  90. unsigned char lower = c & 0xf;
  91. digestStr[i*2] = table[upper];
  92. digestStr[i*2+1] = table[lower];
  93. }
  94. digestStr[64] = 0;
  95. lua_pushstring(l, digestStr);
  96. return 1;
  97. }
  98. static int lua_decodeURIComponent(lua_State *l)
  99. {
  100. size_t length;
  101. const char *input = luaL_checklstring(l, 1, &length);
  102. if (!input) return 0;
  103. bool decodePlus = true;
  104. if (!lua_isnoneornil(l, 2)) {
  105. decodePlus = (lua_toboolean(l, 2));
  106. }
  107. std::string output = decodeURIComponent(input, length, decodePlus);
  108. lua_pushstring(l, output.c_str());
  109. return 1;
  110. }
  111. static int lua_encodeURIComponent(lua_State *l)
  112. {
  113. size_t length;
  114. const char *input = luaL_checklstring(l, 1, &length);
  115. if (!input) return 0;
  116. bool spaceAsPlus = true;
  117. if (!lua_isnoneornil(l, 2)) {
  118. spaceAsPlus = (lua_toboolean(l, 2));
  119. }
  120. std::string output = encodeURIComponent(input, length, spaceAsPlus);
  121. lua_pushstring(l, output.c_str());
  122. return 1;
  123. }
  124. static int lua_convertShiftJISToUTF8(lua_State *l)
  125. {
  126. size_t length;
  127. const char *input = luaL_checklstring(l, 1, &length);
  128. if (!input) return 0;
  129. if (length > 0) {
  130. char *output = convertShiftJISToUTF8(input, length);
  131. if (!output) lua_pushnil(l);
  132. else {
  133. lua_pushstring(l, output);
  134. free(output);
  135. }
  136. }
  137. else lua_pushstring(l, "");
  138. return 1;
  139. }
  140. static int lua_isExpiredKey(lua_State *l)
  141. {
  142. size_t length;
  143. const char *input = luaL_checklstring(l, 1, &length);
  144. if (!input) return 0;
  145. if (expiredMonaKeys.count(input)) {
  146. lua_pushboolean(l, 1);
  147. }
  148. else lua_pushboolean(l, 0);
  149. return 1;
  150. }
  151. static int lua_isValidAsUTF8(lua_State *l)
  152. {
  153. size_t length;
  154. const char *input = luaL_checklstring(l, 1, &length);
  155. if (!input) return 0;
  156. lua_pushboolean(l, isValidAsUTF8(input, length));
  157. return 1;
  158. }
  159. }
  160. #endif
  161. void BBS2chProxyConnection::setMonaKey(const std::string &key, int reason) {
  162. /* do nothing when all-zero key is given - is this safe for all cases? */
  163. if (key == "00000000-0000-0000-0000-000000000000") {
  164. return;
  165. }
  166. pthread_mutex_lock(mutex);
  167. if (key.empty()) {
  168. if ((reason >= 3320 && reason <= 3324) || (reason >= 3390 && reason <= 3392)) {
  169. expiredMonaKeys.insert(monaKeyForRequest);
  170. }
  171. log_printf(1, "Reset MonaKey\n");
  172. }
  173. else {
  174. monaKeyIssueTime[key] = getCurrentTime();
  175. log_printf(1, "Updated MonaKey: %s\n", key.c_str());
  176. }
  177. monaKey = key;
  178. pthread_mutex_unlock(mutex);
  179. }
  180. std::string BBS2chProxyConnection::getMonaKey() {
  181. if (monaKey.empty())
  182. return "00000000-0000-0000-0000-000000000000";
  183. return monaKey;
  184. }
  185. void *BBS2chProxyConnection::launch(void *param)
  186. {
  187. reinterpret_cast<BBS2chProxyConnection *>(param)->connect();
  188. return (void *)NULL;
  189. }
  190. void BBS2chProxyConnection::run(void)
  191. {
  192. pthread_t thread;
  193. pthread_attr_t thread_attr;
  194. pthread_attr_init(&thread_attr);
  195. pthread_attr_setdetachstate(&thread_attr , PTHREAD_CREATE_DETACHED);
  196. if(0 != pthread_create(&thread , &thread_attr , &BBS2chProxyConnection::launch , this))
  197. perror("pthread_create");
  198. pthread_attr_destroy(&thread_attr);
  199. }
  200. void *BBS2chProxyConnection::tunnel_c2s(void *param)
  201. {
  202. char buf[2048];
  203. fd_set fds;
  204. int sock_c = reinterpret_cast<BBS2chProxyConnection *>(param)->sock_c;
  205. int sock_s = reinterpret_cast<BBS2chProxyConnection *>(param)->sock_s;
  206. #ifdef _WIN32
  207. struct timeval timeout;
  208. timeout.tv_sec = 0;
  209. timeout.tv_usec = 10000;
  210. #endif
  211. while(1) {
  212. #ifdef _WIN32
  213. FD_ZERO(&fds);
  214. FD_SET(sock_c,&fds);
  215. if(select(sock_c + 1,&fds,NULL,NULL,&timeout) < 0) break;
  216. if(FD_ISSET(sock_c,&fds)) {
  217. #endif
  218. int ret = recv(sock_c, buf, 2048, 0);
  219. if(ret > 0) send(sock_s, buf, ret, 0);
  220. else if(ret <= 0) break;
  221. #ifdef _WIN32
  222. }
  223. #endif
  224. }
  225. //fprintf(stderr,"tunnel_c2s end\n");
  226. CLOSESOCKET(sock_s);
  227. return NULL;
  228. }
  229. void *BBS2chProxyConnection::tunnel_s2c(void *param)
  230. {
  231. char buf[2048];
  232. fd_set fds;
  233. int sock_c = reinterpret_cast<BBS2chProxyConnection *>(param)->sock_c;
  234. int sock_s = reinterpret_cast<BBS2chProxyConnection *>(param)->sock_s;
  235. while(1) {
  236. int ret = recv(sock_s, buf, 2048, 0);
  237. if(ret > 0) send(sock_c, buf, ret, 0);
  238. else if(ret <= 0) break;
  239. }
  240. //fprintf(stderr,"tunnel_s2c end\n");
  241. CLOSESOCKET(sock_c);
  242. return NULL;
  243. }
  244. int BBS2chProxyConnection::tunnel(const char *addr, int port)
  245. {
  246. struct sockaddr_in server;
  247. memset(&server, 0, sizeof(server));
  248. server.sin_family = AF_INET;
  249. server.sin_addr.s_addr = inet_addr(addr);
  250. server.sin_port = htons(port);
  251. if(server.sin_addr.s_addr == 0xffffffff) {
  252. struct hostent *host;
  253. host = gethostbyname(addr);
  254. if (host == NULL) {
  255. sendResponse(400, "Bad Request", socketToClient);
  256. return 400;
  257. }
  258. server.sin_addr.s_addr = *(unsigned int *)host->h_addr_list[0];
  259. }
  260. log_printf(1,"Tunneling connection to %s:%d\n",addr,port);
  261. sock_s = socket(AF_INET, SOCK_STREAM, 0);
  262. if(-1 == ::connect(sock_s, (struct sockaddr *)&server, sizeof(server))) {
  263. perror("connect");
  264. sendResponse(400, "Bad Request", socketToClient);
  265. return 400;
  266. }
  267. send(sock_c, "HTTP/1.1 200 Connection established\r\n\r\n", 39, 0);
  268. pthread_t thread_c2s, thread_s2c;
  269. if(0 != pthread_create(&thread_c2s, NULL, &BBS2chProxyConnection::tunnel_c2s, this))
  270. perror("pthread_create");
  271. if(0 != pthread_create(&thread_s2c, NULL, &BBS2chProxyConnection::tunnel_s2c, this))
  272. perror("pthread_create");
  273. pthread_join(thread_c2s, NULL);
  274. pthread_join(thread_s2c, NULL);
  275. log_printf(1,"Tunneling connection to %s:%d finished\n",addr,port);
  276. return 0;
  277. }
  278. void BBS2chProxyConnection::connect(void)
  279. {
  280. char method[32], url[1024], protocol[32];
  281. int i;
  282. char *buf, *ptr;
  283. bool html2dat = false;
  284. bool html2dat_kako = false;
  285. regmatch_t match[7];
  286. long statusCode = 0;
  287. std::string baseURL;
  288. socketToClient = new BBS2chProxyRawSocket(sock_c);
  289. buf = (char *)malloc(16384);
  290. if(!buf) goto end;
  291. beginHandleRequest:
  292. ptr = buf;
  293. if(!socketToClient->readLine(buf, 1024)) {
  294. sendResponse(400, "Bad Request", socketToClient);
  295. statusCode = 400;
  296. goto end;
  297. }
  298. i=0;
  299. while(*ptr != ' ' && *ptr != 0 && i < 32) method[i++] = *ptr++;
  300. if(*ptr == 0 || i == 32) {
  301. sendResponse(400, "Bad Request", socketToClient);
  302. statusCode = 400;
  303. goto end;
  304. }
  305. method[i] = 0;
  306. ptr++;
  307. i=0;
  308. while(*ptr != ' ' && *ptr != 0 && i < 1024) url[i++] = *ptr++;
  309. if(*ptr == 0 || i == 1024) {
  310. sendResponse(400, "Bad Request", socketToClient);
  311. statusCode = 400;
  312. goto end;
  313. }
  314. url[i] = 0;
  315. ptr++;
  316. i=0;
  317. while(*ptr != '\r' && *ptr != '\n' && *ptr != 0 && i < 32) protocol[i++] = *ptr++;
  318. if(*ptr == 0 || i == 32) {
  319. sendResponse(400, "Bad Request", socketToClient);
  320. statusCode = 400;
  321. goto end;
  322. }
  323. protocol[i] = 0;
  324. log_printf(1, "Received %s %s %s\n",method,url,protocol);
  325. if(strcasecmp(method,"GET") && strcasecmp(method,"POST") && strcasecmp(method,"HEAD") && strcasecmp(method,"CONNECT") && strcasecmp(method,"PUT") && strcasecmp(method, "OPTIONS")) {
  326. sendResponse(400, "Bad Request", socketToClient);
  327. statusCode = 400;
  328. goto end;
  329. }
  330. if(!url[0]) {
  331. sendResponse(400, "Bad Request", socketToClient);
  332. statusCode = 400;
  333. goto end;
  334. }
  335. if(strncasecmp(protocol,"HTTP",4)) {
  336. sendResponse(400, "Bad Request", socketToClient);
  337. statusCode = 400;
  338. goto end;
  339. }
  340. if(!strcasecmp(method,"CONNECT")) {
  341. if(!accept_https || !baseURL.empty()) {
  342. sendResponse(400, "Bad Request", socketToClient);
  343. statusCode = 400;
  344. goto end;
  345. }
  346. while(socketToClient->readLine(buf, 16384)) {
  347. if(!strcmp("\r\n",buf)) break;
  348. }
  349. int port = 443;
  350. char *ptr = strchr(url, ':');
  351. if(ptr) {
  352. *ptr = 0;
  353. port = atoi(ptr+1);
  354. }
  355. #ifdef USE_MITM
  356. bool useMITM = false;
  357. if (mitm_mode) {
  358. if (mitm_mode == 2) useMITM = true;
  359. else if (mitm_mode == 1) {
  360. int length = strlen(url);
  361. if (length >= strlen("5ch.net") && !strcasecmp(url+length-strlen("5ch.net"), "5ch.net")) {
  362. int pos = length-strlen("5ch.net");
  363. if (pos == 0) useMITM = true;
  364. else useMITM = (url[pos-1] == '.');
  365. }
  366. else if (length >= strlen("2ch.net") && !strcasecmp(url+length-strlen("2ch.net"), "2ch.net")) {
  367. int pos = length-strlen("2ch.net");
  368. if (pos == 0) useMITM = true;
  369. else useMITM = (url[pos-1] == '.');
  370. }
  371. else if (length >= strlen("bbspink.com") && !strcasecmp(url+length-strlen("bbspink.com"), "bbspink.com")) {
  372. int pos = length-strlen("bbspink.com");
  373. if (pos == 0) useMITM = true;
  374. else useMITM = (url[pos-1] == '.');
  375. }
  376. }
  377. }
  378. if (useMITM) {
  379. socketToClient->writeString("HTTP/1.1 200 Connection established\r\n\r\n");
  380. if (port == 80) {
  381. baseURL = "http://";
  382. baseURL += url;
  383. goto beginHandleRequest;
  384. }
  385. else {
  386. try {
  387. BBS2chProxySecureSocket *secureSocket = new BBS2chProxySecureSocket(sock_c, url);
  388. delete socketToClient;
  389. socketToClient = secureSocket;
  390. baseURL = "https://";
  391. baseURL += url;
  392. if (port != 443) {
  393. snprintf(buf, 16384, "%d", port);
  394. baseURL += ":";
  395. baseURL += buf;
  396. }
  397. goto beginHandleRequest;
  398. } catch (const std::runtime_error& e) {
  399. log_printf(0, "%s\n", e.what());
  400. sendResponse(400, "Bad Request", socketToClient);
  401. statusCode = 400;
  402. goto end;
  403. }
  404. }
  405. }
  406. else
  407. #endif
  408. {
  409. statusCode = tunnel(url, port);
  410. /* if a return value is non-zero, tunnel function failed to establish a tunnelling connection */
  411. if (statusCode == 0) {
  412. delete socketToClient;
  413. socketToClient = NULL;
  414. }
  415. goto end;
  416. }
  417. }
  418. #if USE_MITM
  419. if(!baseURL.empty()) {
  420. std::string completeURL = baseURL + url;
  421. strcpy(url, completeURL.c_str());
  422. log_printf(1, "Running as MITM proxy for %s\n", url);
  423. }
  424. #endif
  425. if(force_5chnet && !strncasecmp(url, "http", 4)) {
  426. char *ptr = strstr(url, "://");
  427. if (ptr) {
  428. ptr += 3;
  429. char *end = ptr;
  430. while(*end != '/' && *end != 0) end++;
  431. ptr = strstr(ptr,".2ch.net");
  432. if(ptr && ptr < end && memcmp(ptr-4,"menu.",5)) {
  433. memcpy(ptr+1,"5ch",3);
  434. force5ch = true;
  435. log_printf(1, "Detected *.2ch.net URL, changed target URL to %s\n",url);
  436. }
  437. }
  438. }
  439. if(regexec(&regex, url, 6, match, 0) != REG_NOMATCH) {
  440. if((appKey && (api_mode & 1)) || strncasecmp(url+match[1].rm_so,"headline.",9)) html2dat = true;
  441. }
  442. else if(regexec(&regex_kako, url, 7, match, 0) != REG_NOMATCH) {
  443. html2dat_kako = true;
  444. }
  445. else if(regexec(&regex_offlaw, url, 5, match, 0) != REG_NOMATCH) {
  446. char *thread = strstr(url,"key=");
  447. if(thread) {
  448. match[6].rm_so = thread+4-url;
  449. match[6].rm_eo = thread+4-url;
  450. char *ptr = thread+4;
  451. while(*ptr != '&' && *ptr != 0) {
  452. ptr++;
  453. match[6].rm_eo++;
  454. }
  455. if(match[6].rm_so != match[6].rm_eo) html2dat_kako = true;
  456. }
  457. }
  458. if(html2dat || html2dat_kako) {
  459. char tmp[1024];
  460. regmatch_t *tid = html2dat ? match+5 : match+6;
  461. strcpy(tmp,url);
  462. tmp[match[2].rm_eo] = 0;
  463. tmp[match[4].rm_eo] = 0;
  464. tmp[tid->rm_eo] = 0;
  465. if(!appKey || !(api_mode & 1) || html2dat_kako) {
  466. log_printf(1, "Retrieving thread via read.cgi...\n");
  467. snprintf(url,1024,"%s/%s/%s",tmp+match[1].rm_so,tmp+match[4].rm_so,tmp+tid->rm_so);
  468. threadKey = std::string(url);
  469. 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);
  470. statusCode = datProxy(url, method);
  471. }
  472. else {
  473. log_printf(1, "Retrieving thread via API...\n");
  474. tmp[match[1].rm_eo] = 0;
  475. 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);
  476. statusCode = datProxyAPI(url, method);
  477. }
  478. }
  479. else {
  480. char urlMod[1024];
  481. strcpy(urlMod,url);
  482. if(force_5chnet_https) {
  483. const char *host = "5ch.net";
  484. char *ptr = strstr(url,host);
  485. if(!ptr) {
  486. host = "2ch.net";
  487. ptr = strstr(url,host);
  488. }
  489. if(!ptr) {
  490. host = "bbspink.com";
  491. ptr = strstr(url,host);
  492. }
  493. if(ptr) {
  494. char *start = url+7;
  495. char *end = strchr(start,'/');
  496. int hostLength = strlen(host);
  497. if(!end) end = url+strlen(url);
  498. if(ptr >= start && ptr < end && (*(ptr-1) == '.' || *(ptr-1) == '/') && (*(ptr+hostLength) == '/' || *(ptr+hostLength) == ':' || *(ptr+hostLength) == 0)) {
  499. log_printf(1, "This is %s URL, connecting with HTTPS\n",host);
  500. if(*(ptr+hostLength) == ':') {
  501. *(ptr+hostLength) = 0;
  502. snprintf(urlMod,1024,"https://%s%s",start,end);
  503. *(ptr+hostLength) = ':';
  504. }
  505. else snprintf(urlMod,1024,"https://%s",start);
  506. log_printf(2, "URL is: %s\n",urlMod);
  507. }
  508. }
  509. }
  510. if(bbsmenu_url && !strcmp(url, bbsmenu_url)) {
  511. log_printf(1, "Running as a BBS menu proxy...\n");
  512. statusCode = bbsmenuProxy(urlMod, method);
  513. }
  514. else {
  515. bool isPostRequest = !strcasecmp(method, "POST");
  516. bool isPutRequest = !strcasecmp(method, "PUT");
  517. if(isPostRequest && (strstr(urlMod,".5ch.net") || strstr(urlMod,".bbspink.com")) && strstr(urlMod,"/test/bbs.cgi")) bbscgi = true;
  518. log_printf(1, "Not a thread request, passthrough...\n");
  519. BBS2chProxyHttpHeaders headers;
  520. while (socketToClient->readLine(buf, 16384)) {
  521. if (!strcmp("\r\n",buf)) break;
  522. headers.add(buf);
  523. }
  524. if (force_5chnet) {
  525. if (headers.has("Host")) {
  526. std::string host = headers.get("Host");
  527. size_t pos = host.find("2ch.net");
  528. if (pos != std::string::npos && pos+7 == host.length()) {
  529. if (pos == 0 || host[pos-1] == '.') {
  530. host.replace(pos, 1, "5");
  531. headers.set("Host", host);
  532. }
  533. }
  534. }
  535. if (bbscgi && headers.has("Referer")) {
  536. std::string referrer = headers.get("Referer");
  537. size_t pos = referrer.find("2ch.net");
  538. if (pos != std::string::npos) {
  539. if (pos == 0 || referrer[pos-1] == '.') {
  540. referrer.replace(pos, 1, "5");
  541. headers.set("Referer", referrer);
  542. }
  543. }
  544. }
  545. }
  546. headers.remove("Connection");
  547. if (user_agent) headers.remove("User-Agent");
  548. if (headers.hasNameAndValue("Transfer-Encoding", "chunked")) {
  549. isClientChunked = true;
  550. }
  551. else if (headers.has("Content-Length")) {
  552. content_length = atoi(headers.get("Content-Length").c_str());
  553. }
  554. if (headers.has("Expect")) {
  555. if (!strcasecmp(headers.get("Expect").c_str(), "100-continue")) {
  556. log_printf(1, "Received Expect: 100-continue header, sending 100 Continue response to the client\n");
  557. socketToClient->writeString("HTTP/1.1 100 Continue\r\n\r\n");
  558. }
  559. }
  560. if (bbscgi && (content_length > 0 || isClientChunked)) {
  561. bool isNotFormURLEncoded = false;
  562. if (headers.has("Content-Type") && headers.get("Content-Type").find("application/x-www-form-urlencoded") == std::string::npos) {
  563. isNotFormURLEncoded = true;
  564. }
  565. if (!isNotFormURLEncoded) {
  566. headers.remove("Content-Length");
  567. if (!bbscgi_headers.empty()) {
  568. for (std::map<std::string, std::string>::iterator it = bbscgi_headers.begin(); it != bbscgi_headers.end(); it++) {
  569. if (headers.has(it->first)) {
  570. log_printf(1, "Ignoring header \"%s\" because custom header will be appended\n", it->first.c_str());
  571. headers.remove(it->first);
  572. }
  573. }
  574. }
  575. char *postdata = NULL;
  576. if (isClientChunked) {
  577. size_t bufferLength = 128;
  578. size_t chunkSize = 0;
  579. char tmp[64];
  580. postdata = (char *)malloc(bufferLength);
  581. while (1) {
  582. if (!chunkSize) {
  583. if (!socketToClient->readLine(tmp, 64)) break;
  584. chunkSize = strtol(tmp, NULL, 16);
  585. if (chunkSize == 0) {
  586. break;
  587. }
  588. if (chunkSize + content_length >= bufferLength) {
  589. bufferLength = chunkSize + content_length + 1;
  590. postdata = (char *)realloc(postdata, bufferLength);
  591. }
  592. }
  593. size_t ret = socketToClient->read(postdata+content_length, chunkSize);
  594. if (ret > 0) content_length += ret;
  595. if (ret < chunkSize) break;
  596. if (!socketToClient->readLine(tmp, 64)) break;
  597. chunkSize = 0;
  598. }
  599. postdata[content_length] = 0;
  600. headers.remove("Transfer-Encoding");
  601. }
  602. else {
  603. postdata = (char *)calloc(content_length+1, 1);
  604. content_length = socketToClient->read(postdata, content_length);
  605. }
  606. if (gikofix) {
  607. char *ptr = postdata+content_length-1;
  608. while (ptr >= postdata && (*ptr == '\r' || *ptr == '\n')) {
  609. *ptr-- = 0;
  610. }
  611. }
  612. curl_slist *headersForCurl = NULL;
  613. headersForCurl = headers.appendToCurlSlist(headersForCurl);
  614. statusCode = bbsCgiProxy(urlMod, protocol, &headers, postdata);
  615. free(postdata);
  616. curl_slist_free_all(headersForCurl);
  617. goto end;
  618. }
  619. }
  620. curl_slist *headersForCurl = NULL;
  621. headersForCurl = headers.appendToCurlSlist(headersForCurl);
  622. if (!headers.has("Expect")) {
  623. headersForCurl = curl_slist_append(headersForCurl, "Expext:");
  624. }
  625. CURL *curl = curl_easy_init();
  626. if(curl) {
  627. CURLcode res;
  628. if(curl_share) curl_easy_setopt(curl, CURLOPT_SHARE, curl_share);
  629. curl_easy_setopt(curl, CURLOPT_URL, urlMod);
  630. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
  631. curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  632. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, header_callback_proxy);
  633. curl_easy_setopt(curl, CURLOPT_HEADERDATA, this);
  634. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback_proxy);
  635. curl_easy_setopt(curl, CURLOPT_WRITEDATA, this);
  636. if(content_length) {
  637. /* set Content-Length explicitly via API to work properly with curl >= 7.66.0 */
  638. if(isPostRequest)
  639. curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, content_length);
  640. else if(isPutRequest)
  641. curl_easy_setopt(curl, CURLOPT_INFILESIZE, content_length);
  642. }
  643. curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_callback_proxy);
  644. curl_easy_setopt(curl, CURLOPT_READDATA, this);
  645. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
  646. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
  647. //curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
  648. if(force_ipv4) curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
  649. if(!strncasecmp(protocol,"HTTP/1.0",8) && !strncasecmp(urlMod, "http://", 7)) {
  650. curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
  651. }
  652. else {
  653. /* force use HTTP 1.1 because CURL_HTTP_VERSION_2TLS is used on curl (w/ nghttp2) >= 7.62.0 */
  654. curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
  655. }
  656. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headersForCurl);
  657. if(user_agent) {
  658. curl_easy_setopt(curl, CURLOPT_USERAGENT, user_agent);
  659. }
  660. if(isPostRequest) {
  661. curl_easy_setopt(curl, CURLOPT_POST, 1L);
  662. }
  663. else if(isPutRequest) {
  664. curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
  665. }
  666. else if(!strcasecmp(method, "HEAD")) {
  667. curl_easy_setopt(curl, CURLOPT_NOBODY, 1L);
  668. }
  669. else if(!strcasecmp(method, "OPTIONS")) {
  670. curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "OPTIONS");
  671. }
  672. if(proxy_server) {
  673. curl_easy_setopt(curl, CURLOPT_PROXY, proxy_server);
  674. curl_easy_setopt(curl, CURLOPT_PROXYPORT, proxy_port);
  675. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, proxy_type);
  676. }
  677. res = curl_easy_perform(curl);
  678. if(res != CURLE_OK) {
  679. log_printf(0,"curl error: %s (%s)\n",curl_easy_strerror(res),urlMod);
  680. if(!status) sendResponse(503, "Service Unavailable", socketToClient);
  681. statusCode = 503;
  682. }
  683. else {
  684. if(chunked) {
  685. socketToClient->writeString("0\r\n\r\n");
  686. }
  687. curl_easy_getinfo(curl,CURLINFO_RESPONSE_CODE, &statusCode);
  688. }
  689. curl_easy_cleanup(curl);
  690. }
  691. curl_slist_free_all(headersForCurl);
  692. }
  693. }
  694. end:
  695. if(statusCode) log_printf(1, "Returned status code %d to client\n",statusCode);
  696. if(buf) free(buf);
  697. if(socketToClient) socketToClient->close();
  698. delete this;
  699. }
  700. int BBS2chProxyConnection::datProxy(const char *url, const char *method)
  701. {
  702. DataStorage *html = NULL;
  703. long statusCode = 0;
  704. long rangeStart = 0, rangeEnd = 0;
  705. time_t lastModified = 0;
  706. time_t ifModifiedSince = 0;
  707. char *buf = (char *)malloc(16384);
  708. BBS2chProxyHttpHeaders headers;
  709. if(!buf) goto last;
  710. while(socketToClient->readLine(buf, 16384)) {
  711. //fprintf(stderr,"%s",buf);
  712. if(!strcmp("\r\n",buf)) break;
  713. headers.add(buf);
  714. };
  715. if(headers.has("Range")) {
  716. std::string value = headers.get("Range");
  717. if(value.find("bytes=") == 0 && value.find(",") == std::string::npos) {
  718. char *ptr = (char *)value.c_str() + 6;
  719. if(*ptr == '-') {
  720. rangeStart = atoi(ptr);
  721. }
  722. else {
  723. rangeStart = strtol(ptr, &ptr, 10);
  724. if(*ptr == '-') ptr++;
  725. if(*ptr && *ptr != '\r') {
  726. rangeEnd = strtol(ptr, NULL, 10);
  727. if(rangeEnd && rangeStart > rangeEnd) {
  728. sendResponse(416, "Requested range not satisfiable", socketToClient);
  729. statusCode = 416;
  730. goto last;
  731. }
  732. }
  733. }
  734. //fprintf(stderr, "range=%ld-%ld\n",rangeStart,rangeEnd);
  735. }
  736. else {
  737. sendResponse(416, "Requested range not satisfiable", socketToClient);
  738. statusCode = 416;
  739. goto last;
  740. }
  741. }
  742. if(headers.has("If-Modified-Since")) {
  743. struct tm time_ = {};
  744. strptime(headers.get("If-Modified-Since").c_str(), httpTimestampFmt, &time_);
  745. ifModifiedSince = mktime(&time_);
  746. }
  747. if(rangeStart > 0) {
  748. PBBS2chProxyThreadInfo info;
  749. pthread_mutex_lock(mutex);
  750. BBS2chProxyThreadCache::iterator it = threadCache->find(threadKey);
  751. if(it != threadCache->end()) {
  752. info = it->second;
  753. }
  754. pthread_mutex_unlock(mutex);
  755. log_printf(5,"range request from %ld bytes\n",rangeStart);
  756. if(info) {
  757. int from = info->lastResNum;
  758. int alreadyRead = info->cachedSize;
  759. int lastResLength = info->cachedData->length;
  760. log_printf(5,"hit %s: cached %d bytes, last res size %d\n",threadKey.c_str(),alreadyRead,lastResLength);
  761. if(rangeStart <= alreadyRead && rangeStart >= alreadyRead - lastResLength) {
  762. CURL *curl = curl_easy_init();
  763. if(curl) {
  764. CURLcode res;
  765. DataStorage *dat = new DataStorage();
  766. log_printf(5,"partial access from res num %d\n",from);
  767. snprintf(buf,16384,"%s%d-n",url,from);
  768. if(curl_share) curl_easy_setopt(curl, CURLOPT_SHARE, curl_share);
  769. curl_easy_setopt(curl, CURLOPT_URL, buf);
  770. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
  771. curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  772. curl_easy_setopt(curl, CURLOPT_ENCODING, "");
  773. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback_download);
  774. curl_easy_setopt(curl, CURLOPT_WRITEDATA, dat);
  775. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  776. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
  777. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
  778. if(force_ipv4) curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
  779. if(proxy_server) {
  780. curl_easy_setopt(curl, CURLOPT_PROXY, proxy_server);
  781. curl_easy_setopt(curl, CURLOPT_PROXYPORT, proxy_port);
  782. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, proxy_type);
  783. }
  784. if(user_agent) {
  785. curl_easy_setopt(curl, CURLOPT_USERAGENT, user_agent);
  786. }
  787. else if(headers.has("User-Agent")) {
  788. curl_easy_setopt(curl, CURLOPT_USERAGENT, headers.get("User-Agent").c_str());
  789. }
  790. res = curl_easy_perform(curl);
  791. if(res == CURLE_OK) {
  792. curl_easy_getinfo(curl,CURLINFO_RESPONSE_CODE, &statusCode);
  793. curl_easy_cleanup(curl);
  794. if(statusCode == 200 && dat->length) {
  795. DataStorage *updated = html2dat(dat, from, &lastModified, true);
  796. if(ifModifiedSince && lastModified && updated && updated->length == lastResLength) {
  797. struct tm time_ = {};
  798. gmtime_r(&lastModified,&time_);
  799. time_t tmp = mktime(&time_);
  800. if(ifModifiedSince >= tmp) {
  801. sendResponse(304, "Not Modified", socketToClient);
  802. log_printf(5,"not modified!\n");
  803. delete updated;
  804. delete dat;
  805. statusCode = 304;
  806. goto last;
  807. }
  808. }
  809. if(updated && updated->length && updated->length >= lastResLength) {
  810. html = new DataStorage(alreadyRead - lastResLength);
  811. html->appendBytes(updated->bytes, updated->length);
  812. if(!rangeEnd) rangeEnd = html->length - 1;
  813. if(rangeStart > rangeEnd) {
  814. sendResponse(416, "Requested range not satisfiable", socketToClient);
  815. delete updated;
  816. delete dat;
  817. statusCode = 416;
  818. goto last;
  819. }
  820. statusCode = 206;
  821. log_printf(5,"cache hit; reconstructed data length:%ld\n",(long)html->length);
  822. }
  823. else {
  824. log_printf(5,"cache misshit?\n");
  825. sendResponse(416, "Requested range not satisfiable", socketToClient);
  826. delete updated;
  827. delete dat;
  828. statusCode = 416;
  829. goto last;
  830. }
  831. delete updated;
  832. }
  833. }
  834. else {
  835. log_printf(0,"curl error: %s (%s)\n",curl_easy_strerror(res),buf);
  836. curl_easy_cleanup(curl);
  837. }
  838. delete dat;
  839. if(html) goto resp;
  840. }
  841. }
  842. else {
  843. log_printf(5,"invalid cache contents\n");
  844. pthread_mutex_lock(mutex);
  845. BBS2chProxyThreadCache::iterator it = threadCache->find(threadKey);
  846. if(it != threadCache->end()) {
  847. threadCache->erase(it);
  848. }
  849. pthread_mutex_unlock(mutex);
  850. }
  851. }
  852. }
  853. {
  854. CURL *curl = curl_easy_init();
  855. if(curl) {
  856. CURLcode res;
  857. DataStorage *dat = new DataStorage();
  858. if(curl_share) curl_easy_setopt(curl, CURLOPT_SHARE, curl_share);
  859. curl_easy_setopt(curl, CURLOPT_URL, url);
  860. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
  861. curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  862. curl_easy_setopt(curl, CURLOPT_ENCODING, "");
  863. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback_download);
  864. curl_easy_setopt(curl, CURLOPT_WRITEDATA, dat);
  865. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  866. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
  867. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
  868. if(force_ipv4) curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
  869. if(proxy_server) {
  870. curl_easy_setopt(curl, CURLOPT_PROXY, proxy_server);
  871. curl_easy_setopt(curl, CURLOPT_PROXYPORT, proxy_port);
  872. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, proxy_type);
  873. }
  874. if(user_agent) {
  875. curl_easy_setopt(curl, CURLOPT_USERAGENT, user_agent);
  876. }
  877. else if(headers.has("User-Agent")) {
  878. curl_easy_setopt(curl, CURLOPT_USERAGENT, headers.get("User-Agent").c_str());
  879. }
  880. res = curl_easy_perform(curl);
  881. if(res != CURLE_OK) {
  882. log_printf(0,"curl error: %s (%s)\n",curl_easy_strerror(res),url);
  883. sendResponse(503, "Service Unavailable", socketToClient);
  884. curl_easy_cleanup(curl);
  885. delete dat;
  886. statusCode = 503;
  887. goto last;
  888. }
  889. curl_easy_getinfo(curl,CURLINFO_RESPONSE_CODE, &statusCode);
  890. curl_easy_cleanup(curl);
  891. if(statusCode == 200) {
  892. html = html2dat(dat, 1, &lastModified, false);
  893. }
  894. delete dat;
  895. }
  896. if(!html || !html->length) {
  897. sendResponse(503, "Service Unavailable", socketToClient);
  898. statusCode = 503;
  899. goto last;
  900. }
  901. if((rangeStart || rangeEnd) && html && html->length) {
  902. if(!rangeEnd) rangeEnd = html->length - 1;
  903. if(rangeStart < 0) rangeStart = html->length + rangeStart;
  904. if(rangeStart < html->length && rangeEnd < html->length && rangeStart <= rangeEnd) {
  905. statusCode = 206;
  906. }
  907. else {
  908. if(ifModifiedSince && lastModified && rangeStart == html->length) {
  909. struct tm time_ = {};
  910. gmtime_r(&lastModified,&time_);
  911. time_t tmp = mktime(&time_);
  912. if(ifModifiedSince >= tmp) {
  913. sendResponse(304, "Not Modified", socketToClient);
  914. log_printf(5,"not modified!\n");
  915. statusCode = 304;
  916. goto last;
  917. }
  918. }
  919. sendResponse(416, "Requested range not satisfiable", socketToClient);
  920. statusCode = 416;
  921. goto last;
  922. }
  923. }
  924. }
  925. resp:
  926. if(statusCode == 206) sendBasicHeaders(statusCode,"Partial Content",socketToClient);
  927. else sendBasicHeaders(statusCode,"OK",socketToClient);
  928. if(0 >= socketToClient->writeString("Content-Type: text/plain\r\n")) goto last;
  929. if(0 >= socketToClient->writeString("Accept-Ranges: bytes\r\n")) goto last;
  930. if(statusCode == 206) {
  931. std::ostringstream ss;
  932. ss << "Content-Range: bytes " << rangeStart << "-" << rangeEnd << "/" << html->length << "\r\n";
  933. if (0 >= socketToClient->writeString(ss.str())) goto last;
  934. //fprintf(stderr,"Content-Length: %ld\r\n",rangeEnd - rangeStart + 1);
  935. //fprintf(stderr,"Content-Range: bytes %ld-%ld/%ld\r\n",rangeStart,rangeEnd,(long)html->length);
  936. DataStorage *newHtml = new DataStorage();
  937. newHtml->appendBytes(html->bytes+rangeStart, rangeEnd - rangeStart + 1);
  938. delete html;
  939. html = newHtml;
  940. }
  941. {
  942. std::ostringstream ss;
  943. ss << "Content-Length: " << html->length << "\r\n";
  944. if(0 >= socketToClient->writeString(ss.str())) goto last;
  945. }
  946. if(lastModified) {
  947. struct tm time_ = {};
  948. char date[256];
  949. gmtime_r(&lastModified,&time_);
  950. strftime(date,256,httpTimestampFmt,&time_);
  951. std::string header = "Last-Modified: ";
  952. header += date;
  953. header += "\r\n";
  954. if(0 >= socketToClient->writeString(header)) goto last;
  955. //fprintf(stderr,"Last-Modified: %s\r\n",date);
  956. }
  957. if(0 > socketToClient->writeString("\r\n")) goto last;
  958. if(html && statusCode >= 200 && statusCode < 300 && strcasecmp(method, "HEAD")) {
  959. if(html->length > socketToClient->write(html->bytes, html->length)) goto last;
  960. }
  961. last:
  962. if(buf) free(buf);
  963. if(html) delete html;
  964. return statusCode;
  965. }
  966. DataStorage *BBS2chProxyConnection::html2dat_old(DataStorage *html, int startResNum, time_t *lastModified, bool useCache)
  967. {
  968. char *ptr = html->bytes;
  969. char *end = html->bytes + html->length - 1;
  970. DataStorage *txt = new DataStorage();
  971. int res = startResNum, i=0;
  972. char signature[32];
  973. char title[1024];
  974. int cachedSize = 0;
  975. bool bbspink = strstr(threadKey.c_str(),"bbspink.com") ? true : false;
  976. ptr = (char *)memmem_priv(ptr, end-ptr+1, "<title>", 7);
  977. if(!ptr) {
  978. delete txt;
  979. return NULL;
  980. }
  981. ptr += 7;
  982. while(1) {
  983. if(*ptr == '<') {
  984. if(!strncasecmp(ptr,"</title>",8)) {
  985. ptr += 8;
  986. break;
  987. }
  988. else title[i++] = *ptr++;
  989. }
  990. else title[i++] = *ptr++;
  991. }
  992. title[i] = 0;
  993. snprintf(signature,32,"<dt>%d ",res);
  994. ptr = (char *)memmem_priv(ptr, end-ptr+1, signature, strlen(signature));
  995. if(!ptr) {
  996. delete txt;
  997. return NULL;
  998. }
  999. unsigned char *buffer = (unsigned char *)malloc(65536+1024+1024+1024+2048);
  1000. if(!buffer) {
  1001. delete txt;
  1002. return NULL;
  1003. }
  1004. unsigned char *body = buffer;
  1005. char *mail = (char *)body + 65536;
  1006. char *name = mail + 1024;
  1007. char *date = name + 1024;
  1008. char *encrypted = date + 1024;
  1009. while(ptr < end) {
  1010. //fprintf(stderr,"%s\n",signature);
  1011. DataStorage *resData = new DataStorage();
  1012. i=0;
  1013. mail[0] = 0;
  1014. ptr = strstr(ptr,signature);
  1015. ptr += strlen(signature);
  1016. while(*ptr != '<') ptr++;
  1017. ptr++;
  1018. const char *endStr;
  1019. if(*ptr == 'a' || *ptr == 'A') {
  1020. replay:
  1021. // has mail
  1022. while(*ptr != '"') ptr++;
  1023. ptr++;
  1024. if(!strncmp(ptr,"/cdn-cgi/l/email-protection#",28)) {
  1025. ptr += 28;
  1026. while(*ptr != '"' && *ptr != 'X') encrypted[i++] = *ptr++;
  1027. encrypted[i] = 0;
  1028. i = decryptMail((unsigned char *)mail,encrypted);
  1029. int reconstruct_len = *ptr == 'X' ? i + 15 : i + 16;
  1030. ptr -= reconstruct_len;
  1031. char *start = ptr;
  1032. memcpy(ptr, "<a href=\"mailto:", 16);
  1033. ptr += 16;
  1034. memcpy(ptr, mail, i);
  1035. ptr = start;
  1036. i=0;
  1037. goto replay;
  1038. }
  1039. else {
  1040. if(!strncmp(ptr,"mailto:",7)) ptr += 7;
  1041. while(*ptr != '"') mail[i++] = *ptr++;
  1042. mail[i] = 0;
  1043. }
  1044. endStr = "</a>";
  1045. }
  1046. else if(*ptr == 'b') {
  1047. endStr = NULL;
  1048. }
  1049. else {
  1050. endStr = "</font>";
  1051. }
  1052. if(endStr) {
  1053. ptr = strstr(ptr,"<b>");
  1054. ptr += 3;
  1055. }
  1056. else {
  1057. ptr = strchr(ptr,'>');
  1058. ptr++;
  1059. }
  1060. i=0;
  1061. while(1) {
  1062. if(*ptr == '<') {
  1063. if(!strncasecmp(ptr,"</b>",4) && (!endStr || !strncasecmp(ptr+4,endStr,strlen(endStr)))) {
  1064. ptr += 4;
  1065. if(endStr) ptr += strlen(endStr);
  1066. break;
  1067. }
  1068. else if(!strncmp(ptr,"<span class=\"__cf_email__\"",26)) {
  1069. int j=0;
  1070. ptr = strstr(ptr,"data-cfemail=\"");
  1071. ptr += 14;
  1072. while(*ptr != '"') encrypted[j++] = *ptr++;
  1073. encrypted[j] = 0;
  1074. j = decryptMail((unsigned char *)name+i,encrypted);
  1075. i += j;
  1076. ptr = strstr(ptr,"</script>");
  1077. ptr += 9;
  1078. }
  1079. else name[i++] = *ptr++;
  1080. }
  1081. else name[i++] = *ptr++;
  1082. }
  1083. resData->appendBytes(name, i);
  1084. resData->appendBytes("<>", 2);
  1085. if(mail[0]) resData->appendBytes(mail ,strlen(mail));
  1086. resData->appendBytes("<>", 2);
  1087. ptr += 2;
  1088. i=0;
  1089. while(1) {
  1090. if(*ptr == '<') {
  1091. if(!strncasecmp(ptr,"<dd>",4)) {
  1092. ptr += 4;
  1093. break;
  1094. }
  1095. else if(!strncmp(ptr,"<a href=\"javascript:be(",23)) {
  1096. memcpy(date+i,"BE:",3);
  1097. ptr += 23;
  1098. i += 3;
  1099. while(*ptr != ')') date[i++] = *ptr++;
  1100. date[i++] = '-';
  1101. ptr = strchr(ptr,'?');
  1102. ptr++;
  1103. char *tmp = strstr(ptr,"</a>");
  1104. memcpy(date+i,ptr,tmp-ptr);
  1105. i += tmp-ptr;
  1106. ptr = tmp + 4;
  1107. }
  1108. else date[i++] = *ptr++;
  1109. }
  1110. else date[i++] = *ptr++;
  1111. }
  1112. resData->appendBytes(date ,i);
  1113. resData->appendBytes("<>", 2);
  1114. i=0;
  1115. while(1) {
  1116. if(*ptr == '<') {
  1117. if(!strncasecmp(ptr,"<br><br>\n",9)) {
  1118. ptr += 9;
  1119. break;
  1120. }
  1121. else if(!strncasecmp(ptr,"<dt>",4) || !strncasecmp(ptr,"</dl>",5)) {
  1122. while(i>0 &&body[i-1] == '\n') i--;
  1123. break;
  1124. }
  1125. else if(!strncmp(ptr,"<span class=\"__cf_email__\"",26) || !strncmp(ptr,"<a class=\"__cf_email__\"",23)) {
  1126. int j=0;
  1127. ptr = strstr(ptr,"data-cfemail=\"");
  1128. ptr += 14;
  1129. while(*ptr != '"') encrypted[j++] = *ptr++;
  1130. encrypted[j] = 0;
  1131. j = decryptMail(body+i,encrypted);
  1132. i += j;
  1133. ptr = strstr(ptr,"</script>");
  1134. ptr += 9;
  1135. }
  1136. else if(!strncmp(ptr,"<a href=\"http",13)) {
  1137. ptr = strchr(ptr,'>');
  1138. ptr++;
  1139. char *link = ptr;
  1140. ptr = strstr(link,"</a>");
  1141. memcpy(body+i,link,ptr-link);
  1142. i += ptr-link;
  1143. ptr += 4;
  1144. }
  1145. else if(!strncmp(ptr,"<img src=\"",10)) {
  1146. ptr += 10;
  1147. char *img = ptr;
  1148. ptr = strstr(img,"\">");
  1149. memcpy(body+i,img,ptr-img);
  1150. 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)) {
  1151. int length = ptr-img;
  1152. while(*img != '/') {
  1153. img++;
  1154. length--;
  1155. }
  1156. memcpy(body+i,"sssp:",5);
  1157. memcpy(body+i+5,img,length);
  1158. i += length + 5;
  1159. }
  1160. else i += ptr-img;
  1161. ptr += 2;
  1162. }
  1163. else if(!bbspink && !strncmp(ptr,"<br>",4)) {
  1164. if(i>5 && !strncmp((char *)body+i-5,"<br> ",5)) {
  1165. memcpy(body+i," <br>",5);
  1166. i += 5;
  1167. }
  1168. else {
  1169. memcpy(body+i,"<br>",4);
  1170. i += 4;
  1171. }
  1172. ptr += 4;
  1173. }
  1174. else body[i++] = *ptr++;
  1175. }
  1176. else if(!bbspink && *ptr == ' ') {
  1177. if(*(ptr+1) == ' ') ptr++;
  1178. else body[i++] = *ptr++;
  1179. }
  1180. else body[i++] = *ptr++;
  1181. }
  1182. resData->appendBytes(body ,i);
  1183. resData->appendBytes("<>", 2);
  1184. if(res == 1) resData->appendBytes(title ,strlen(title));
  1185. resData->appendBytes("\n" ,1);
  1186. if(useCache && res == startResNum) {
  1187. PBBS2chProxyThreadInfo info;
  1188. bool hit = false;
  1189. pthread_mutex_lock(mutex);
  1190. BBS2chProxyThreadCache::iterator it = threadCache->find(threadKey);
  1191. if(it != threadCache->end()) {
  1192. info = it->second;
  1193. threadCache->erase(it);
  1194. }
  1195. pthread_mutex_unlock(mutex);
  1196. if(info) {
  1197. log_printf(5,"cache hit");
  1198. if(info->cachedData->length == resData->length) {
  1199. log_printf(5,"... size match");
  1200. if(!memcmp(info->cachedData->bytes,resData->bytes,resData->length)) {
  1201. log_printf(5,"... content match");
  1202. hit = true;
  1203. cachedSize = info->cachedSize - resData->length;
  1204. }
  1205. }
  1206. log_printf(5,"\n");
  1207. }
  1208. if(!hit) {
  1209. delete resData;
  1210. free(buffer);
  1211. return NULL;
  1212. }
  1213. }
  1214. txt->appendBytes(resData->bytes, resData->length);
  1215. res++;
  1216. while(*ptr == '\n' || *ptr == '\r') ptr++;
  1217. snprintf(signature,32,"<dt>%d ",res);
  1218. if(!memmem_priv(ptr, end-ptr+1, signature, strlen(signature))) {
  1219. PBBS2chProxyThreadInfo info(new BBS2chProxyThreadInfo());
  1220. info->lastResNum = res-1;
  1221. info->cachedSize = txt->length+cachedSize;
  1222. info->cachedData = resData;
  1223. pthread_mutex_lock(mutex);
  1224. threadCache->insert(std::make_pair(threadKey,info));
  1225. pthread_mutex_unlock(mutex);
  1226. log_printf(5,"cached thread %s (%ld bytes)\n",threadKey.c_str(),(long)resData->length);
  1227. if(lastModified) {
  1228. *lastModified = 0;
  1229. char formattedDate[256];
  1230. char *ptr;
  1231. ptr = date;
  1232. int year = strtol(ptr,&ptr,10);
  1233. if(*ptr != '/') break;
  1234. ptr++;
  1235. int month = strtol(ptr,&ptr,10);
  1236. if(*ptr != '/') break;
  1237. ptr++;
  1238. int day = strtol(ptr,&ptr,10);
  1239. if(!*ptr) break;
  1240. while(*ptr != ' ' && *ptr != 0) ptr++;
  1241. if(!*ptr) break;
  1242. ptr++;
  1243. int hour = strtol(ptr,&ptr,10);
  1244. if(*ptr != ':') break;
  1245. ptr++;
  1246. int minutes = strtol(ptr,&ptr,10);
  1247. if(*ptr != ':') break;
  1248. ptr++;
  1249. int seconds = strtol(ptr,&ptr,10);
  1250. if(!(month>0 && month<13) || !(day>0 && day<32)) break;
  1251. if(year < 100) year += 2000;
  1252. snprintf(formattedDate,256,"%d/%d/%d %02d:%02d:%02d JST",year,month,day,hour,minutes,seconds);
  1253. //fprintf(stderr,"%s\n",formattedDate);
  1254. struct tm time = {};
  1255. strptime(formattedDate,threadTimestampFmt,&time);
  1256. *lastModified = mktime(&time);
  1257. //gmtime_r(lastModified,&time);
  1258. //strftime(formattedDate,256,httpTimestampFmt,&time);
  1259. //fprintf(stderr,"%s\n",formattedDate);
  1260. }
  1261. //fprintf(stderr,"not found,%ld\n",end-ptr+1);
  1262. break;
  1263. }
  1264. delete resData;
  1265. }
  1266. free(buffer);
  1267. return txt;
  1268. }
  1269. DataStorage *BBS2chProxyConnection::html2dat(DataStorage *html, int startResNum, time_t *lastModified, bool useCache)
  1270. {
  1271. char *ptr = html->bytes;
  1272. char *end = html->bytes + html->length - 1;
  1273. DataStorage *txt = new DataStorage();
  1274. int res = startResNum, i=0;
  1275. char signature[64];
  1276. char title[1024];
  1277. int cachedSize = 0;
  1278. char signatureTag[32];
  1279. char closeTag[32];
  1280. int closeTagLen;
  1281. ptr = (char *)memmem_priv(ptr, end-ptr+1, "<h1 class=\"title\">", 18);
  1282. if(!ptr) {
  1283. delete txt;
  1284. return html2dat_old(html, startResNum, lastModified, useCache);
  1285. }
  1286. else {
  1287. char *ptr2 = (char *)memmem_priv(ptr, end-ptr+1, " class=\"post\"", 13);
  1288. if(ptr2) {
  1289. char *tmp = ptr2;
  1290. *ptr2 = 0;
  1291. while(*ptr2 != '<') ptr2--;
  1292. strcpy(signatureTag, ptr2);
  1293. *tmp = ' ';
  1294. }
  1295. else {
  1296. delete txt;
  1297. return NULL;
  1298. }
  1299. /*char *ptr2 = (char *)memmem_priv(ptr, end-ptr+1, "<dl class=\"post\"", 16);
  1300. if(ptr2) {
  1301. delete txt;
  1302. return html2dat_pink(html, startResNum, lastModified, useCache);
  1303. }*/
  1304. }
  1305. ptr += 18;
  1306. while(1) {
  1307. if(*ptr == '<') {
  1308. if(!strncasecmp(ptr,"</h1>",5)) {
  1309. ptr += 5;
  1310. break;
  1311. }
  1312. else title[i++] = *ptr++;
  1313. }
  1314. else if(*ptr == '\n') break;
  1315. else title[i++] = *ptr++;
  1316. }
  1317. title[i] = 0;
  1318. snprintf(signature,32,"%s class=\"post\" id=\"%d\"",signatureTag,res);
  1319. ptr = (char *)memmem_priv(ptr, end-ptr+1, signature, strlen(signature));
  1320. if(!ptr) {
  1321. delete txt;
  1322. return NULL;
  1323. }
  1324. unsigned char *buffer = (unsigned char *)malloc(65536+1024+1024+1024+2048);
  1325. if(!buffer) {
  1326. delete txt;
  1327. return NULL;
  1328. }
  1329. unsigned char *body = buffer;
  1330. char *mail = (char *)body + 65536;
  1331. char *name = mail + 1024;
  1332. char *date = name + 1024;
  1333. char *encrypted = date + 1024;
  1334. while(ptr < end) {
  1335. //fprintf(stderr,"%s\n",signature);
  1336. DataStorage *resData = new DataStorage();
  1337. i=0;
  1338. mail[0] = 0;
  1339. ptr = strstr(ptr," class=\"name\"><b>");
  1340. if(ptr) {
  1341. char *tmp = ptr;
  1342. *ptr = 0;
  1343. while(*ptr != '<') ptr--;
  1344. snprintf(closeTag,32,"</%s>",ptr+1);
  1345. closeTagLen = strlen(closeTag);
  1346. ptr = tmp + 17;
  1347. }
  1348. else {
  1349. delete resData;
  1350. break;
  1351. }
  1352. char endStr[64];
  1353. if(!strncmp(ptr,"<a href=\"mailto:",16)) {
  1354. replay:
  1355. // has mail
  1356. while(*ptr != '"') ptr++;
  1357. ptr++;
  1358. if(!strncmp(ptr,"/cdn-cgi/l/email-protection#",28)) {
  1359. ptr += 28;
  1360. while(*ptr != '"' && *ptr != 'X') encrypted[i++] = *ptr++;
  1361. encrypted[i] = 0;
  1362. i = decryptMail((unsigned char *)mail,encrypted);
  1363. int reconstruct_len = *ptr == 'X' ? i + 15 : i + 16;
  1364. ptr -= reconstruct_len;
  1365. char *start = ptr;
  1366. memcpy(ptr, "<a href=\"mailto:", 16);
  1367. ptr += 16;
  1368. memcpy(ptr, mail, i);
  1369. ptr = start;
  1370. i=0;
  1371. goto replay;
  1372. }
  1373. else {
  1374. if(!strncmp(ptr,"mailto:",7)) ptr += 7;
  1375. while(1) {
  1376. if(*ptr == '<' && !strncmp(ptr,"<a href=\"",9)) {
  1377. ptr = strchr(ptr,'>');
  1378. ptr++;
  1379. char *link = ptr;
  1380. ptr = strstr(link,"</a>");
  1381. memcpy(mail+i,link,ptr-link);
  1382. i += ptr-link;
  1383. ptr += 4;
  1384. }
  1385. else if(*ptr == '"') break;
  1386. else mail[i++] = *ptr++;
  1387. }
  1388. //while(*ptr != '"') mail[i++] = *ptr++;
  1389. mail[i] = 0;
  1390. }
  1391. snprintf(endStr,64,"</a></b>%s",closeTag);
  1392. while(*ptr != '>') ptr++;
  1393. ptr++;
  1394. }
  1395. /* we do not have to handle this special case because read.cgi on bbspink doesn't
  1396. emit font tags anymore and it conflicts with text decorations using "melon point" */
  1397. /*else if(!strncmp(ptr,"<font",5)) {
  1398. snprintf(endStr,64,"</font></b>%s",closeTag);
  1399. while(*ptr != '>') ptr++;
  1400. ptr++;
  1401. }*/
  1402. else {
  1403. snprintf(endStr,64,"</b>%s",closeTag);
  1404. }
  1405. i=0;
  1406. while(1) {
  1407. if(*ptr == '<') {
  1408. if(!strncmp(ptr,endStr,strlen(endStr))) {
  1409. ptr += strlen(endStr);
  1410. break;
  1411. }
  1412. else if(!strncmp(ptr,"<span class=\"__cf_email__\"",26)) {
  1413. int j=0;
  1414. ptr = strstr(ptr,"data-cfemail=\"");
  1415. ptr += 14;
  1416. while(*ptr != '"') encrypted[j++] = *ptr++;
  1417. encrypted[j] = 0;
  1418. j = decryptMail((unsigned char *)name+i,encrypted);
  1419. i += j;
  1420. ptr = strstr(ptr,"</script>");
  1421. ptr += 9;
  1422. }
  1423. else if(!strncmp(ptr,"<a href=\"",9)) {
  1424. ptr = strchr(ptr,'>');
  1425. ptr++;
  1426. char *link = ptr;
  1427. ptr = strstr(link,"</a>");
  1428. memcpy(name+i,link,ptr-link);
  1429. i += ptr-link;
  1430. ptr += 4;
  1431. }
  1432. else name[i++] = *ptr++;
  1433. }
  1434. else name[i++] = *ptr++;
  1435. }
  1436. resData->appendBytes(name, i);
  1437. resData->appendBytes("<>", 2);
  1438. if(mail[0]) resData->appendBytes(mail ,strlen(mail));
  1439. resData->appendBytes("<>", 2);
  1440. ptr = strstr(ptr," class=\"date\">");
  1441. if(ptr) {
  1442. char *tmp = ptr;
  1443. *ptr = 0;
  1444. while(*ptr != '<') ptr--;
  1445. snprintf(closeTag,32,"</%s>",ptr+1);
  1446. closeTagLen = strlen(closeTag);
  1447. ptr = tmp + 14;
  1448. }
  1449. else {
  1450. delete resData;
  1451. break;
  1452. }
  1453. i=0;
  1454. while(1) {
  1455. if(*ptr == '<') {
  1456. if(!strncasecmp(ptr,closeTag,closeTagLen)) {
  1457. ptr += closeTagLen;
  1458. break;
  1459. }
  1460. else date[i++] = *ptr++;
  1461. }
  1462. else date[i++] = *ptr++;
  1463. }
  1464. if(!strncmp(ptr,"<div class=\"uid",15) || !strncmp(ptr,"<span class=\"uid",16)) {
  1465. char *tmp = ptr+1;
  1466. while(*ptr != ' ') ptr++;
  1467. *ptr = 0;
  1468. snprintf(closeTag,32,"</%s>",tmp);
  1469. closeTagLen = strlen(closeTag);
  1470. ptr += 11;
  1471. while(*ptr != '>') ptr++;
  1472. ptr++;
  1473. date[i++] = ' ';
  1474. while(1) {
  1475. if(*ptr == '<') {
  1476. if(!strncasecmp(ptr,closeTag,closeTagLen)) {
  1477. ptr += closeTagLen;
  1478. break;
  1479. }
  1480. else date[i++] = *ptr++;
  1481. }
  1482. else date[i++] = *ptr++;
  1483. }
  1484. }
  1485. if(!strncmp(ptr,"<div class=\"be",14) || !strncmp(ptr,"<span class=\"be",15)) {
  1486. ptr += 14;
  1487. while(*ptr != '>') ptr++;
  1488. ptr++;
  1489. if(!strncmp(ptr,"<a href=\"",9)) {
  1490. ptr += 9;
  1491. while(*ptr != '/' && *ptr != '"') ptr++;
  1492. if(*ptr == '/' && (!strncmp(ptr,"//be.2ch.net/user/",18) || !strncmp(ptr,"//be.5ch.net/user/",18))) {
  1493. memcpy(date+i," BE:",4);
  1494. i += 4;
  1495. ptr += 18;
  1496. while(*ptr != '"') date[i++] = *ptr++;
  1497. date[i++] = '-';
  1498. ptr = strchr(ptr,'?');
  1499. ptr++;
  1500. char *tmp = strstr(ptr,"</a>");
  1501. memcpy(date+i,ptr,tmp-ptr);
  1502. i += tmp-ptr;
  1503. ptr = tmp + 4;
  1504. }
  1505. }
  1506. }
  1507. resData->appendBytes(date ,i);
  1508. resData->appendBytes("<>", 2);
  1509. if(!strcmp(signatureTag,"<div")) {
  1510. ptr = strstr(ptr,"<div class=\"message\">");
  1511. if(!ptr) {
  1512. delete resData;
  1513. break;
  1514. }
  1515. else {
  1516. ptr += 21;
  1517. if(!strncasecmp(ptr,"<span class=\"escaped\">",22)) {
  1518. if(!strncasecmp(ptr+22,"<span class=\"AA\">",17)) {
  1519. strcpy(closeTag,"</span></span></div>");
  1520. closeTagLen = 20;
  1521. ptr += 22+17;
  1522. }
  1523. else {
  1524. strcpy(closeTag,"</span></div>");
  1525. closeTagLen = 13;
  1526. ptr += 22;
  1527. }
  1528. }
  1529. else {
  1530. strcpy(closeTag,"</div>");
  1531. closeTagLen = 6;
  1532. }
  1533. }
  1534. }
  1535. else {
  1536. ptr = strstr(ptr,"<dd class=\"thread_in\">");
  1537. if(!ptr) {
  1538. delete resData;
  1539. break;
  1540. }
  1541. strcpy(closeTag,"</dd>");
  1542. closeTagLen = 5;
  1543. ptr += 22;
  1544. }
  1545. i=0;
  1546. while(1) {
  1547. if(*ptr == '<') {
  1548. if(!strncasecmp(ptr,closeTag,closeTagLen)) {
  1549. ptr += closeTagLen;
  1550. break;
  1551. }
  1552. else if(!strncmp(ptr,"<span class=\"__cf_email__\"",26) || !strncmp(ptr,"<a class=\"__cf_email__\"",23)) {
  1553. int j=0;
  1554. ptr = strstr(ptr,"data-cfemail=\"");
  1555. ptr += 14;
  1556. while(*ptr != '"') encrypted[j++] = *ptr++;
  1557. encrypted[j] = 0;
  1558. j = decryptMail(body+i,encrypted);
  1559. i += j;
  1560. ptr = strstr(ptr,"</script>");
  1561. ptr += 9;
  1562. }
  1563. else if(!strncmp(ptr,"<a ",3)) {
  1564. char *tmp = strchr(ptr,'>');
  1565. char *href = (char *)memmem_priv(ptr,tmp-ptr,"href=\"",6);
  1566. char *link = tmp+1;
  1567. if(href && !strncmp(link,"&gt;&gt;",8) && memmem_priv(href,link-href,"test/read.cgi/",14)) {
  1568. while(ptr < link) {
  1569. if(!strncmp(ptr," class=\"",8)) {
  1570. ptr += 8;
  1571. while(*ptr != '"' && *ptr != '>') ptr++;
  1572. if(*ptr == '"') ptr++;
  1573. }
  1574. else body[i++] = *ptr++;
  1575. }
  1576. }
  1577. else {
  1578. ptr = strstr(link,"</a>");
  1579. memcpy(body+i,link,ptr-link);
  1580. i += ptr-link;
  1581. ptr += 4;
  1582. }
  1583. }
  1584. else if(!strncmp(ptr,"<img src=\"",10)) {
  1585. ptr += 10;
  1586. char *img = ptr;
  1587. ptr = strstr(img,"\">");
  1588. memcpy(body+i,img,ptr-img);
  1589. 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)) {
  1590. int length = ptr-img;
  1591. while(*img != '/') {
  1592. img++;
  1593. length--;
  1594. }
  1595. memcpy(body+i,"sssp:",5);
  1596. memcpy(body+i+5,img,length);
  1597. i += length + 5;
  1598. }
  1599. else i += ptr-img;
  1600. ptr += 2;
  1601. }
  1602. else if(!strncmp(ptr,"<br>",4)) {
  1603. if(i>5 && !strncmp((char *)body+i-5,"<br> ",5)) {
  1604. memcpy(body+i," <br>",5);
  1605. i += 5;
  1606. }
  1607. else {
  1608. memcpy(body+i,"<br>",4);
  1609. i += 4;
  1610. }
  1611. ptr += 4;
  1612. }
  1613. else body[i++] = *ptr++;
  1614. }
  1615. else body[i++] = *ptr++;
  1616. }
  1617. resData->appendBytes(body ,i);
  1618. resData->appendBytes("<>", 2);
  1619. if(res == 1) resData->appendBytes(title ,strlen(title));
  1620. resData->appendBytes("\n" ,1);
  1621. if(useCache && res == startResNum) {
  1622. PBBS2chProxyThreadInfo info;
  1623. bool hit = false;
  1624. pthread_mutex_lock(mutex);
  1625. BBS2chProxyThreadCache::iterator it = threadCache->find(threadKey);
  1626. if(it != threadCache->end()) {
  1627. info = it->second;
  1628. threadCache->erase(it);
  1629. }
  1630. pthread_mutex_unlock(mutex);
  1631. if(info) {
  1632. log_printf(5,"cache hit");
  1633. if(info->cachedData->length == resData->length) {
  1634. log_printf(5,"... size match");
  1635. if(!memcmp(info->cachedData->bytes,resData->bytes,resData->length)) {
  1636. log_printf(5,"... content match");
  1637. hit = true;
  1638. cachedSize = info->cachedSize - resData->length;
  1639. }
  1640. }
  1641. log_printf(5,"\n");
  1642. }
  1643. if(!hit) {
  1644. delete resData;
  1645. free(buffer);
  1646. return NULL;
  1647. }
  1648. }
  1649. txt->appendBytes(resData->bytes, resData->length);
  1650. res++;
  1651. while(*ptr == '\n' || *ptr == '\r') ptr++;
  1652. snprintf(signature,64,"%s class=\"post\" id=\"",signatureTag);
  1653. ptr = (char *)memmem_priv(ptr, end-ptr+1, signature, strlen(signature));
  1654. if(ptr) {
  1655. int next = atoi(ptr+strlen(signature));
  1656. if(next >= res) {
  1657. while(next > res) {
  1658. txt->appendBytes("broken<><>broken<> broken <>\n", 29);
  1659. res++;
  1660. }
  1661. }
  1662. else ptr = NULL;
  1663. }
  1664. if(!ptr) {
  1665. PBBS2chProxyThreadInfo info(new BBS2chProxyThreadInfo());
  1666. info->lastResNum = res-1;
  1667. info->cachedSize = txt->length+cachedSize;
  1668. info->cachedData = resData;
  1669. pthread_mutex_lock(mutex);
  1670. threadCache->insert(std::make_pair(threadKey,info));
  1671. pthread_mutex_unlock(mutex);
  1672. log_printf(5,"cached thread %s (%ld bytes)\n",threadKey.c_str(),(long)resData->length);
  1673. if(lastModified) {
  1674. *lastModified = 0;
  1675. char formattedDate[256];
  1676. char *ptr;
  1677. ptr = date;
  1678. int year = strtol(ptr,&ptr,10);
  1679. if(*ptr != '/') break;
  1680. ptr++;
  1681. int month = strtol(ptr,&ptr,10);
  1682. if(*ptr != '/') break;
  1683. ptr++;
  1684. int day = strtol(ptr,&ptr,10);
  1685. if(!*ptr) break;
  1686. while(*ptr != ' ' && *ptr != 0) ptr++;
  1687. if(!*ptr) break;
  1688. ptr++;
  1689. int hour = strtol(ptr,&ptr,10);
  1690. if(*ptr != ':') break;
  1691. ptr++;
  1692. int minutes = strtol(ptr,&ptr,10);
  1693. if(*ptr != ':') break;
  1694. ptr++;
  1695. int seconds = strtol(ptr,&ptr,10);
  1696. if(!(month>0 && month<13) || !(day>0 && day<32)) break;
  1697. if(year < 100) year += 2000;
  1698. snprintf(formattedDate,256,"%d/%d/%d %02d:%02d:%02d JST",year,month,day,hour,minutes,seconds);
  1699. //fprintf(stderr,"%s\n",formattedDate);
  1700. struct tm time = {};
  1701. strptime(formattedDate,threadTimestampFmt,&time);
  1702. *lastModified = mktime(&time);
  1703. //gmtime_r(lastModified,&time);
  1704. //strftime(formattedDate,256,httpTimestampFmt,&time);
  1705. //fprintf(stderr,"%s\n",formattedDate);
  1706. }
  1707. //fprintf(stderr,"not found,%ld\n",end-ptr+1);
  1708. break;
  1709. }
  1710. delete resData;
  1711. }
  1712. free(buffer);
  1713. return txt;
  1714. }
  1715. int BBS2chProxyConnection::datProxyAPI(const char *url, const char *method)
  1716. {
  1717. long statusCode = 0;
  1718. std::string postBody = auth->requestBodyForURL(url);
  1719. if(postBody.empty()) {
  1720. sendResponse(401, "Unauthorized", socketToClient);
  1721. return 401;
  1722. }
  1723. CURL *curl = curl_easy_init();
  1724. char *buf = (char *)malloc(16384);
  1725. if(curl) {
  1726. CURLcode res;
  1727. struct curl_slist *headersForCurl = NULL;
  1728. DataStorage *receivedHeader = new DataStorage();
  1729. DataStorage *receivedBody = new DataStorage();
  1730. BBS2chProxyHttpHeaders headers;
  1731. while(socketToClient->readLine(buf, 16384)) {
  1732. //fprintf(stderr,"%s",buf);
  1733. if(!strcmp("\r\n",buf)) break;
  1734. headers.add(buf);
  1735. }
  1736. headersForCurl = headers.appendToCurlSlist(headersForCurl, "Range");
  1737. headersForCurl = headers.appendToCurlSlist(headersForCurl, "If-Modified-Since");
  1738. headersForCurl = headers.appendToCurlSlist(headersForCurl, "Accept-Encoding");
  1739. if(x_2ch_ua_dat) headersForCurl = curl_slist_append(headersForCurl, x_2ch_ua_dat);
  1740. if(curl_share) curl_easy_setopt(curl, CURLOPT_SHARE, curl_share);
  1741. curl_easy_setopt(curl, CURLOPT_URL, url);
  1742. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headersForCurl);
  1743. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
  1744. curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  1745. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback_download);
  1746. curl_easy_setopt(curl, CURLOPT_WRITEDATA, receivedBody);
  1747. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, header_callback_download);
  1748. curl_easy_setopt(curl, CURLOPT_HEADERDATA, receivedHeader);
  1749. curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
  1750. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
  1751. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
  1752. if(force_ipv4) curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
  1753. if(proxy_server) {
  1754. curl_easy_setopt(curl, CURLOPT_PROXY, proxy_server);
  1755. curl_easy_setopt(curl, CURLOPT_PROXYPORT, proxy_port);
  1756. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, proxy_type);
  1757. }
  1758. curl_easy_setopt(curl, CURLOPT_USERAGENT, api_ua_dat?api_ua_dat:"");
  1759. curl_easy_setopt(curl, CURLOPT_POST, 1L);
  1760. #if LIBCURL_VERSION_NUM >= 0x071101
  1761. curl_easy_setopt(curl, CURLOPT_COPYPOSTFIELDS, postBody.c_str());
  1762. #else
  1763. curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postBody.c_str());
  1764. #endif
  1765. //return;
  1766. res = curl_easy_perform(curl);
  1767. if(res == CURLE_OK) {
  1768. curl_easy_getinfo(curl,CURLINFO_RESPONSE_CODE, &statusCode);
  1769. receivedHeader->appendBytes("",1);
  1770. char *ptr = strstr(receivedHeader->bytes,"\r\n\r\n");
  1771. *(ptr+4) = 0;
  1772. int threadStatus = 0;
  1773. for(char *ptr2 = receivedHeader->bytes; ptr2<ptr;) {
  1774. if(!strncasecmp(ptr2, "Thread-Status:", strlen("Thread-Status:"))) {
  1775. ptr2 += strlen("Thread-Status:");
  1776. while(*ptr2 == ' ') ptr2++;
  1777. threadStatus = atoi(ptr2);
  1778. break;
  1779. }
  1780. ptr2 = strstr(ptr2, "\r\n") + 2;
  1781. }
  1782. if(threadStatus == 1) {
  1783. if(ptr+4-receivedHeader->bytes > socketToClient->write(receivedHeader->bytes, ptr+4-receivedHeader->bytes)) goto last;
  1784. if(receivedBody->length > socketToClient->write(receivedBody->bytes, receivedBody->length)) goto last;
  1785. goto last;
  1786. }
  1787. else if(threadStatus == 8) {
  1788. sendBasicHeaders(302, "Found", socketToClient);
  1789. if(0 >= socketToClient->writeString("Location: http://www2.2ch.net/live.html\r\n")) goto last;
  1790. if(0 >= socketToClient->writeString("\r\n")) goto last;
  1791. statusCode = 302;
  1792. goto last;
  1793. }
  1794. else {
  1795. if (statusCode < 400) {
  1796. sendResponse(401, "Unauthorized", socketToClient);
  1797. statusCode = 401;
  1798. }
  1799. else {
  1800. sendResponse(503, "Service Unavailable", socketToClient);
  1801. statusCode = 503;
  1802. }
  1803. receivedBody->appendBytes("",1);
  1804. if(!strncasecmp(receivedBody->bytes,"ng (",4)) {
  1805. log_printf(0,"API gateway returned error: %s\n",receivedBody->bytes);
  1806. }
  1807. }
  1808. //fprintf(stderr,"%ld\n",statusCode);
  1809. }
  1810. else {
  1811. log_printf(0,"curl error: %s\n",curl_easy_strerror(res));
  1812. sendResponse(503, "Service Unavailable", socketToClient);
  1813. statusCode = 503;
  1814. }
  1815. last:
  1816. curl_easy_cleanup(curl);
  1817. curl_slist_free_all(headersForCurl);
  1818. delete receivedBody;
  1819. delete receivedHeader;
  1820. }
  1821. free(buf);
  1822. return statusCode;
  1823. }
  1824. int BBS2chProxyConnection::bbsmenuProxy(const char *url, const char *method)
  1825. {
  1826. long statusCode = 0;
  1827. DataStorage *dat = new DataStorage();
  1828. DataStorage *outHTML = new DataStorage();
  1829. char *buf = (char *)malloc(16384);
  1830. CURL *curl = NULL;
  1831. BBS2chProxyHttpHeaders headers;
  1832. if(!buf) goto last;
  1833. while(socketToClient->readLine(buf, 16384)) {
  1834. //fprintf(stderr,"%s",buf);
  1835. if(!strcmp("\r\n",buf)) break;
  1836. headers.add(buf);
  1837. }
  1838. curl = curl_easy_init();
  1839. if(curl) {
  1840. CURLcode res;
  1841. if(curl_share) curl_easy_setopt(curl, CURLOPT_SHARE, curl_share);
  1842. curl_easy_setopt(curl, CURLOPT_URL, url);
  1843. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
  1844. curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  1845. curl_easy_setopt(curl, CURLOPT_ENCODING, "");
  1846. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback_download);
  1847. curl_easy_setopt(curl, CURLOPT_WRITEDATA, dat);
  1848. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  1849. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
  1850. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
  1851. if(force_ipv4) curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
  1852. if(proxy_server) {
  1853. curl_easy_setopt(curl, CURLOPT_PROXY, proxy_server);
  1854. curl_easy_setopt(curl, CURLOPT_PROXYPORT, proxy_port);
  1855. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, proxy_type);
  1856. }
  1857. if(user_agent) {
  1858. curl_easy_setopt(curl, CURLOPT_USERAGENT, user_agent);
  1859. }
  1860. else if(headers.has("User-Agent")) {
  1861. curl_easy_setopt(curl, CURLOPT_USERAGENT, headers.get("User-Agent").c_str());
  1862. }
  1863. res = curl_easy_perform(curl);
  1864. if(res == CURLE_OK) {
  1865. curl_easy_getinfo(curl,CURLINFO_RESPONSE_CODE, &statusCode);
  1866. if(statusCode == 200 && dat->length) {
  1867. dat->appendBytes("",1);
  1868. dat->length--;
  1869. char *ptr = dat->bytes;
  1870. while(*ptr) {
  1871. if(!strncasecmp(ptr,"<a href=",8)) {
  1872. char *start = ptr;
  1873. char *end = strchr(ptr+8,'>');
  1874. ptr = strstr(ptr+8,"://");
  1875. if(ptr && ptr < end) {
  1876. char *protocol = ptr;
  1877. char *end2 = strchr(ptr+3,'/');
  1878. ptr = strstr(protocol+3,"5ch.net");
  1879. if(ptr && ptr < end2 && (*(ptr-1)=='.' || *(ptr-1)=='/')) {
  1880. memcpy(ptr,"2ch",3);
  1881. if(*(protocol-1) == 's') outHTML->appendBytes(start, protocol-start-1);
  1882. else outHTML->appendBytes(start, protocol-start);
  1883. outHTML->appendBytes(protocol, end-protocol);
  1884. ptr = end;
  1885. continue;
  1886. }
  1887. ptr = strstr(protocol+3,"bbspink.com");
  1888. if(ptr && ptr < end2 && (*(ptr-1)=='.' || *(ptr-1)=='/')) {
  1889. if(*(protocol-1) == 's') outHTML->appendBytes(start, protocol-start-1);
  1890. else outHTML->appendBytes(start, protocol-start);
  1891. outHTML->appendBytes(protocol, end-protocol);
  1892. ptr = end;
  1893. continue;
  1894. }
  1895. }
  1896. ptr = start;
  1897. }
  1898. outHTML->appendBytes(ptr++, 1);
  1899. }
  1900. }
  1901. }
  1902. else {
  1903. log_printf(0,"curl error: %s (%s)\n",curl_easy_strerror(res),buf);
  1904. statusCode = 503;
  1905. }
  1906. }
  1907. if(statusCode == 200) {
  1908. std::ostringstream ss;
  1909. ss << "Content-Length: " << outHTML->length << "\r\n";
  1910. sendBasicHeaders(statusCode,"OK",socketToClient);
  1911. if(0 >= socketToClient->writeString("Content-Type: text/html\r\n")) goto last;
  1912. if(0 >= socketToClient->writeString(ss.str())) goto last;
  1913. if(0 >= socketToClient->writeString("\r\n")) goto last;
  1914. if(strcasecmp(method, "HEAD")) {
  1915. if(outHTML->length > socketToClient->write(outHTML->bytes, outHTML->length)) goto last;
  1916. }
  1917. }
  1918. else {
  1919. sendResponse(503, "Service Unavailable", socketToClient);
  1920. statusCode = 503;
  1921. }
  1922. last:
  1923. if(curl) curl_easy_cleanup(curl);
  1924. if(buf) free(buf);
  1925. if(dat) delete dat;
  1926. if(outHTML) delete outHTML;
  1927. return statusCode;
  1928. }
  1929. int BBS2chProxyConnection::bbsCgiProxy(const char *url, const char *protocol, BBS2chProxyHttpHeaders *requestHeaders, const char *requestBody)
  1930. {
  1931. CURL *curl = curl_easy_init();
  1932. long statusCode = 0;
  1933. std::string hostStr = requestHeaders->get("Host");
  1934. std::string boardStr;
  1935. std::string threadStr;
  1936. requestHeaders->remove("Host");
  1937. if (user_agent) requestHeaders->set("User-Agent", user_agent);
  1938. if (requestBody && (lua_script || !bbscgi_headers.empty() || !bbscgi_postorder.empty())) {
  1939. std::map<std::string, std::string> fields;
  1940. const char *ptr = requestBody;
  1941. size_t bodyLength = 0;
  1942. while (1) {
  1943. const char *tmp = ptr;
  1944. while (*tmp != '=' && *tmp != 0) tmp++;
  1945. if (*tmp == 0) {
  1946. bodyLength = tmp - requestBody;
  1947. break;
  1948. }
  1949. std::string key(ptr, tmp-ptr);
  1950. tmp++;
  1951. ptr = tmp;
  1952. while (*tmp != '&' && *tmp != 0) tmp++;
  1953. std::string value(ptr, tmp-ptr);
  1954. fields.insert(std::make_pair(key, value));
  1955. if (*tmp == 0) {
  1956. bodyLength = tmp - requestBody;
  1957. break;
  1958. }
  1959. ptr = tmp + 1;
  1960. }
  1961. if (fields.count("bbs")) boardStr = fields["bbs"];
  1962. if (fields.count("key")) threadStr = fields["key"];
  1963. if (!bbscgi_postorder.empty()) {
  1964. std::string newBody;
  1965. for (std::vector<std::string>::iterator it = bbscgi_postorder.begin(); it != bbscgi_postorder.end(); it++) {
  1966. std::string &name = *it;
  1967. if (fields.count(name)) {
  1968. if (!newBody.empty()) newBody.append("&");
  1969. newBody.append(name);
  1970. newBody.append("=");
  1971. newBody.append(fields[name]);
  1972. fields.erase(name);
  1973. }
  1974. }
  1975. for (std::map<std::string, std::string>::iterator it = fields.begin(); it != fields.end(); it++) {
  1976. if (!newBody.empty()) newBody.append("&");
  1977. newBody.append(it->first);
  1978. newBody.append("=");
  1979. newBody.append(it->second);
  1980. }
  1981. if (bodyLength == newBody.length()) {
  1982. strcpy((char *)requestBody, newBody.c_str());
  1983. log_printf(1, "Reordered request body is: %s\n", requestBody);
  1984. }
  1985. else {
  1986. log_printf(0, "Error occured while reordering the request body - skipping\n");
  1987. }
  1988. }
  1989. }
  1990. if (!bbscgi_headers.empty()) {
  1991. for (std::map<std::string, std::string>::iterator it = bbscgi_headers.begin(); it!=bbscgi_headers.end(); it++) {
  1992. /* we cannot use a reference here, because the original string shouldn't be replaced */
  1993. std::string value = it->second;
  1994. if (!hostStr.empty()) {
  1995. std::string::size_type pos = value.find("%HOST%");
  1996. while (pos != std::string::npos) {
  1997. value.replace(pos, 6, hostStr);
  1998. pos = value.find("%HOST%", pos+hostStr.length());
  1999. }
  2000. }
  2001. if (!boardStr.empty()) {
  2002. std::string::size_type pos = value.find("%BOARD%");
  2003. while (pos != std::string::npos) {
  2004. value.replace(pos, 7, boardStr);
  2005. pos = value.find("%BOARD%", pos+boardStr.length());
  2006. }
  2007. }
  2008. if (!threadStr.empty()) {
  2009. std::string::size_type pos = value.find("%THREAD%");
  2010. while (pos != std::string::npos) {
  2011. value.replace(pos, 8, threadStr);
  2012. pos = value.find("%THREAD%", pos+threadStr.length());
  2013. }
  2014. }
  2015. requestHeaders->set(it->first, value);
  2016. log_printf(1, "Appended custom header \"%s: %s\"\n", it->first.c_str(), value.c_str());
  2017. }
  2018. }
  2019. for (int run=0; run<2; run++) {
  2020. BBS2chProxyHttpHeaders *_headers = requestHeaders;
  2021. curl_slist *headersForCurl = NULL;
  2022. char *_body = (char *)requestBody;
  2023. status = 0;
  2024. monaKeyForRequest = "";
  2025. #ifdef USE_LUA
  2026. if (lua_script) {
  2027. lua_State* l = luaL_newstate();
  2028. luaL_openlibs(l);
  2029. if (luaL_loadfile(l, lua_script) != LUA_OK) {
  2030. log_printf(0, "Lua: Failed to open script %s:\n %s\n", lua_script, lua_tostring(l, -1));
  2031. goto lua_end;
  2032. }
  2033. lua_newtable(l);
  2034. lua_pushcfunction(l, lua_hmacSHA256);
  2035. lua_setfield(l, -2, "hmacSHA256");
  2036. lua_pushcfunction(l, lua_decodeURIComponent);
  2037. lua_setfield(l, -2, "decodeURIComponent");
  2038. lua_pushcfunction(l, lua_encodeURIComponent);
  2039. lua_setfield(l, -2, "encodeURIComponent");
  2040. lua_pushcfunction(l, lua_convertShiftJISToUTF8);
  2041. lua_setfield(l, -2, "convertShiftJISToUTF8");
  2042. lua_pushcfunction(l, lua_isExpiredKey);
  2043. lua_setfield(l, -2, "isExpiredKey");
  2044. lua_pushcfunction(l, lua_isValidAsUTF8);
  2045. lua_setfield(l, -2, "isValidAsUTF8");
  2046. lua_pushstring(l, getMonaKey().c_str());
  2047. lua_setfield(l, -2, "monaKey");
  2048. lua_setglobal(l, "proxy2ch");
  2049. BBS2chProxyHttpHeaders::getClassDefinitionForLua(l);
  2050. lua_setglobal(l, "HttpHeaders");
  2051. if (lua_pcall(l, 0, 0, 0) != LUA_OK) {
  2052. log_printf(0, "Lua: Failed to run script %s:\n %s\n", lua_script, lua_tostring(l, -1));
  2053. goto lua_end;
  2054. }
  2055. lua_getglobal(l, "willSendRequestToBbsCgi");
  2056. if (!lua_isfunction(l, -1)) {
  2057. log_printf(0, "Lua: willSendRequestToBbsCgi function does not exist in the script\n");
  2058. goto lua_end;
  2059. }
  2060. lua_newtable(l);
  2061. _headers->getUserdataForLua(l);
  2062. lua_setfield(l, -2, "headers");
  2063. lua_pushstring(l, _body);
  2064. lua_setfield(l, -2, "body");
  2065. lua_pushstring(l, hostStr.c_str());
  2066. lua_pushstring(l, boardStr.c_str());
  2067. lua_pushstring(l, threadStr.c_str());
  2068. if (lua_pcall(l, 4, 1, 0) != LUA_OK) {
  2069. log_printf(0, "Lua: Failed to call willSendRequestToBbsCgi function:\n %s\n", lua_tostring(l, -1));
  2070. goto lua_end;
  2071. }
  2072. if (!lua_istable(l, -1)) {
  2073. log_printf(0, "Lua: A return type of willSendRequestToBbsCgi function should be a table\n");
  2074. goto lua_end;
  2075. }
  2076. lua_pushstring(l, "body");
  2077. lua_rawget(l, -2);
  2078. if (lua_isstring(l, -1)) {
  2079. const char *newBody = lua_tostring(l, -1);
  2080. _body = strdup(newBody);
  2081. log_printf(1, "Lua: Set request body \"%s\"\n", newBody);
  2082. }
  2083. lua_pop(l, 1);
  2084. lua_pushstring(l, "headers");
  2085. lua_rawget(l, -2);
  2086. if (lua_istable(l, -1)) {
  2087. _headers = new BBS2chProxyHttpHeaders();
  2088. lua_pushnil(l);
  2089. while (lua_next(l, -2)) {
  2090. if (lua_isstring(l, -1) && lua_isstring(l, -2)) {
  2091. const char *name = lua_tostring(l, -2);
  2092. const char *value = lua_tostring(l, -1);
  2093. _headers->add(name, value);
  2094. log_printf(1, "Lua: Set request header \"%s: %s\"\n", name, value);
  2095. }
  2096. lua_pop(l, 1);
  2097. }
  2098. }
  2099. else if (lua_isuserdata(l, -1)) {
  2100. if (lua_getmetatable(l, -1)) {
  2101. if (lua_getfield(l, -1, "_type") == LUA_TSTRING) {
  2102. if (!strcmp(lua_tostring(l, -1), "HttpHeaders")) {
  2103. BBS2chProxyHttpHeaders *newHeaders = *((BBS2chProxyHttpHeaders **)lua_touserdata(l, -3));
  2104. if (newHeaders != _headers) {
  2105. /* remove metatable to prevent the object from garbage collected by lua */
  2106. lua_newtable(l);
  2107. lua_setmetatable(l, -4);
  2108. _headers = newHeaders;
  2109. }
  2110. for (std::map<std::string, PBBS2chProxyHttpHeaderEntry>::iterator it = _headers->getMap().begin(); it != _headers->getMap().end(); it++) {
  2111. log_printf(1, "Lua: Set request header \"%s\"\n", it->second->getFull().c_str());
  2112. }
  2113. }
  2114. }
  2115. lua_pop(l, 2);
  2116. }
  2117. }
  2118. lua_end:
  2119. lua_close(l);
  2120. }
  2121. #endif
  2122. do {
  2123. bool isPink = hostStr.find("bbspink.com") != std::string::npos;
  2124. bool shouldSign = appKey && (((api_mode & 2) && !isPink) || (api_mode & 4));
  2125. bool shouldConvertBodyToUTF8 = (bbscgi_utf8 == 1 && shouldSign) || (bbscgi_utf8 == 2);
  2126. std::string userAgent = _headers->get("User-Agent");
  2127. if (_headers->has("X-MonaKey")) {
  2128. monaKeyForRequest = _headers->get("X-MonaKey");
  2129. }
  2130. if (shouldConvertBodyToUTF8 && !_headers->has("X-PostSig")) {
  2131. std::string newBody = convertBodyToUTF8(_body);
  2132. if (!newBody.empty()) {
  2133. if (_body != requestBody) {
  2134. free(_body);
  2135. }
  2136. _body = strdup(newBody.c_str());
  2137. log_printf(1, "Converted request body to UTF-8: %s\n", _body);
  2138. }
  2139. else {
  2140. log_printf(1, "Request body seems already to be UTF-8, will be sent without conversion\n");
  2141. }
  2142. _headers->set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
  2143. log_printf(1, "Appended header \"Content-Type: application/x-www-form-urlencoded; charset=UTF-8\"\n");
  2144. }
  2145. if (shouldSign && (!lua_script || !_headers->has("X-PostSig"))) {
  2146. if (userAgent.empty() && user_agent) userAgent = user_agent;
  2147. if (!userAgent.empty()) {
  2148. monaKeyForRequest = getMonaKey();
  2149. appendPostSignature(_body, userAgent, monaKeyForRequest, _headers);
  2150. } else {
  2151. log_printf(0, "API: User-Agent muse be set explicitly to post with API.\n");
  2152. }
  2153. }
  2154. if (!monaKeyForRequest.empty() && monaKeyIssueTime.count(monaKeyForRequest)) {
  2155. double issued = monaKeyIssueTime[monaKeyForRequest];
  2156. double now = getCurrentTime();
  2157. double wait = 4.0 - (now - issued);
  2158. if (wait > 0) {
  2159. log_printf(1, "Sleeping for %.1f seconds to avoid posting too fast...\n", wait);
  2160. #ifdef _WIN32
  2161. Sleep(wait * 1e+3);
  2162. #else
  2163. usleep(wait * 1e+6);
  2164. #endif
  2165. }
  2166. monaKeyIssueTime.erase(monaKeyForRequest);
  2167. }
  2168. headersForCurl = _headers->appendToCurlSlist(headersForCurl);
  2169. if (!_headers->has("Expect")) headersForCurl = curl_slist_append(headersForCurl, "Expect:");
  2170. if (!_headers->has("Accept")) headersForCurl = curl_slist_append(headersForCurl, "Accept:");
  2171. } while (0);
  2172. if (curl) {
  2173. CURLcode res;
  2174. if (curl_share) curl_easy_setopt(curl, CURLOPT_SHARE, curl_share);
  2175. curl_easy_setopt(curl, CURLOPT_URL, url);
  2176. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
  2177. curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  2178. if (run == 0)
  2179. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, header_callback_bbscgi);
  2180. else
  2181. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, header_callback_proxy);
  2182. curl_easy_setopt(curl, CURLOPT_HEADERDATA, this);
  2183. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback_proxy);
  2184. curl_easy_setopt(curl, CURLOPT_WRITEDATA, this);
  2185. curl_easy_setopt(curl, CURLOPT_POST, 1L);
  2186. curl_easy_setopt(curl, CURLOPT_POSTFIELDS, _body);
  2187. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
  2188. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
  2189. //curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
  2190. if (force_ipv4) curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
  2191. if (!strncasecmp(protocol,"HTTP/1.0",8) && !strncasecmp(url, "http://", 7)) {
  2192. curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
  2193. }
  2194. else {
  2195. /* force use HTTP 1.1 because CURL_HTTP_VERSION_2TLS is used on curl (w/ nghttp2) >= 7.62.0 */
  2196. curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
  2197. }
  2198. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headersForCurl);
  2199. if (user_agent) {
  2200. curl_easy_setopt(curl, CURLOPT_USERAGENT, user_agent);
  2201. }
  2202. if (proxy_server) {
  2203. curl_easy_setopt(curl, CURLOPT_PROXY, proxy_server);
  2204. curl_easy_setopt(curl, CURLOPT_PROXYPORT, proxy_port);
  2205. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, proxy_type);
  2206. }
  2207. res = curl_easy_perform(curl);
  2208. if (res != CURLE_OK) {
  2209. if (res == CURLE_WRITE_ERROR && status == 2) {
  2210. log_printf(1, "MonaKey should be reset. Sending the same request automatically...\n");
  2211. curl_easy_reset(curl);
  2212. curl_slist_free_all(headersForCurl);
  2213. if (_headers != requestHeaders) delete _headers;
  2214. if (_body != requestBody) free(_body);
  2215. continue;
  2216. }
  2217. else {
  2218. log_printf(0,"curl error: %s (%s)\n",curl_easy_strerror(res),url);
  2219. if (!status) sendResponse(503, "Service Unavailable", socketToClient);
  2220. statusCode = 503;
  2221. }
  2222. }
  2223. else {
  2224. if (chunked) {
  2225. socketToClient->writeString("0\r\n\r\n");
  2226. }
  2227. curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &statusCode);
  2228. }
  2229. curl_easy_cleanup(curl);
  2230. }
  2231. curl_slist_free_all(headersForCurl);
  2232. if (_headers != requestHeaders) delete _headers;
  2233. if (_body != requestBody) free(_body);
  2234. break;
  2235. }
  2236. return statusCode;
  2237. }
  2238. void BBS2chProxyConnection::compileRegex(void)
  2239. {
  2240. static int compiled;
  2241. if (compiled) return;
  2242. regcomp(&regex, "^https?://([^:/.]+)\\.(2ch\\.net|5ch\\.net|bbspink\\.com)(:[0-9]+)?/([^/]+)/dat/([0-9]+)\\.dat", REG_EXTENDED|REG_ICASE);
  2243. regcomp(&regex_kako, "^https?://([^:/.]+)\\.(2ch\\.net|5ch\\.net|bbspink\\.com)(:[0-9]+)?/([^/]+)/kako/[0-9]+/([0-9]+/)?([0-9]+)\\.dat", REG_EXTENDED|REG_ICASE);
  2244. regcomp(&regex_offlaw, "^https?://([^:/.]+)\\.(2ch\\.net|5ch\\.net|bbspink\\.com)(:[0-9]+)?/test/offlaw2.so\\?.*bbs=([^&]+)", REG_EXTENDED|REG_ICASE);
  2245. compiled = 1;
  2246. }