BBS2chProxyConnection.cpp 55 KB

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