BBS2chProxyConnection.cpp 69 KB

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