BBS2chProxyConnection.cpp 70 KB

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