BBS2chProxyConnection.cpp 61 KB

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