BBS2chProxyConnection.cpp 68 KB

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