BBS2chProxyConnection.cpp 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507
  1. #include <string>
  2. #include <vector>
  3. #include <map>
  4. #include <set>
  5. #include <sstream>
  6. #include <stdexcept>
  7. #include <algorithm>
  8. #include <pthread.h>
  9. #include <time.h>
  10. #include <stdlib.h>
  11. #include <string.h>
  12. #include <unistd.h>
  13. #ifdef _WIN32
  14. #include <fcntl.h>
  15. #include <winsock2.h>
  16. #include <ws2tcpip.h>
  17. #include <mswsock.h>
  18. #define CLOSESOCKET(x) closesocket(x)
  19. #define gmtime_r(a, b) gmtime_s(b, a)
  20. #else
  21. #include <sys/socket.h>
  22. #include <netinet/in.h>
  23. #include <netdb.h>
  24. #include <arpa/inet.h>
  25. #include <poll.h>
  26. #define CLOSESOCKET(x) close(x)
  27. #endif
  28. #include "BBS2chProxyConnection.h"
  29. #include "BBS2chProxyRawSocket.h"
  30. #include "BBS2chProxyPoster.h"
  31. #ifdef USE_MITM
  32. #include "BBS2chProxySecureSocket.h"
  33. #endif
  34. //#define DEBUG 1
  35. #define HTTP_TIMESTAMP_FMT_PARSE "%a, %d %b %Y %H:%M:%S %Z"
  36. #define HTTP_TIMESTAMP_FMT_PRINT "%a, %d %b %Y %H:%M:%S GMT"
  37. extern char *proxy_server;
  38. extern long proxy_port;
  39. extern long proxy_type;
  40. extern long timeout;
  41. extern char *user_agent;
  42. extern BBS2chProxyHttpHeaders api_dat_headers;
  43. extern char *appKey;
  44. extern char *hmacKey;
  45. extern int allow_chunked;
  46. extern int curl_features;
  47. extern unsigned int curl_version_number;
  48. extern bool accept_https;
  49. extern int force_5chnet;
  50. extern int force_5chnet_https;
  51. extern int force_ipv4;
  52. extern char *bbsmenu_url;
  53. extern char *api_server;
  54. extern BBS2chProxyHttpHeaders bbscgi_headers;
  55. extern int gikofix;
  56. extern CURLSH *curl_share;
  57. extern unsigned int api_mode;
  58. extern int api_override;
  59. extern int direct_dat;
  60. extern int fool_janestyle;
  61. extern int talk_to_5ch;
  62. extern int subject_to_lastmodify;
  63. extern std::set<std::string> subject_to_lastmodify_hosts;
  64. #ifdef USE_MITM
  65. extern unsigned int mitm_mode;
  66. #endif
  67. extern void log_printf(int level, const char *format ...);
  68. #include "utils.h"
  69. BBS2chProxyKeyManager BBS2chProxyConnection::keyManager;
  70. BBS2chProxyAuth BBS2chProxyConnection::auth;
  71. BBS2chProxyBoardManager BBS2chProxyConnection::boardManager;
  72. static regex_t regex;
  73. static regex_t regex_kako;
  74. static regex_t regex_offlaw;
  75. static regex_t regex_api;
  76. static regex_t regex_api_auth;
  77. static regex_t regex_talk;
  78. static regex_t regex_talk_api;
  79. static regex_t regex_talk_bbscgi;
  80. static bool isPinkPrefix(const std::string &prefix)
  81. {
  82. if (prefix == "aoi") return true;
  83. else if (prefix == "babiru") return true;
  84. else if (prefix == "idol") return true;
  85. else if (prefix == "kilauea") return true;
  86. else if (prefix == "mercury") return true;
  87. else if (prefix == "nasu") return true;
  88. else if (prefix == "okazu") return true;
  89. else if (prefix == "peach") return true;
  90. else if (prefix == "pele") return true;
  91. else if (prefix == "phoebe") return true;
  92. else if (prefix == "pie") return true;
  93. else if (prefix == "pink") return true;
  94. else if (prefix == "qiufen") return true;
  95. else if (prefix == "sakura01") return true;
  96. else if (prefix == "sakura02") return true;
  97. else if (prefix == "set") return true;
  98. else if (prefix == "venus") return true;
  99. else if (prefix == "vip") return true;
  100. else if (prefix == "wow") return true;
  101. else if (prefix == "yomi") return true;
  102. return false;
  103. }
  104. void BBS2chProxyConnection::run(void * (*func)(void *))
  105. {
  106. pthread_t thread;
  107. pthread_attr_t thread_attr;
  108. pthread_attr_init(&thread_attr);
  109. pthread_attr_setdetachstate(&thread_attr , PTHREAD_CREATE_DETACHED);
  110. if(0 != pthread_create(&thread , &thread_attr , func , this))
  111. perror("pthread_create");
  112. pthread_attr_destroy(&thread_attr);
  113. }
  114. struct TunnelSockets {
  115. int sock_c;
  116. int sock_s;
  117. std::string addr;
  118. int port;
  119. };
  120. static void *tunnelMain(void *param)
  121. {
  122. TunnelSockets *sockets = (TunnelSockets *)param;
  123. char *buf = new char[16384];
  124. #ifdef _WIN32
  125. fd_set fds;
  126. int nfds = sockets->sock_c > sockets->sock_s ? sockets->sock_c + 1 : sockets->sock_s + 1;
  127. #else
  128. struct pollfd fds[2];
  129. memset(fds, 0, sizeof(fds));
  130. fds[0].fd = sockets->sock_c;
  131. fds[0].events = POLLIN;
  132. fds[1].fd = sockets->sock_s;
  133. fds[1].events = POLLIN;
  134. #endif
  135. while (1) {
  136. #ifdef _WIN32
  137. FD_ZERO(&fds);
  138. FD_SET(sockets->sock_c, &fds);
  139. FD_SET(sockets->sock_s, &fds);
  140. if (select(nfds, &fds, NULL, NULL, NULL) < 0) break;
  141. if (FD_ISSET(sockets->sock_c, &fds)) {
  142. int ret = recv(sockets->sock_c, buf, 16384, 0);
  143. if (ret > 0) send(sockets->sock_s, buf, ret, 0);
  144. else if (ret <= 0) break;
  145. }
  146. if (FD_ISSET(sockets->sock_s, &fds)) {
  147. int ret = recv(sockets->sock_s, buf, 16384, 0);
  148. if (ret > 0) send(sockets->sock_c, buf, ret, 0);
  149. else if (ret <= 0) break;
  150. }
  151. #else
  152. if (poll(fds, 2, -1) < 0) break;
  153. if (fds[0].revents & POLLIN) {
  154. int ret = recv(sockets->sock_c, buf, 16384, 0);
  155. if (ret > 0) send(sockets->sock_s, buf, ret, 0);
  156. else if (ret <= 0) break;
  157. }
  158. else if (fds[0].revents != 0) break;
  159. if (fds[1].revents & POLLIN) {
  160. int ret = recv(sockets->sock_s, buf, 16384, 0);
  161. if (ret > 0) send(sockets->sock_c, buf, ret, 0);
  162. else if (ret <= 0) break;
  163. }
  164. else if (fds[1].revents != 0) break;
  165. #endif
  166. }
  167. CLOSESOCKET(sockets->sock_c);
  168. CLOSESOCKET(sockets->sock_s);
  169. log_printf(1, "Finished tunneling to %s:%d\n", sockets->addr.c_str(), sockets->port);
  170. delete sockets;
  171. delete[] buf;
  172. return NULL;
  173. }
  174. int BBS2chProxyConnection::tunnel(const char *addr, int port)
  175. {
  176. struct sockaddr_in server;
  177. memset(&server, 0, sizeof(server));
  178. server.sin_family = AF_INET;
  179. server.sin_addr.s_addr = inet_addr(addr);
  180. server.sin_port = htons(port);
  181. if(server.sin_addr.s_addr == 0xffffffff) {
  182. struct hostent *host;
  183. host = gethostbyname(addr);
  184. if (host == NULL) {
  185. log_printf(0, "Failed to lookup hostname %s\n", addr);
  186. socketToClient->sendResponse(400, "Bad Request");
  187. return 400;
  188. }
  189. server.sin_addr.s_addr = *(unsigned int *)host->h_addr_list[0];
  190. }
  191. log_printf(1,"Tunneling connection to %s:%d\n",addr,port);
  192. int sock_s = socket(AF_INET, SOCK_STREAM, 0);
  193. if(-1 == ::connect(sock_s, (struct sockaddr *)&server, sizeof(server))) {
  194. perror("connect");
  195. socketToClient->sendResponse(400, "Bad Request");
  196. return 400;
  197. }
  198. send(sock_c, "HTTP/1.1 200 Connection established\r\n\r\n", 39, 0);
  199. TunnelSockets *sockets = new TunnelSockets();
  200. sockets->sock_c = sock_c;
  201. sockets->sock_s = sock_s;
  202. sockets->addr = addr;
  203. sockets->port = port;
  204. pthread_t thread;
  205. if(0 != pthread_create(&thread, NULL, tunnelMain, sockets))
  206. perror("pthread_create");
  207. pthread_detach(thread);
  208. return 0;
  209. }
  210. void BBS2chProxyConnection::connect(void)
  211. {
  212. char method[32], url[1024], protocol[32];
  213. int i;
  214. char *buf, *ptr;
  215. unsigned int datProxyMode = 0; // 0: no dat, 1: read.cgi or API, 2: force API, 3: kakolog
  216. regmatch_t match[8];
  217. long statusCode = 0;
  218. BBS2chProxyURL baseURL;
  219. BBS2chProxyHttpHeaders requestHeaders;
  220. BBS2chThreadIdentifier threadIdentifier;
  221. bool talkTo5chBbsCgi = false;
  222. socketToClient = new BBS2chProxyRawSocket(sock_c);
  223. buf = (char *)malloc(16384);
  224. if(!buf) goto end;
  225. beginHandleRequest:
  226. ptr = buf;
  227. if(!socketToClient->readLine(buf, 1024)) {
  228. socketToClient->sendResponse(400, "Bad Request");
  229. statusCode = 400;
  230. goto end;
  231. }
  232. i=0;
  233. while(*ptr != ' ' && *ptr != 0 && i < 32) method[i++] = *ptr++;
  234. if(*ptr == 0 || i == 32) {
  235. socketToClient->sendResponse(400, "Bad Request");
  236. statusCode = 400;
  237. goto end;
  238. }
  239. method[i] = 0;
  240. ptr++;
  241. i=0;
  242. while(*ptr != ' ' && *ptr != 0 && i < 1024) url[i++] = *ptr++;
  243. if(*ptr == 0 || i == 1024) {
  244. socketToClient->sendResponse(400, "Bad Request");
  245. statusCode = 400;
  246. goto end;
  247. }
  248. url[i] = 0;
  249. ptr++;
  250. i=0;
  251. while(*ptr != '\r' && *ptr != '\n' && *ptr != 0 && i < 32) protocol[i++] = *ptr++;
  252. if(*ptr == 0 || i == 32) {
  253. socketToClient->sendResponse(400, "Bad Request");
  254. statusCode = 400;
  255. goto end;
  256. }
  257. protocol[i] = 0;
  258. if(!strncasecmp(protocol,"HTTP/1.0",8)) {
  259. isClientHttp1_0 = true;
  260. }
  261. else isClientHttp1_0 = false;
  262. log_printf(1, "Received %s %s %s\n",method,url,protocol);
  263. if(strcasecmp(method,"GET") && strcasecmp(method,"POST") && strcasecmp(method,"HEAD") && strcasecmp(method,"CONNECT") && strcasecmp(method,"PUT") && strcasecmp(method, "OPTIONS")) {
  264. socketToClient->sendResponse(400, "Bad Request");
  265. statusCode = 400;
  266. goto end;
  267. }
  268. if(!url[0]) {
  269. socketToClient->sendResponse(400, "Bad Request");
  270. statusCode = 400;
  271. goto end;
  272. }
  273. if(strncasecmp(protocol,"HTTP",4)) {
  274. socketToClient->sendResponse(400, "Bad Request");
  275. statusCode = 400;
  276. goto end;
  277. }
  278. if(!strcasecmp(method,"CONNECT")) {
  279. if(!accept_https || baseURL.isValid()) {
  280. socketToClient->sendResponse(400, "Bad Request");
  281. statusCode = 400;
  282. goto end;
  283. }
  284. while(socketToClient->readLine(buf, 16384)) {
  285. if(!strcmp("\r\n",buf)) break;
  286. }
  287. int port = 443;
  288. char *ptr = strchr(url, ':');
  289. if(ptr) {
  290. *ptr = 0;
  291. port = atoi(ptr+1);
  292. }
  293. #ifdef USE_MITM
  294. bool useMITM = false;
  295. if (mitm_mode) {
  296. baseURL = BBS2chProxyURL("https", url);
  297. if (mitm_mode == 2) useMITM = true;
  298. else if (mitm_mode == 1 && (baseURL.isFamilyOf5chNet() || (talk_to_5ch && baseURL.isKindOfHost("talk-platform.com")))) useMITM = true;
  299. }
  300. if (useMITM) {
  301. socketToClient->writeString("HTTP/1.1 200 Connection established\r\n\r\n");
  302. if (port == 80) {
  303. baseURL.setScheme("http");
  304. goto beginHandleRequest;
  305. }
  306. else {
  307. try {
  308. BBS2chProxySecureSocket *secureSocket = new BBS2chProxySecureSocket(sock_c, url);
  309. delete socketToClient;
  310. socketToClient = secureSocket;
  311. if (port != 443) baseURL.setPort(port);
  312. isHttps = true;
  313. goto beginHandleRequest;
  314. } catch (const std::runtime_error& e) {
  315. log_printf(0, "%s\n", e.what());
  316. socketToClient->sendResponse(400, "Bad Request");
  317. statusCode = 400;
  318. goto end;
  319. }
  320. }
  321. }
  322. else
  323. #endif
  324. {
  325. statusCode = tunnel(url, port);
  326. /* if a return value is non-zero, tunnel function failed to establish a tunnelling connection */
  327. if (statusCode == 0) {
  328. delete socketToClient;
  329. socketToClient = NULL;
  330. }
  331. goto end;
  332. }
  333. }
  334. #if USE_MITM
  335. if (baseURL.isValid()) {
  336. requestURL = BBS2chProxyURL(baseURL, url);
  337. log_printf(1, "Running as MITM proxy for %s\n", requestURL.absoluteString().c_str());
  338. } else
  339. #endif
  340. if (url[0] == '/') {
  341. requestURL = BBS2chProxyURL("http", "localhost", serverPort, url);
  342. }
  343. else {
  344. requestURL = BBS2chProxyURL(url);
  345. if (requestURL.getPort() == serverPort) requestURL.replaceHost("127.0.0.1", "localhost");
  346. }
  347. if (!requestURL.isHttp()) {
  348. socketToClient->sendResponse(400, "Bad Request");
  349. statusCode = 400;
  350. goto end;
  351. }
  352. if (force_5chnet) {
  353. if (requestURL.getHost() != "menu.2ch.net" && requestURL.replaceHost("2ch.net", "5ch.net")) {
  354. force5ch = true;
  355. log_printf(1, "Detected *.2ch.net URL, changed target URL to %s\n", requestURL.absoluteString().c_str());
  356. }
  357. }
  358. /* parse request headers */
  359. while (socketToClient->readLine(buf, 16384)) {
  360. if (!strcmp("\r\n",buf)) break;
  361. requestHeaders.add(buf);
  362. log_printf(5, " %s", buf);
  363. }
  364. if (requestHeaders.hasNameAndValue("Transfer-Encoding", "chunked")) {
  365. isClientChunked = true;
  366. }
  367. else if (requestHeaders.has("Content-Length")) {
  368. content_length = atoi(requestHeaders.get("Content-Length").c_str());
  369. }
  370. if (requestHeaders.has("Expect")) {
  371. if (!strcasecmp(requestHeaders.get("Expect").c_str(), "100-continue") && !isClientHttp1_0) {
  372. log_printf(1, "Received Expect: 100-continue header, sending 100 Continue response to the client\n");
  373. socketToClient->writeString("HTTP/1.1 100 Continue\r\n\r\n");
  374. }
  375. }
  376. if (regexec(&regex, requestURL.absoluteString().c_str(), 6, match, 0) != REG_NOMATCH) {
  377. const std::string &url = requestURL.absoluteString();
  378. threadIdentifier.hostPrefix = url.substr(match[1].rm_so, match[1].rm_eo - match[1].rm_so);
  379. threadIdentifier.host = requestURL.getHost();
  380. threadIdentifier.board = url.substr(match[4].rm_so, match[4].rm_eo - match[4].rm_so);
  381. threadIdentifier.key = url.substr(match[5].rm_so, match[5].rm_eo - match[5].rm_so);
  382. if (requestURL.isKindOfHost("talk-platform.com")) {
  383. if (!appKey || !(api_mode & 8)) datProxyMode = 3;
  384. else datProxyMode = 2;
  385. }
  386. else if (direct_dat) {
  387. long datStatus;
  388. bool foundAsKakolog;
  389. BBS2chProxyURL newURL = getRawDatURLAndStatus(threadIdentifier, requestHeaders, false, &datStatus, &foundAsKakolog);
  390. if (datStatus == 200) {
  391. directDatDownloading = 1;
  392. if (foundAsKakolog) {
  393. requestURL = newURL;
  394. }
  395. } else {
  396. if (datStatus == 404) {
  397. if (!requestHeaders.has("Range") && !requestURL.hostStartsWith("headline.")) datProxyMode = 1;
  398. else {
  399. statusCode = 302;
  400. socketToClient->sendBasicHeaders(302, "Found");
  401. if (0 >= socketToClient->writeString("Location: http://www2.2ch.net/live.html\r\n")) goto end;
  402. if (0 >= socketToClient->writeString("\r\n")) goto end;
  403. goto end;
  404. }
  405. } else {
  406. statusCode = 503;
  407. socketToClient->sendResponse(503, "Service Unavailable");
  408. goto end;
  409. }
  410. }
  411. }
  412. else if ((appKey && (api_mode & 1)) || !requestURL.hostStartsWith("headline.")) datProxyMode = 1;
  413. }
  414. else if (regexec(&regex_kako, requestURL.absoluteString().c_str(), 8, match, 0) != REG_NOMATCH) {
  415. const std::string &url = requestURL.absoluteString();
  416. threadIdentifier.hostPrefix = url.substr(match[1].rm_so, match[1].rm_eo - match[1].rm_so);
  417. threadIdentifier.host = requestURL.getHost();
  418. threadIdentifier.board = url.substr(match[4].rm_so, match[4].rm_eo - match[4].rm_so);
  419. threadIdentifier.key = url.substr(match[7].rm_so, match[7].rm_eo - match[7].rm_so);
  420. if (requestURL.isKindOfHost("talk-platform.com")) {
  421. if (!appKey || !(api_mode & 8)) datProxyMode = 3;
  422. else datProxyMode = 2;
  423. }
  424. else if (direct_dat) {
  425. long datStatus;
  426. bool foundAsKakolog;
  427. BBS2chProxyURL newURL = getRawDatURLAndStatus(threadIdentifier, requestHeaders, true, &datStatus, &foundAsKakolog);
  428. if (datStatus == 200) {
  429. directDatDownloading = 1;
  430. requestURL = newURL;
  431. } else {
  432. if (!requestHeaders.has("Range")) datProxyMode = 3;
  433. else {
  434. statusCode = 503;
  435. socketToClient->sendResponse(503, "Service Unavailable");
  436. goto end;
  437. }
  438. }
  439. }
  440. else datProxyMode = 3;
  441. }
  442. else if (regexec(&regex_offlaw, requestURL.absoluteString().c_str(), 5, match, 0) != REG_NOMATCH) {
  443. const char *tmp = requestURL.absoluteString().c_str();
  444. const char *thread = strstr(tmp, "key=");
  445. if (thread) {
  446. match[6].rm_so = thread+4-tmp;
  447. match[6].rm_eo = thread+4-tmp;
  448. const char *ptr = thread+4;
  449. while (*ptr != '&' && *ptr != 0) {
  450. ptr++;
  451. match[6].rm_eo++;
  452. }
  453. if (match[6].rm_so != match[6].rm_eo) {
  454. const std::string &url = requestURL.absoluteString();
  455. threadIdentifier.hostPrefix = url.substr(match[1].rm_so, match[1].rm_eo - match[1].rm_so);
  456. threadIdentifier.host = requestURL.getHost();
  457. threadIdentifier.board = url.substr(match[4].rm_so, match[4].rm_eo - match[4].rm_so);
  458. threadIdentifier.key = url.substr(match[6].rm_so, match[6].rm_eo - match[6].rm_so);
  459. if (direct_dat) {
  460. long datStatus;
  461. bool foundAsKakolog;
  462. BBS2chProxyURL newURL = getRawDatURLAndStatus(threadIdentifier, requestHeaders, true, &datStatus, &foundAsKakolog);
  463. if (datStatus == 200) {
  464. directDatDownloading = 1;
  465. requestURL = newURL;
  466. } else {
  467. if (!requestHeaders.has("Range")) datProxyMode = 3;
  468. else {
  469. statusCode = 503;
  470. socketToClient->sendResponse(503, "Service Unavailable");
  471. goto end;
  472. }
  473. }
  474. }
  475. else datProxyMode = 3;
  476. }
  477. }
  478. }
  479. else if (api_override || talk_to_5ch) {
  480. const std::string &url = requestURL.absoluteString();
  481. if (api_override && regexec(&regex_api, url.c_str(), 5, match, 0) != REG_NOMATCH) {
  482. threadIdentifier.hostPrefix = url.substr(match[2].rm_so, match[2].rm_eo - match[2].rm_so);
  483. threadIdentifier.host = threadIdentifier.hostPrefix;
  484. threadIdentifier.host += isPinkPrefix(threadIdentifier.hostPrefix) ? ".bbspink.com" : ".5ch.net";
  485. threadIdentifier.board = url.substr(match[3].rm_so, match[3].rm_eo - match[3].rm_so);
  486. threadIdentifier.key = url.substr(match[4].rm_so, match[4].rm_eo - match[4].rm_so);
  487. if (direct_dat) {
  488. long datStatus;
  489. bool foundAsKakolog;
  490. BBS2chProxyURL newURL = getRawDatURLAndStatus(threadIdentifier, requestHeaders, false, &datStatus, &foundAsKakolog);
  491. if (datStatus == 200) {
  492. directDatDownloading = 2;
  493. strcpy(method, "GET");
  494. requestURL = newURL;
  495. requestHeaders.set("Host", newURL.getHost());
  496. requestHeaders.remove("Content-Length");
  497. requestHeaders.remove("Content-Type");
  498. } else {
  499. if (datStatus == 404) {
  500. if (!requestHeaders.has("Range") && !requestURL.hostStartsWith("headline.")) datProxyMode = 3;
  501. else {
  502. statusCode = 200;
  503. socketToClient->sendBasicHeaders(200, "OK");
  504. if (0 >= socketToClient->writeString("Thread-Status: 8\r\n")) goto end;
  505. if (0 >= socketToClient->writeString("User-Status: 3\r\n\r\n")) goto end;
  506. goto end;
  507. }
  508. } else {
  509. statusCode = 503;
  510. socketToClient->sendResponse(503, "Service Unavailable");
  511. goto end;
  512. }
  513. }
  514. } else if (appKey && !(api_mode & 1)) {
  515. datProxyMode = 2;
  516. } else {
  517. datProxyMode = 3;
  518. }
  519. if (datProxyMode == 3) {
  520. requestHeaders.set("X-Proxy2ch-API-Bypass", "1");
  521. }
  522. }
  523. else if (api_override && regexec(&regex_api_auth, url.c_str(), 2, match, 0) != REG_NOMATCH) {
  524. /* return dummy response immediately */
  525. log_printf(1, "Returning dummy response because API overriding is enabled\n");
  526. statusCode = 200;
  527. socketToClient->sendBasicHeaders(200, "OK");
  528. if (0 >= socketToClient->writeString("Content-Type: text/plain\r\n")) goto end;
  529. if (0 >= socketToClient->writeString("Content-Length: 203\r\n\r\n")) goto end;
  530. if (0 >= socketToClient->writeString("SESSION-ID=Monazilla/1.00:000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000")) goto end;
  531. goto end;
  532. }
  533. else if (talk_to_5ch && regexec(&regex_talk, url.c_str(), 3, match, 0) != REG_NOMATCH) {
  534. std::string board = url.substr(match[2].rm_so, match[2].rm_eo - match[2].rm_so);
  535. std::string path = url.substr(match[1].rm_so, match[1].rm_eo - match[1].rm_so);
  536. std::string host = boardManager.getServerForBoard(board);
  537. if (!host.empty()) {
  538. requestURL = BBS2chProxyURL(force_5chnet_https ? "https" : "http", host.c_str(), 0, path.c_str());
  539. requestHeaders.set("Host", requestURL.getHost());
  540. log_printf(1, "Enabled Talk to 5ch proxy, will connect to %s\n", requestURL.absoluteString().c_str());
  541. }
  542. }
  543. else if (talk_to_5ch && regexec(&regex_talk_api, url.c_str(), 3, match, 0) != REG_NOMATCH) {
  544. threadIdentifier.board = url.substr(match[1].rm_so, match[1].rm_eo - match[1].rm_so);
  545. threadIdentifier.key = url.substr(match[2].rm_so, match[2].rm_eo - match[2].rm_so);
  546. threadIdentifier.host = boardManager.getServerForBoard(threadIdentifier.board);
  547. threadIdentifier.hostPrefix = threadIdentifier.host.substr(0, threadIdentifier.host.find("."));
  548. if (!threadIdentifier.host.empty()) {
  549. log_printf(1, "Enabled Talk to 5ch proxy, will connect to %s\n", threadIdentifier.host.c_str());
  550. if (direct_dat) {
  551. long datStatus;
  552. bool foundAsKakolog;
  553. BBS2chProxyURL newURL = getRawDatURLAndStatus(threadIdentifier, requestHeaders, false, &datStatus, &foundAsKakolog);
  554. if (datStatus == 200) {
  555. directDatDownloading = 2;
  556. strcpy(method, "GET");
  557. requestURL = newURL;
  558. requestHeaders.set("Host", newURL.getHost());
  559. requestHeaders.remove("Content-Length");
  560. requestHeaders.remove("Content-Type");
  561. } else {
  562. if (datStatus == 404) {
  563. if (!requestHeaders.has("Range") && threadIdentifier.hostPrefix != "headline") {
  564. datProxyMode = 3;
  565. requestHeaders.set("X-Proxy2ch-API-Bypass", "1");
  566. }
  567. else {
  568. statusCode = 200;
  569. socketToClient->sendBasicHeaders(200, "OK");
  570. if (0 >= socketToClient->writeString("Thread-Status: 8\r\n")) goto end;
  571. if (0 >= socketToClient->writeString("User-Status: 3\r\n\r\n")) goto end;
  572. goto end;
  573. }
  574. } else {
  575. statusCode = 503;
  576. socketToClient->sendResponse(503, "Service Unavailable");
  577. goto end;
  578. }
  579. }
  580. }
  581. else if ((appKey && (api_mode & 1)) || threadIdentifier.hostPrefix != "headline") datProxyMode = 1;
  582. }
  583. }
  584. else if (talk_to_5ch && regexec(&regex_talk_bbscgi, url.c_str(), 1, match, 0) != REG_NOMATCH) {
  585. talkTo5chBbsCgi = true;
  586. }
  587. }
  588. if (datProxyMode) {
  589. if (!appKey || (datProxyMode == 1 && !(api_mode & 1)) || datProxyMode == 3) {
  590. if (threadIdentifier.host == "classic.talk-platform.com") {
  591. isHttps = true;
  592. log_printf(1, "Retrieving thread via json...\n");
  593. BBS2chProxyHTML2DatTalk html2dat(threadCache, threadIdentifier, curl);
  594. html2dat.setRequestHeaders(requestHeaders);
  595. statusCode = datProxy(html2dat, method, requestHeaders);
  596. }
  597. else {
  598. log_printf(1, "Retrieving thread via read.cgi...\n");
  599. BBS2chProxyHTML2Dat5ch html2dat(threadCache, threadIdentifier, force_5chnet_https || isHttps, curl);
  600. html2dat.setRequestHeaders(requestHeaders);
  601. statusCode = datProxy(html2dat, method, requestHeaders);
  602. }
  603. }
  604. else {
  605. log_printf(1, "Retrieving thread via API...\n");
  606. std::string targetURL = "https://";
  607. targetURL += api_server;
  608. targetURL += "/v1/";
  609. targetURL += threadIdentifier.hostPrefix;
  610. targetURL += '/';
  611. targetURL += threadIdentifier.board;
  612. targetURL += '/';
  613. targetURL += threadIdentifier.key;
  614. isHttps = true;
  615. statusCode = datProxyAPI(targetURL, method, requestHeaders);
  616. }
  617. }
  618. else {
  619. if (force_5chnet_https && !isHttps && requestURL.isFamilyOf5chNet()) {
  620. requestURL.setScheme("https");
  621. isHttps = true;
  622. log_printf(1, "The host %s is 5ch.net family, connecting with HTTPS\n", requestURL.getHost().c_str());
  623. }
  624. else if (!isHttps && requestURL.isKindOfHost("talk-platform.com")) {
  625. requestURL.setScheme("https");
  626. isHttps = true;
  627. log_printf(1, "The host talk-platform.com only accepts HTTPS, connecting with HTTPS\n");
  628. }
  629. if (bbsmenu_url && requestURL.equalsTo(BBS2chProxyURL(bbsmenu_url), true)) {
  630. log_printf(1, "Running as a BBS menu proxy...\n");
  631. statusCode = bbsmenuProxy(requestURL.absoluteString(), method, requestHeaders);
  632. }
  633. else if (fool_janestyle && requestURL.equalsTo(BBS2chProxyURL("http", "janesoft.net", 0, "/janestyle/setting.php"), true)) {
  634. log_printf(1, "Fooling JaneStyle as if API is still alive...\n");
  635. socketToClient->sendBasicHeaders(200, "OK");
  636. socketToClient->writeString("\r\n0");
  637. statusCode = 200;
  638. }
  639. else if (talk_to_5ch && requestURL.equalsTo(BBS2chProxyURL("https", "classic.talk-platform.com", 0, "/bbsmenu.json"), true)) {
  640. log_printf(1, "Returning bbsmenu.json including fake 5ch.net boards...\n");
  641. socketToClient->sendBasicHeaders(200, "OK");
  642. socketToClient->writeString("Content-Type: application/json\r\n\r\n");
  643. socketToClient->writeString(boardManager.getBoardJSONForTalkAndFake5ch());
  644. statusCode = 200;
  645. }
  646. else if (requestURL.getHost() == "localhost" && requestURL.getPort() == serverPort && requestURL.isHttp()) {
  647. if (requestURL.getPath() == "/5ch/bbsmenu.html") {
  648. std::map<std::string, std::string> query = requestURL.getQuery();
  649. bool useHttps = query["https"] == "true";
  650. bool use2ch = query["2ch"] == "true";
  651. bool hasTalk = query["talk"] == "true";
  652. log_printf(1, "Returning bbsmenu.html...\n");
  653. socketToClient->sendBasicHeaders(200, "OK");
  654. socketToClient->writeString("Content-Type: text/html; charset=Shift_JIS\r\n\r\n");
  655. socketToClient->writeString(boardManager.getBoardHTML(!useHttps, use2ch, hasTalk));
  656. statusCode = 200;
  657. }
  658. else if (requestURL.getPath() == "/5ch/bbsmenu.json") {
  659. std::map<std::string, std::string> query = requestURL.getQuery();
  660. bool useHttps = query["https"] == "true";
  661. bool use2ch = query["2ch"] == "true";
  662. bool hasTalk = query["talk"] == "true";
  663. log_printf(1, "Returning bbsmenu.json...\n");
  664. socketToClient->sendBasicHeaders(200, "OK");
  665. socketToClient->writeString("Content-Type: application/json\r\n\r\n");
  666. socketToClient->writeString(boardManager.getBoardJSON(!useHttps, use2ch, hasTalk));
  667. statusCode = 200;
  668. }
  669. else {
  670. socketToClient->sendResponse(404, "Not Found");
  671. statusCode = 404;
  672. }
  673. }
  674. else if (((subject_to_lastmodify == 1 && requestURL.isFamilyOf5chNet()) ||
  675. (subject_to_lastmodify == 2 && subject_to_lastmodify_hosts.find(requestURL.getHost()) != subject_to_lastmodify_hosts.end())) &&
  676. requestURL.pathEndsWith("/subject.txt") && requestURL.numberOfPathComponents() == 2) {
  677. log_printf(1, "Running as subject.txt to lastmodify.txt proxy...\n");
  678. statusCode = subjectTxtProxy(requestURL, method, requestHeaders);
  679. }
  680. else {
  681. bool isPostRequest = !strcasecmp(method, "POST");
  682. bool isPutRequest = !strcasecmp(method, "PUT");
  683. char *postdata = NULL;
  684. if (isPostRequest && (requestURL.isFamilyOf5chNet() || requestURL.isKindOfHost("classic.talk-platform.com")) && requestURL.pathStartsWith("/test/bbs.cgi")) bbscgi = true;
  685. else if (talkTo5chBbsCgi) bbscgi = true;
  686. if (bbscgi) log_printf(1, "Looks like a request to bbs.cgi, will be modified before sending...\n");
  687. else if (directDatDownloading) log_printf(1, "Downloading .dat directly from %s...\n", requestURL.absoluteString().c_str());
  688. else log_printf(1, "Not a notable request, will be forwarded to server...\n");
  689. if (force_5chnet) {
  690. if (requestHeaders.has("Host")) {
  691. std::string host = requestHeaders.get("Host");
  692. size_t pos = host.find("2ch.net");
  693. if (pos != std::string::npos && pos+7 == host.length()) {
  694. if (pos == 0 || host[pos-1] == '.') {
  695. host.replace(pos, 1, "5");
  696. requestHeaders.set("Host", host);
  697. }
  698. }
  699. }
  700. if (bbscgi && requestHeaders.has("Referer")) {
  701. std::string referrer = requestHeaders.get("Referer");
  702. size_t pos = referrer.find("2ch.net");
  703. if (pos != std::string::npos) {
  704. if (pos == 0 || referrer[pos-1] == '.') {
  705. referrer.replace(pos, 1, "5");
  706. requestHeaders.set("Referer", referrer);
  707. }
  708. }
  709. }
  710. }
  711. requestHeaders.remove("Connection");
  712. if (user_agent) requestHeaders.remove("User-Agent");
  713. if (bbscgi && (content_length > 0 || isClientChunked)) {
  714. bool isNotFormURLEncoded = false;
  715. if (requestHeaders.has("Content-Type") && requestHeaders.get("Content-Type").find("application/x-www-form-urlencoded") == std::string::npos) {
  716. isNotFormURLEncoded = true;
  717. }
  718. if (!isNotFormURLEncoded) {
  719. requestHeaders.remove("Content-Length");
  720. if (!bbscgi_headers.empty()) {
  721. for (BBS2chProxyHttpHeaders::iterator it = bbscgi_headers.begin(); it != bbscgi_headers.end(); ++it) {
  722. if (requestHeaders.has(it->first->getName())) {
  723. log_printf(1, "Ignoring header \"%s\" because custom header will be appended\n", it->first->getName().c_str());
  724. requestHeaders.remove(it->first->getName());
  725. }
  726. }
  727. }
  728. if (isClientChunked) {
  729. content_length = readChunkedBodyIntoBuffer(&postdata, socketToClient);
  730. requestHeaders.remove("Transfer-Encoding");
  731. }
  732. else {
  733. postdata = (char *)calloc(content_length+1, 1);
  734. content_length = socketToClient->read(postdata, content_length);
  735. }
  736. if (gikofix) {
  737. char *ptr = postdata+content_length-1;
  738. while (ptr >= postdata && (*ptr == '\r' || *ptr == '\n')) {
  739. *ptr-- = 0;
  740. }
  741. }
  742. BBS2chProxyFormData requestBody(postdata, strlen(postdata));
  743. statusCode = bbsCgiProxy(requestURL, requestHeaders, requestBody, talkTo5chBbsCgi);
  744. if (statusCode >= 0) {
  745. free(postdata);
  746. goto end;
  747. }
  748. }
  749. }
  750. curl_slist *headersForCurl = NULL;
  751. headersForCurl = requestHeaders.appendToCurlSlist(headersForCurl);
  752. if (!requestHeaders.has("Expect")) {
  753. headersForCurl = curl_slist_append(headersForCurl, "Expect:");
  754. }
  755. if(curl) {
  756. CURLcode res;
  757. if(curl_share) curl_easy_setopt(curl, CURLOPT_SHARE, curl_share);
  758. curl_easy_setopt(curl, CURLOPT_URL, requestURL.absoluteString().c_str());
  759. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
  760. curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  761. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, header_callback_proxy);
  762. curl_easy_setopt(curl, CURLOPT_HEADERDATA, this);
  763. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback_proxy);
  764. curl_easy_setopt(curl, CURLOPT_WRITEDATA, this);
  765. if (postdata) curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postdata);
  766. else {
  767. if(content_length) {
  768. /* set Content-Length explicitly via API to work properly with curl >= 7.66.0 */
  769. if(isPostRequest)
  770. curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, content_length);
  771. else if(isPutRequest)
  772. curl_easy_setopt(curl, CURLOPT_INFILESIZE, content_length);
  773. }
  774. curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_callback_proxy);
  775. curl_easy_setopt(curl, CURLOPT_READDATA, this);
  776. }
  777. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
  778. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
  779. //curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
  780. if(force_ipv4) curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
  781. curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
  782. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headersForCurl);
  783. if(user_agent) {
  784. curl_easy_setopt(curl, CURLOPT_USERAGENT, user_agent);
  785. }
  786. if(isPostRequest) {
  787. curl_easy_setopt(curl, CURLOPT_POST, 1L);
  788. }
  789. else if(isPutRequest) {
  790. curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
  791. }
  792. else if(!strcasecmp(method, "HEAD")) {
  793. curl_easy_setopt(curl, CURLOPT_NOBODY, 1L);
  794. }
  795. else if(!strcasecmp(method, "OPTIONS")) {
  796. curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "OPTIONS");
  797. }
  798. if(proxy_server) {
  799. curl_easy_setopt(curl, CURLOPT_PROXY, proxy_server);
  800. curl_easy_setopt(curl, CURLOPT_PROXYPORT, proxy_port);
  801. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, proxy_type);
  802. }
  803. res = curl_easy_perform(curl);
  804. if(res != CURLE_OK) {
  805. log_printf(0, "curl error: %s (%s)\n", curl_easy_strerror(res), requestURL.absoluteString().c_str());
  806. if(!status) socketToClient->sendResponse(503, "Service Unavailable");
  807. statusCode = 503;
  808. }
  809. else {
  810. if(isResponseChunked) {
  811. socketToClient->writeString("0\r\n\r\n");
  812. }
  813. curl_easy_getinfo(curl,CURLINFO_RESPONSE_CODE, &statusCode);
  814. }
  815. curl_easy_reset(curl);
  816. }
  817. curl_slist_free_all(headersForCurl);
  818. if (postdata) free(postdata);
  819. }
  820. }
  821. end:
  822. if(statusCode) log_printf(1, "Returned status code %d to client\n",statusCode);
  823. if(buf) free(buf);
  824. if(socketToClient) socketToClient->close();
  825. }
  826. int BBS2chProxyConnection::datProxy(IBBS2chProxyHTML2Dat &html2dat, const char *method, BBS2chProxyHttpHeaders &requestHeaders)
  827. {
  828. std::string dat;
  829. long statusCode = 0;
  830. long rangeStart = 0, rangeEnd = 0;
  831. time_t lastModified = 0;
  832. time_t ifModifiedSince = 0;
  833. if(requestHeaders.has("Range")) {
  834. std::string value = requestHeaders.get("Range");
  835. if(value.find("bytes=") == 0 && value.find(",") == std::string::npos) {
  836. char *ptr = (char *)value.c_str() + 6;
  837. if(*ptr == '-') {
  838. rangeStart = atoi(ptr);
  839. }
  840. else {
  841. rangeStart = strtol(ptr, &ptr, 10);
  842. if(*ptr == '-') ptr++;
  843. if(*ptr && *ptr != '\r') {
  844. rangeEnd = strtol(ptr, NULL, 10);
  845. if(rangeEnd && rangeStart > rangeEnd) {
  846. socketToClient->sendResponse(416, "Requested range not satisfiable");
  847. statusCode = 416;
  848. goto last;
  849. }
  850. }
  851. }
  852. //fprintf(stderr, "range=%ld-%ld\n",rangeStart,rangeEnd);
  853. }
  854. else {
  855. socketToClient->sendResponse(416, "Requested range not satisfiable");
  856. statusCode = 416;
  857. goto last;
  858. }
  859. }
  860. if(requestHeaders.has("If-Modified-Since")) {
  861. #if LIBCURL_VERSION_NUM >= 0x070c02 /* curl 7.12.2 or later */
  862. ifModifiedSince = curl_getdate(requestHeaders.get("If-Modified-Since").c_str(), NULL);
  863. #else
  864. struct tm time_ = {0};
  865. strptime(requestHeaders.get("If-Modified-Since").c_str(), HTTP_TIMESTAMP_FMT_PARSE, &time_);
  866. ifModifiedSince = mktime(&time_);
  867. #endif
  868. }
  869. if(rangeStart > 0) {
  870. PBBS2chProxyThreadInfo info = threadCache->get(html2dat.getKey());
  871. log_printf(5,"range request from %ld bytes\n",rangeStart);
  872. if(info) {
  873. int from = info->lastResNum;
  874. int alreadyRead = info->cachedSize;
  875. int lastResLength = info->cachedData.size();
  876. log_printf(5,"hit %s: cached %d bytes, last res size %d\n",html2dat.getKey().c_str(),alreadyRead,lastResLength);
  877. if(rangeStart <= alreadyRead && rangeStart >= alreadyRead - lastResLength) {
  878. std::string updated = html2dat.generateDatFrom(from, &lastModified, true, &statusCode);
  879. if (!updated.empty()) {
  880. if (ifModifiedSince && lastModified && updated.size() == lastResLength) {
  881. if (ifModifiedSince >= lastModified) {
  882. socketToClient->sendResponse(304, "Not Modified");
  883. log_printf(5, "not modified!\n");
  884. statusCode = 304;
  885. goto last;
  886. }
  887. }
  888. if (updated.size() >= lastResLength) {
  889. dat = std::string(alreadyRead - lastResLength, ' ');
  890. dat += updated;
  891. if (!rangeEnd) rangeEnd = dat.size() - 1;
  892. if (rangeStart > rangeEnd) {
  893. socketToClient->sendResponse(416, "Requested range not satisfiable");
  894. statusCode = 416;
  895. goto last;
  896. }
  897. statusCode = 206;
  898. log_printf(5, "cache hit; reconstructed data length:%ld\n", (long)dat.size());
  899. }
  900. else {
  901. log_printf(5, "cache misshit?\n");
  902. socketToClient->sendResponse(416, "Requested range not satisfiable");
  903. statusCode = 416;
  904. goto last;
  905. }
  906. }
  907. if (!dat.empty()) goto resp;
  908. }
  909. else {
  910. log_printf(5,"invalid cache contents\n");
  911. threadCache->remove(html2dat.getKey());
  912. }
  913. }
  914. }
  915. {
  916. dat = html2dat.generateDatFrom(1, &lastModified, false, &statusCode);
  917. if(dat.empty()) {
  918. socketToClient->sendResponse(503, "Service Unavailable");
  919. statusCode = 503;
  920. goto last;
  921. }
  922. if((rangeStart || rangeEnd) && !dat.empty()) {
  923. if(!rangeEnd) rangeEnd = dat.size() - 1;
  924. if(rangeStart < 0) rangeStart = dat.size() + rangeStart;
  925. if (ifModifiedSince && lastModified) {
  926. if (rangeStart == dat.size() || (rangeStart == dat.size() - 1 && rangeEnd == dat.size() - 1)) {
  927. if (ifModifiedSince >= lastModified) {
  928. socketToClient->sendResponse(304, "Not Modified");
  929. log_printf(5,"not modified!\n");
  930. statusCode = 304;
  931. goto last;
  932. }
  933. }
  934. }
  935. if(rangeStart < dat.size() && rangeEnd < dat.size() && rangeStart <= rangeEnd) {
  936. statusCode = 206;
  937. }
  938. else {
  939. socketToClient->sendResponse(416, "Requested range not satisfiable");
  940. statusCode = 416;
  941. goto last;
  942. }
  943. }
  944. }
  945. resp:
  946. if(statusCode == 206) socketToClient->sendBasicHeaders(statusCode, "Partial Content");
  947. else socketToClient->sendBasicHeaders(statusCode, "OK");
  948. if(0 >= socketToClient->writeString("Content-Type: text/plain\r\n")) goto last;
  949. if(0 >= socketToClient->writeString("Accept-Ranges: bytes\r\n")) goto last;
  950. if (requestHeaders.has("X-Proxy2ch-API-Bypass")) {
  951. if (0 >= socketToClient->writeString("Thread-Status: 1\r\n")) goto last;
  952. if (0 >= socketToClient->writeString("User-Status: 3\r\n")) goto last;
  953. }
  954. if(statusCode == 206) {
  955. std::ostringstream ss;
  956. ss << "Content-Range: bytes " << rangeStart << "-" << rangeEnd << "/" << dat.size() << "\r\n";
  957. if (0 >= socketToClient->writeString(ss.str())) goto last;
  958. //fprintf(stderr,"Content-Length: %ld\r\n",rangeEnd - rangeStart + 1);
  959. //fprintf(stderr,"Content-Range: bytes %ld-%ld/%ld\r\n",rangeStart,rangeEnd,(long)dat.size());
  960. dat = dat.substr(rangeStart, rangeEnd - rangeStart + 1);
  961. }
  962. {
  963. std::ostringstream ss;
  964. ss << "Content-Length: " << dat.size() << "\r\n";
  965. if(0 >= socketToClient->writeString(ss.str())) goto last;
  966. }
  967. if(lastModified) {
  968. struct tm time_ = {0};
  969. char date[256];
  970. gmtime_r(&lastModified,&time_);
  971. strftime(date, 256, HTTP_TIMESTAMP_FMT_PRINT, &time_);
  972. std::string header = "Last-Modified: ";
  973. header += date;
  974. header += "\r\n";
  975. if(0 >= socketToClient->writeString(header)) goto last;
  976. //fprintf(stderr,"Last-Modified: %s\r\n",date);
  977. }
  978. if(0 >= socketToClient->writeString("\r\n")) goto last;
  979. if(!dat.empty() && statusCode >= 200 && statusCode < 300 && strcasecmp(method, "HEAD")) {
  980. if(0 >= socketToClient->writeString(dat)) goto last;
  981. }
  982. last:
  983. return statusCode;
  984. }
  985. int BBS2chProxyConnection::datProxyAPI(const std::string &url, const char *method, BBS2chProxyHttpHeaders &requestHeaders)
  986. {
  987. long statusCode = 0;
  988. const std::string &postBody = auth.requestBodyForURL(url.c_str(), curl);
  989. bool directMode = false;
  990. if (postBody.empty()) {
  991. socketToClient->sendResponse(401, "Unauthorized");
  992. return 401;
  993. }
  994. /* just read and strip off post body */
  995. if (!strcasecmp(method, "POST")) {
  996. char *postdata = NULL;
  997. if (isClientChunked) {
  998. readChunkedBodyIntoBuffer(&postdata, socketToClient);
  999. }
  1000. else if (content_length) {
  1001. postdata = (char *)calloc(content_length+1, 1);
  1002. socketToClient->read(postdata, content_length);
  1003. }
  1004. if (postdata && strstr(postdata, "sid=")) directMode = true;
  1005. if (postdata) free(postdata);
  1006. }
  1007. if (curl) {
  1008. CURLcode res;
  1009. struct curl_slist *headersForCurl = NULL;
  1010. BBS2chProxyHttpHeaders receivedHeaders;
  1011. std::vector<char> receivedBody;
  1012. bool explicitAcceptEncoding = false;
  1013. headersForCurl = requestHeaders.appendToCurlSlist(headersForCurl, "Range");
  1014. headersForCurl = requestHeaders.appendToCurlSlist(headersForCurl, "If-Modified-Since");
  1015. if (!api_dat_headers.has("Accept-Encoding")) {
  1016. headersForCurl = requestHeaders.appendToCurlSlist(headersForCurl, "Accept-Encoding");
  1017. }
  1018. else explicitAcceptEncoding = true;
  1019. if (!api_dat_headers.empty()) {
  1020. std::set<std::string> excludes;
  1021. if (explicitAcceptEncoding) {
  1022. excludes.insert("accept-encoding");
  1023. }
  1024. headersForCurl = api_dat_headers.appendToCurlSlist(headersForCurl, excludes);
  1025. }
  1026. if (curl_share) curl_easy_setopt(curl, CURLOPT_SHARE, curl_share);
  1027. curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  1028. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headersForCurl);
  1029. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
  1030. curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  1031. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback_download);
  1032. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &receivedBody);
  1033. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, header_callback_download);
  1034. curl_easy_setopt(curl, CURLOPT_HEADERDATA, &receivedHeaders);
  1035. curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
  1036. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
  1037. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
  1038. if (force_ipv4) curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
  1039. if (proxy_server) {
  1040. curl_easy_setopt(curl, CURLOPT_PROXY, proxy_server);
  1041. curl_easy_setopt(curl, CURLOPT_PROXYPORT, proxy_port);
  1042. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, proxy_type);
  1043. }
  1044. if (!api_dat_headers.has("User-Agent")) {
  1045. curl_easy_setopt(curl, CURLOPT_USERAGENT, "");
  1046. }
  1047. if (explicitAcceptEncoding) {
  1048. curl_easy_setopt(curl, CURLOPT_ENCODING, api_dat_headers.get("Accept-Encoding").c_str());
  1049. }
  1050. curl_easy_setopt(curl, CURLOPT_POST, 1L);
  1051. #if LIBCURL_VERSION_NUM >= 0x071101
  1052. curl_easy_setopt(curl, CURLOPT_COPYPOSTFIELDS, postBody.c_str());
  1053. #else
  1054. curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postBody.c_str());
  1055. #endif
  1056. //return;
  1057. res = curl_easy_perform(curl);
  1058. if (res == CURLE_OK) {
  1059. curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &statusCode);
  1060. int threadStatus = 0;
  1061. if (!directMode && receivedHeaders.has("Thread-Status")) {
  1062. threadStatus = atoi(receivedHeaders.get("Thread-Status").c_str());
  1063. }
  1064. if (threadStatus == 1 || threadStatus == 2 || directMode) {
  1065. if (explicitAcceptEncoding && receivedHeaders.has("Content-Encoding")) {
  1066. std::ostringstream ss;
  1067. ss << receivedBody.size();
  1068. receivedHeaders.set("Content-Length", ss.str());
  1069. receivedHeaders.remove("Content-Encoding");
  1070. }
  1071. if (requestHeaders.has("Range") && statusCode == 200 && !strcmp(api_server, "api.talk-platform.com")) {
  1072. /* api.talk-platform.com does not return 206 for ranged requests. so we try emulating 206 or 304 response. sucks! */
  1073. if (receivedBody.size() == 0) {
  1074. if (0 >= socketToClient->writeString("HTTP/1.1 304 Not Modified\r\n")) goto last;
  1075. receivedHeaders.remove("Content-Length");
  1076. statusCode = 304;
  1077. } else if (requestHeaders.has("If-Modified-Since") && receivedBody.size() <= 1) {
  1078. /* we will never reach here since api.talk-platform.com does not return Last-Modified header. sucks! */
  1079. if (0 >= socketToClient->writeString("HTTP/1.1 304 Not Modified\r\n")) goto last;
  1080. receivedHeaders.remove("Content-Length");
  1081. statusCode = 304;
  1082. } else {
  1083. if (0 >= socketToClient->writeString("HTTP/1.1 206 Partial Content\r\n")) goto last;
  1084. if (!receivedHeaders.has("Content-Length")) {
  1085. std::ostringstream ss;
  1086. ss << receivedBody.size();
  1087. receivedHeaders.set("Content-Length", ss.str());
  1088. }
  1089. size_t pos = requestHeaders.get("Range").find("bytes=");
  1090. if (pos != std::string::npos) {
  1091. pos += 6;
  1092. std::string range = requestHeaders.get("Range").substr(pos);
  1093. const char *rangeData = range.c_str();
  1094. char *ptr;
  1095. unsigned long rangeStart = strtoul(rangeData, &ptr, 10);
  1096. if (*ptr == '-' && *(ptr+1) == 0) {
  1097. unsigned long rangeEnd = rangeStart + receivedBody.size() - 1;
  1098. std::ostringstream ss;
  1099. ss << "bytes " << rangeStart << "-" << rangeEnd << "/" << rangeEnd + 1;
  1100. receivedHeaders.set("Content-Range", ss.str());
  1101. }
  1102. }
  1103. statusCode = 206;
  1104. }
  1105. }
  1106. else {
  1107. if (0 >= socketToClient->writeString(receivedHeaders.getStatusLine() + "\r\n")) goto last;
  1108. }
  1109. for (BBS2chProxyHttpHeaders::iterator it = receivedHeaders.begin(); it != receivedHeaders.end(); ++it) {
  1110. if (0 >= socketToClient->writeString(it->second + "\r\n")) goto last;
  1111. }
  1112. if (0 >= socketToClient->writeString("\r\n")) goto last;
  1113. if (statusCode != 304) {
  1114. if (receivedBody.size() > socketToClient->write(&receivedBody.front(), receivedBody.size())) goto last;
  1115. }
  1116. goto last;
  1117. }
  1118. else if (threadStatus == 8) {
  1119. socketToClient->sendBasicHeaders(302, "Found");
  1120. if (0 >= socketToClient->writeString("Location: http://www2.2ch.net/live.html\r\n")) goto last;
  1121. if (0 >= socketToClient->writeString("\r\n")) goto last;
  1122. statusCode = 302;
  1123. goto last;
  1124. }
  1125. else {
  1126. if (statusCode < 400) {
  1127. socketToClient->sendResponse(401, "Unauthorized");
  1128. statusCode = 401;
  1129. }
  1130. else {
  1131. socketToClient->sendResponse(503, "Service Unavailable");
  1132. statusCode = 503;
  1133. }
  1134. receivedBody.push_back('\0');
  1135. if (!strncasecmp(&receivedBody.front(), "ng (", 4)) {
  1136. log_printf(0, "API gateway returned error: %s\n", &receivedBody.front());
  1137. }
  1138. }
  1139. //fprintf(stderr,"%ld\n",statusCode);
  1140. }
  1141. else {
  1142. log_printf(0, "curl error: %s\n", curl_easy_strerror(res));
  1143. socketToClient->sendResponse(503, "Service Unavailable");
  1144. statusCode = 503;
  1145. }
  1146. last:
  1147. curl_easy_reset(curl);
  1148. curl_slist_free_all(headersForCurl);
  1149. }
  1150. return statusCode;
  1151. }
  1152. int BBS2chProxyConnection::bbsmenuProxy(const std::string &url, const char *method, BBS2chProxyHttpHeaders &requestHeaders)
  1153. {
  1154. long statusCode = 0;
  1155. std::vector<char> dat;
  1156. std::string outHTML;
  1157. if(curl) {
  1158. CURLcode res;
  1159. if(curl_share) curl_easy_setopt(curl, CURLOPT_SHARE, curl_share);
  1160. curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  1161. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
  1162. curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  1163. curl_easy_setopt(curl, CURLOPT_ENCODING, "");
  1164. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback_download);
  1165. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &dat);
  1166. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  1167. curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
  1168. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
  1169. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
  1170. if(force_ipv4) curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
  1171. if(proxy_server) {
  1172. curl_easy_setopt(curl, CURLOPT_PROXY, proxy_server);
  1173. curl_easy_setopt(curl, CURLOPT_PROXYPORT, proxy_port);
  1174. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, proxy_type);
  1175. }
  1176. if(user_agent) {
  1177. curl_easy_setopt(curl, CURLOPT_USERAGENT, user_agent);
  1178. }
  1179. else if(requestHeaders.has("User-Agent")) {
  1180. curl_easy_setopt(curl, CURLOPT_USERAGENT, requestHeaders.get("User-Agent").c_str());
  1181. }
  1182. res = curl_easy_perform(curl);
  1183. if(res == CURLE_OK) {
  1184. curl_easy_getinfo(curl,CURLINFO_RESPONSE_CODE, &statusCode);
  1185. if(statusCode == 200 && dat.size()) {
  1186. dat.push_back('\0');
  1187. char *ptr = &dat.front();
  1188. while(*ptr) {
  1189. if(!strncasecmp(ptr,"<a href=",8)) {
  1190. char *start = ptr+8;
  1191. char *end = strchr(start,'>');
  1192. if (end) {
  1193. char *urlEnd = end;
  1194. if (*start == '"') {
  1195. start++;
  1196. char *tmp = strchr(start, '"');
  1197. if (tmp && tmp < end) urlEnd = tmp;
  1198. }
  1199. BBS2chProxyURL url(std::string(start, urlEnd-start).c_str());
  1200. if (url.isKindOfHost("5ch.net")) {
  1201. url.replaceHost("5ch.net", "2ch.net");
  1202. url.setScheme("http");
  1203. outHTML.append("<A HREF=");
  1204. outHTML.append(url.absoluteString());
  1205. outHTML.append(">");
  1206. ptr = end+1;
  1207. continue;
  1208. } else if (url.isKindOfHost("bbspink.com")) {
  1209. url.setScheme("http");
  1210. outHTML.append("<A HREF=");
  1211. outHTML.append(url.absoluteString());
  1212. outHTML.append(">");
  1213. ptr = end+1;
  1214. continue;
  1215. }
  1216. }
  1217. }
  1218. outHTML.append(ptr++, 1);
  1219. }
  1220. }
  1221. }
  1222. else {
  1223. log_printf(0,"curl error: %s (%s)\n", curl_easy_strerror(res), url.c_str());
  1224. statusCode = 503;
  1225. }
  1226. }
  1227. if(statusCode == 200) {
  1228. std::ostringstream ss;
  1229. ss << "Content-Length: " << outHTML.size() << "\r\n";
  1230. socketToClient->sendBasicHeaders(statusCode, "OK");
  1231. if(0 >= socketToClient->writeString("Content-Type: text/html\r\n")) goto last;
  1232. if(0 >= socketToClient->writeString(ss.str())) goto last;
  1233. if(0 >= socketToClient->writeString("\r\n")) goto last;
  1234. if(strcasecmp(method, "HEAD")) {
  1235. if(0 >= socketToClient->writeString(outHTML)) goto last;
  1236. }
  1237. }
  1238. else {
  1239. socketToClient->sendResponse(503, "Service Unavailable");
  1240. statusCode = 503;
  1241. }
  1242. last:
  1243. if(curl) curl_easy_reset(curl);
  1244. return statusCode;
  1245. }
  1246. int BBS2chProxyConnection::bbsCgiProxy(BBS2chProxyURL &url, BBS2chProxyHttpHeaders &requestHeaders, BBS2chProxyFormData &requestBody, bool talkTo5ch)
  1247. {
  1248. if (talkTo5ch) {
  1249. std::string board = requestBody.get("bbs");
  1250. if (board.size() >= 10 && !board.compare(0, 9, "5channel_")) {
  1251. board = board.substr(9);
  1252. std::string host = boardManager.getServerForBoard(board);
  1253. if (!host.empty()) {
  1254. std::string referrer = force_5chnet_https ? "https://" : "http://";
  1255. referrer += host;
  1256. referrer += "/";
  1257. referrer += board;
  1258. referrer += "/";
  1259. requestHeaders.set("Host", host);
  1260. requestHeaders.set("Referer", referrer);
  1261. requestHeaders.remove("X-Write-Key");
  1262. requestHeaders.remove("X-Write-Token");
  1263. requestBody.set("bbs", board);
  1264. requestBody.remove("sid");
  1265. requestBody.remove("appkey");
  1266. requestBody.remove("anonymous");
  1267. url = BBS2chProxyURL(force_5chnet_https ? "https" : "http", host.c_str(), 0, "/test/bbs.cgi");
  1268. log_printf(1, "Enabled Talk to 5ch proxy, will connect to %s\n", url.absoluteString().c_str());
  1269. }
  1270. else return -1;
  1271. }
  1272. else return -1;
  1273. return BBS2chProxyTalkTo5chPoster(url, requestHeaders, requestBody, this).post();
  1274. }
  1275. if (url.isKindOfHost("talk-platform.com")) {
  1276. return BBS2chProxyTalkPoster(url, requestHeaders, requestBody, this).post();
  1277. }
  1278. return BBS2chProxy5chPoster(url, requestHeaders, requestBody, this).post();
  1279. }
  1280. BBS2chProxyURL BBS2chProxyConnection::getRawDatURLAndStatus(const BBS2chThreadIdentifier &threadIdentifier, BBS2chProxyHttpHeaders &requestHeaders, bool findKakologOnly, long *status, bool *foundAsKakolog)
  1281. {
  1282. long statusCode = 0;
  1283. std::string datURL;
  1284. for (int i=findKakologOnly ? 1 : 0; i<2; i++) {
  1285. datURL = force_5chnet_https ? "https://" : "http://";
  1286. datURL += threadIdentifier.host;
  1287. datURL += '/';
  1288. datURL += threadIdentifier.board;
  1289. if (i) {
  1290. datURL += "/oyster/";
  1291. datURL += threadIdentifier.key.substr(0, std::max(threadIdentifier.key.size() - 6, (size_t)0));
  1292. datURL += "/";
  1293. datURL += threadIdentifier.key;
  1294. datURL += ".dat";
  1295. } else {
  1296. datURL += "/dat/";
  1297. datURL += threadIdentifier.key;
  1298. datURL += ".dat";
  1299. }
  1300. statusCode = 0;
  1301. if (curl) {
  1302. CURLcode res;
  1303. if (curl_share) curl_easy_setopt(curl, CURLOPT_SHARE, curl_share);
  1304. curl_easy_setopt(curl, CURLOPT_URL, datURL.c_str());
  1305. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
  1306. curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  1307. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
  1308. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
  1309. //curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
  1310. if (force_ipv4) curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
  1311. curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
  1312. curl_easy_setopt(curl, CURLOPT_NOBODY, 1L);
  1313. if (user_agent) {
  1314. curl_easy_setopt(curl, CURLOPT_USERAGENT, user_agent);
  1315. }
  1316. else if (requestHeaders.has("User-Agent")) {
  1317. curl_easy_setopt(curl, CURLOPT_USERAGENT, requestHeaders.get("User-Agent").c_str());
  1318. }
  1319. if (proxy_server) {
  1320. curl_easy_setopt(curl, CURLOPT_PROXY, proxy_server);
  1321. curl_easy_setopt(curl, CURLOPT_PROXYPORT, proxy_port);
  1322. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, proxy_type);
  1323. }
  1324. res = curl_easy_perform(curl);
  1325. if (res == CURLE_OK) {
  1326. curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &statusCode);
  1327. }
  1328. curl_easy_reset(curl);
  1329. if (statusCode == 200) {
  1330. if (foundAsKakolog) *foundAsKakolog = !!(i);
  1331. break;
  1332. }
  1333. }
  1334. }
  1335. if (status) *status = statusCode;
  1336. return BBS2chProxyURL(datURL.c_str());
  1337. }
  1338. struct ThreadInfo {
  1339. std::string dat;
  1340. std::string title;
  1341. unsigned long long updated;
  1342. bool operator<(const ThreadInfo& another) const {
  1343. return updated > another.updated;
  1344. };
  1345. };
  1346. int BBS2chProxyConnection::subjectTxtProxy(BBS2chProxyURL &url, const char *method, BBS2chProxyHttpHeaders &requestHeaders)
  1347. {
  1348. long statusCode = 0;
  1349. std::string path = url.getPath();
  1350. size_t pos = path.find("/subject.txt");
  1351. path = path.substr(0, pos);
  1352. path += "/lastmodify.txt";
  1353. BBS2chProxyURL newURL = BBS2chProxyURL(url, path.c_str());
  1354. std::vector<char> data;
  1355. BBS2chProxyHttpHeaders receivedHeaders;
  1356. if (curl_share) curl_easy_setopt(curl, CURLOPT_SHARE, curl_share);
  1357. curl_easy_setopt(curl, CURLOPT_URL, newURL.absoluteString().c_str());
  1358. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
  1359. curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  1360. curl_easy_setopt(curl, CURLOPT_ENCODING, "");
  1361. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback_download);
  1362. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &data);
  1363. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, header_callback_download);
  1364. curl_easy_setopt(curl, CURLOPT_HEADERDATA, &receivedHeaders);
  1365. curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
  1366. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
  1367. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
  1368. if (force_ipv4) curl_easy_setopt(curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
  1369. if (proxy_server) {
  1370. curl_easy_setopt(curl, CURLOPT_PROXY, proxy_server);
  1371. curl_easy_setopt(curl, CURLOPT_PROXYPORT, proxy_port);
  1372. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, proxy_type);
  1373. }
  1374. if (user_agent) {
  1375. curl_easy_setopt(curl, CURLOPT_USERAGENT, user_agent);
  1376. }
  1377. else if (requestHeaders.has("User-Agent")) {
  1378. curl_easy_setopt(curl, CURLOPT_USERAGENT, requestHeaders.get("User-Agent").c_str());
  1379. }
  1380. CURLcode res = curl_easy_perform(curl);
  1381. if (res == CURLE_OK) {
  1382. curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &statusCode);
  1383. if (statusCode == 200) {
  1384. std::string outText;
  1385. std::vector<ThreadInfo> threads;
  1386. data.push_back('\0');
  1387. char *ptr = &data.front();
  1388. while (1) {
  1389. char *start = ptr;
  1390. char *lineEnd = strchr(ptr, '\n');
  1391. ThreadInfo info;
  1392. int i = 0;
  1393. if (!lineEnd) break;
  1394. while (ptr = strstr(start, "<>"), i < 6 && ptr != NULL && ptr < lineEnd) {
  1395. if (i == 0) {
  1396. info.dat = std::string(start, ptr-start);
  1397. } else if (i == 1) {
  1398. info.title = std::string(start, ptr-start);
  1399. } else if (i == 2) {
  1400. std::string suppl = " (" + std::string(start, ptr-start);
  1401. suppl += ")";
  1402. if (*(start-3) == ')') {
  1403. size_t len1 = info.title.length();
  1404. size_t len2 = suppl.length();
  1405. if (len1 < len2 || info.title.compare(len1-len2, len2, suppl)) {
  1406. info.title += suppl;
  1407. }
  1408. }
  1409. else info.title += suppl;
  1410. } else if (i == 5) {
  1411. info.updated = strtoull(start, NULL, 10);
  1412. }
  1413. start = ptr + 2;
  1414. i++;
  1415. }
  1416. if (i == 6) {
  1417. threads.push_back(info);
  1418. }
  1419. ptr = lineEnd+1;
  1420. }
  1421. std::sort(threads.begin(), threads.end());
  1422. for (std::vector<ThreadInfo>::iterator it = threads.begin(); it != threads.end(); ++it) {
  1423. outText += it->dat;
  1424. outText += "<>";
  1425. outText += it->title;
  1426. outText += "\n";
  1427. }
  1428. std::ostringstream ss;
  1429. socketToClient->sendBasicHeaders(200, "OK");
  1430. if (receivedHeaders.has("Last-Modified")) {
  1431. socketToClient->writeString(receivedHeaders.getFull("Last-Modified", true));
  1432. }
  1433. socketToClient->writeString("Content-Type: text/plain\r\n");
  1434. ss << "Content-Length: " << outText.size() << "\r\n\r\n";
  1435. socketToClient->writeString(ss.str());
  1436. if (strcasecmp(method, "HEAD")) {
  1437. socketToClient->writeString(outText);
  1438. }
  1439. }
  1440. }
  1441. else {
  1442. log_printf(0,"curl error: %s (%s)\n", curl_easy_strerror(res), newURL.absoluteString().c_str());
  1443. statusCode = 503;
  1444. }
  1445. if (statusCode != 200) {
  1446. socketToClient->sendResponse(statusCode, "Error");
  1447. }
  1448. curl_easy_reset(curl);
  1449. return statusCode;
  1450. }
  1451. void BBS2chProxyConnection::compileRegex(void)
  1452. {
  1453. static int compiled;
  1454. if (compiled) return;
  1455. regcomp(&regex, "^https?://([^:/.]+)\\.(2ch\\.net|5ch\\.net|bbspink\\.com|talk-platform.com)(:[0-9]+)?/([^/]+)/dat/([0-9]+)\\.dat", REG_EXTENDED|REG_ICASE);
  1456. regcomp(&regex_kako, "^https?://([^:/.]+)\\.(2ch\\.net|5ch\\.net|bbspink\\.com|talk-platform.com)(:[0-9]+)?/([^/]+)/(kako|oyster)/[0-9]+/([0-9]+/)?([0-9]+)\\.dat", REG_EXTENDED|REG_ICASE);
  1457. regcomp(&regex_offlaw, "^https?://([^:/.]+)\\.(2ch\\.net|5ch\\.net|bbspink\\.com)(:[0-9]+)?/test/offlaw2.so\\?.*bbs=([^&]+)", REG_EXTENDED|REG_ICASE);
  1458. regcomp(&regex_api, "^https?://api\\.[25]ch\\.net(:[0-9]+)?/v1/([^/]+)/([^/]+)/([0-9]+)", REG_EXTENDED|REG_ICASE);
  1459. regcomp(&regex_api_auth, "^https?://api\\.[25]ch\\.net(:[0-9]+)?/v1/auth/?$", REG_EXTENDED|REG_ICASE);
  1460. if (talk_to_5ch) {
  1461. regcomp(&regex_talk, "^https?://classic.talk-platform.com/5channel_(([^/]+)/.*)$", REG_EXTENDED|REG_ICASE);
  1462. regcomp(&regex_talk_api, "^https?://api.talk-platform.com/v1/classic/5channel_([^/]+)/([0-9]+)", REG_EXTENDED|REG_ICASE);
  1463. regcomp(&regex_talk_bbscgi, "^https?://api.talk-platform.com/v1/bbs.cgi$", REG_EXTENDED|REG_ICASE);
  1464. }
  1465. compiled = 1;
  1466. }