BBS2chProxyConnection.cpp 54 KB

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