BBS2chProxyConnection.cpp 52 KB

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