BBS2chProxyConnection.cpp 54 KB

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