main.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  1. #include <string>
  2. #include <vector>
  3. #include <map>
  4. #include <stack>
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <string.h>
  8. #include <stdarg.h>
  9. #ifdef _WIN32
  10. #include <winsock2.h>
  11. #include <ws2tcpip.h>
  12. #include <mswsock.h>
  13. #else
  14. #include <sys/socket.h>
  15. #include <netinet/in.h>
  16. #include <netdb.h>
  17. #endif
  18. #include <pthread.h>
  19. #include <signal.h>
  20. #include <getopt.h>
  21. #include <curl/curl.h>
  22. #ifdef USE_LUA
  23. #include <lua.hpp>
  24. #endif
  25. #include "BBS2chProxyConnection.h"
  26. #include "BBS2chProxyThreadInfo.h"
  27. #include "BBS2chProxyAuth.h"
  28. #ifdef USE_MITM
  29. #include "BBS2chProxySecureSocket.h"
  30. #endif
  31. #define PORT 9080
  32. #define VERSION "20220522"
  33. #define BACKLOG 32
  34. #define NUM_LOCKS 7
  35. #ifndef NO_THREAD_POOL
  36. #ifndef NUM_THREADS_DEFAULT
  37. #define NUM_THREADS_DEFAULT 8
  38. #endif
  39. #include "BBS2chProxyThreadPool.h"
  40. static std::stack<void *>curl_handles;
  41. static int num_threads = NUM_THREADS_DEFAULT;
  42. #endif
  43. char *proxy_server;
  44. long proxy_port;
  45. long proxy_type;
  46. long timeout = 30;
  47. char *user_agent;
  48. char *appKey;
  49. char *hmacKey;
  50. char *api_ua_auth;
  51. char *api_ua_dat;
  52. char *x_2ch_ua_auth;
  53. char *x_2ch_ua_dat;
  54. int allow_chunked;
  55. int verbosity;
  56. int curl_features;
  57. unsigned int curl_version_number;
  58. bool accept_https;
  59. int force_5chnet = 1;
  60. int force_5chnet_https;
  61. int force_ipv4;
  62. char *bbsmenu_url;
  63. char *api_server;
  64. std::map<std::string, std::string> bbscgi_headers;
  65. int gikofix;
  66. CURLSH *curl_share;
  67. char *lua_script;
  68. unsigned int api_mode = 3;
  69. unsigned int mitm_mode = 0;
  70. std::vector<std::string> bbscgi_postorder;
  71. unsigned int bbscgi_utf8 = 1;
  72. int api_override;
  73. static pthread_mutex_t lockarray[NUM_LOCKS];
  74. void log_printf(int level, const char *format ...)
  75. {
  76. if(level > verbosity) return;
  77. va_list argp;
  78. va_start(argp, format);
  79. vfprintf(stderr, format, argp);
  80. va_end(argp);
  81. fflush(stderr);
  82. }
  83. struct listener {
  84. int port;
  85. int sock_listener;
  86. struct sockaddr_in addr_listener;
  87. };
  88. static void usage(void)
  89. {
  90. fprintf(stderr,"usage: proxy2ch [OPTIONS]\n");
  91. fprintf(stderr,"available options:\n");
  92. fprintf(stderr," -p <port> : Listen on port <port> (default: %d)\n",PORT);
  93. fprintf(stderr," -t <timeout> : Set connection timeout to <timeout> seconds (default: %ld)\n",timeout);
  94. fprintf(stderr," -a <user-agent> : Overwrite user-agent for connection\n");
  95. fprintf(stderr," -g : Accept all incoming connections (default: localhost only)\n");
  96. fprintf(stderr," -c : Accept HTTP CONNECT method (act as an HTTPS proxy)\n");
  97. fprintf(stderr," -4 : Force IPv4 DNS resolution\n");
  98. fprintf(stderr," -b <backlog> : Set backlog value to <backlog> for listen() (default: %d)\n",BACKLOG);
  99. fprintf(stderr," -s : Force https connection for 5ch.net/bbspink.com URLs\n");
  100. fprintf(stderr," --proxy <server:port> : Use proxy <server:port> for connection\n");
  101. fprintf(stderr," --api <AppKey:HmacKey> : Use API for reading/posting\n");
  102. fprintf(stderr," --api-usage <read|post|all> : Specify operations where API is used (default: all)\n");
  103. fprintf(stderr," --api-auth-ua <user-agent> : Specify user-agent for API authentication\n");
  104. fprintf(stderr," --api-dat-ua <user-agent> : Specify user-agent for dat retrieving via API\n");
  105. fprintf(stderr," --api-auth-xua <X-2ch-UA> : Specify X-2ch-UA for API authentication\n");
  106. fprintf(stderr," --api-dat-xua <X-2ch-UA> : Specify X-2ch-UA for dat retrieving via API\n");
  107. fprintf(stderr," --api-server <server> : Specify gateway server for API\n");
  108. fprintf(stderr," --api-override : Add support for overriding requests which already use API for dat retrieving\n");
  109. fprintf(stderr," --bbsmenu <URL> : Replace \"5ch.net\" occurrences in links for URL\n");
  110. fprintf(stderr," --chunked : Preserve \"chunked\" transfer encoding\n");
  111. fprintf(stderr," --bbscgi-header <header: value> : Force replace header when sending request to bbs.cgi\n");
  112. fprintf(stderr," --bbscgi-postorder <field1,field2,...> : Specify a field order in request body being sent to bbs.cgi\n");
  113. fprintf(stderr," --bbscgi-utf8 <none|api|all> : Specify whether a request body being sent to bbs.cgi should be converted to UTF-8\n");
  114. #ifdef USE_LUA
  115. fprintf(stderr," --bbscgi-lua <path> : Process request header/body being sent to bbs.cgi with a Lua script at <path>\n");
  116. #endif
  117. fprintf(stderr," --verbose : Print logs in detail\n");
  118. fprintf(stderr," --gikofix : Fix invalid HTTP POST body (for gikoNavi)\n");
  119. fprintf(stderr," --keystore <path> : Use a file at <path> as a persistent storage for MonaKey\n");
  120. #ifndef NO_THREAD_POOL
  121. fprintf(stderr," --num-threads <num> : Specify number of threads in a thread pool\n");
  122. #endif
  123. #ifdef USE_MITM
  124. fprintf(stderr," --mitm <minimal|all> : Act as MITM proxy when -c option is given (experimental)\n");
  125. fprintf(stderr," --mitm-ca-cert <certpath> : Specify CA certificate in PEM format for MITM proxy\n");
  126. fprintf(stderr," --mitm-ca-key <keypath> : Specify CA private key in PEM format for MITM proxy\n");
  127. fprintf(stderr," --mitm-certgen : Generate self-signed CA certificate and private key, print them in PEM format, and exit\n");
  128. #endif
  129. }
  130. static void *threadMainLoop(void *param)
  131. {
  132. #ifndef _WIN32
  133. sigset_t signalsToIgnore;
  134. sigemptyset(&signalsToIgnore);
  135. sigaddset(&signalsToIgnore, SIGPIPE);
  136. if (-1 == pthread_sigmask(SIG_BLOCK, &signalsToIgnore, NULL)) {
  137. perror("pthread_sigmask");
  138. return NULL;
  139. }
  140. #endif
  141. CURL *curl = curl_easy_init();
  142. #ifndef NO_THREAD_POOL
  143. BBS2chProxyThreadPool<PBBS2chProxyConnection> *pool = reinterpret_cast<BBS2chProxyThreadPool<PBBS2chProxyConnection> *>(param);
  144. #ifndef NO_CURL_REUSE_HTTPS
  145. bool canReuseHttps = curl_version_number >= 0x75000; /* 7.80.0 and later */
  146. #else
  147. bool canReuseHttps = false;
  148. #endif
  149. pool->lock();
  150. curl_handles.push(curl);
  151. pool->unlock();
  152. while (1) {
  153. PBBS2chProxyConnection connection;
  154. if (pool->getAndLock(&connection) != 0) {
  155. curl = curl_handles.top();
  156. curl_handles.pop();
  157. pool->unlock();
  158. break;
  159. }
  160. connection->curl = curl_handles.top();
  161. curl_handles.pop();
  162. pool->unlock();
  163. connection->connect();
  164. pool->lock();
  165. /* curl_easy_reset does not necessaryly release unused TLS contexts, and
  166. it results in waste of memory. This issue seems to be fixed in curl
  167. 7.80.0 and later, but in the earlier versions the logic below might
  168. be useful to reduce memory consumption.
  169. Ref: https://github.com/curl/curl/issues/7683 */
  170. /*if (curl_handles.size() + 2 < num_threads && pool->countInQueue() == 0) {
  171. curl_easy_cleanup(connection->curl);
  172. connection->curl = curl_easy_init();
  173. }*/
  174. if (!canReuseHttps && connection->isHttps) {
  175. curl_easy_cleanup(connection->curl);
  176. connection->curl = curl_easy_init();
  177. }
  178. curl_handles.push(connection->curl);
  179. pool->unlock();
  180. }
  181. #else
  182. BBS2chProxyConnection *connection = reinterpret_cast<BBS2chProxyConnection *>(param);
  183. connection->curl = curl;
  184. connection->connect();
  185. delete connection;
  186. #endif
  187. curl_easy_cleanup(curl);
  188. return NULL;
  189. }
  190. static void *listen(void *param)
  191. {
  192. struct listener *listener = (struct listener *)param;
  193. log_printf(0,"Listening on port %d...\n",listener->port);
  194. if(listener->addr_listener.sin_addr.s_addr == INADDR_ANY) {
  195. log_printf(0,"WARNING: proxy accepts all incoming connections!\n");
  196. }
  197. fflush(stderr);
  198. int sock_c;
  199. pthread_mutex_t mutex;
  200. BBS2chProxyThreadCache cache;
  201. socklen_t addrlen = sizeof(listener->addr_listener);
  202. pthread_mutex_init(&mutex, NULL);
  203. #ifndef NO_THREAD_POOL
  204. BBS2chProxyThreadPool<PBBS2chProxyConnection> pool(num_threads);
  205. pool.run(threadMainLoop);
  206. #endif
  207. while(1) {
  208. if (-1 == (sock_c = accept(listener->sock_listener, (struct sockaddr *)&listener->addr_listener, &addrlen))) {
  209. perror("accept");
  210. continue;
  211. }
  212. //fprintf(stderr,"accepted\n");
  213. #ifndef NO_THREAD_POOL
  214. PBBS2chProxyConnection connection(new BBS2chProxyConnection(sock_c, &cache, &mutex));
  215. pool.add(connection);
  216. #else
  217. BBS2chProxyConnection *connection = new BBS2chProxyConnection(sock_c, &cache, &mutex);
  218. connection->run(threadMainLoop);
  219. #endif
  220. }
  221. pthread_mutex_destroy(&mutex);
  222. }
  223. static void lock_cb(CURL *handle, curl_lock_data data, curl_lock_access access, void *userptr)
  224. {
  225. pthread_mutex_lock(&lockarray[data]);
  226. }
  227. static void unlock_cb(CURL *handle, curl_lock_data data, void *userptr)
  228. {
  229. pthread_mutex_unlock(&lockarray[data]);
  230. }
  231. static void init_locks(void)
  232. {
  233. int i;
  234. for(i = 0; i< NUM_LOCKS; i++)
  235. pthread_mutex_init(&lockarray[i], NULL);
  236. }
  237. int main(int argc, char *argv[])
  238. {
  239. struct listener listener;
  240. int ch;
  241. extern char *optarg;
  242. extern int optind, opterr;
  243. int option_index;
  244. bool global = false;
  245. int backlog = BACKLOG;
  246. const char *certpath = NULL, *keypath = NULL;
  247. const char *keyStorage = NULL;
  248. struct option options[] = {
  249. {"proxy", 1, NULL, 0},
  250. {"api", 1, NULL, 0},
  251. {"api-auth-ua", 1, NULL, 0},
  252. {"api-dat-ua", 1, NULL, 0},
  253. {"api-auth-xua", 1, NULL, 0},
  254. {"api-dat-xua", 1, NULL, 0},
  255. {"api-server", 1, NULL, 0},
  256. {"api-usage", 1, NULL, 0},
  257. {"api-override", 0, NULL, 0},
  258. {"bbsmenu", 1, NULL, 0},
  259. {"chunked", 0, NULL, 0},
  260. {"verbose", 0, NULL, 0},
  261. {"debug", 0, NULL, 0},
  262. {"bbscgi-header", 1, NULL, 0},
  263. {"bbscgi-postorder", 1, NULL, 0},
  264. {"bbscgi-utf8", 1, NULL, 0},
  265. #ifdef USE_LUA
  266. {"bbscgi-lua", 1, NULL, 0},
  267. #endif
  268. {"gikofix", 0, NULL, 0},
  269. {"keystore", 1, NULL, 0},
  270. #ifdef USE_MITM
  271. {"mitm", 1, NULL, 0},
  272. {"mitm-ca-cert", 1, NULL, 0},
  273. {"mitm-ca-key", 1, NULL, 0},
  274. {"mitm-certgen", 0, NULL, 0},
  275. #endif
  276. #ifndef NO_THREAD_POOL
  277. {"num-threads", 1, NULL, 0},
  278. #endif
  279. {0, 0, 0, 0}
  280. };
  281. curl_global_init(CURL_GLOBAL_DEFAULT);
  282. curl_version_info_data *data = curl_version_info(CURLVERSION_NOW);
  283. curl_features = data->features;
  284. curl_version_number = data->version_num;
  285. if(data->version_num >= 0x074400) { /* version 7.68.0 or later */
  286. init_locks();
  287. curl_share = curl_share_init();
  288. curl_share_setopt(curl_share, CURLSHOPT_LOCKFUNC, lock_cb);
  289. curl_share_setopt(curl_share, CURLSHOPT_UNLOCKFUNC, unlock_cb);
  290. curl_share_setopt(curl_share, CURLSHOPT_SHARE, CURL_LOCK_DATA_DNS);
  291. #if LIBCURL_VERSION_NUM >= 0x070a03
  292. curl_share_setopt(curl_share, CURLSHOPT_SHARE, CURL_LOCK_DATA_SSL_SESSION);
  293. #endif
  294. /* Shared connection cache is still buggy at the moment!
  295. See https://github.com/curl/curl/issues/4915 */
  296. #if 0 && LIBCURL_VERSION_NUM >= 0x073900
  297. curl_share_setopt(curl_share, CURLSHOPT_SHARE, CURL_LOCK_DATA_CONNECT);
  298. #endif
  299. }
  300. log_printf(0,"proxy2ch version %s with curl %s (TLS/SSL backend: %s)\n",VERSION,data->version,data->ssl_version);
  301. #ifdef USE_LUA
  302. log_printf(0,"Scripting enabled with " LUA_RELEASE "\n");
  303. #endif
  304. memset(&listener, 0, sizeof(listener));
  305. listener.port = PORT;
  306. api_server = strdup("api.5ch.net");
  307. while ((ch = getopt_long(argc, argv, "p:t:ha:gc4b:s", options, &option_index)) != -1) {
  308. switch (ch) {
  309. case 0:
  310. if(!strcmp(options[option_index].name, "proxy")) {
  311. char *ptr = strchr(optarg, '@');
  312. if(!ptr) {
  313. ptr = strstr(optarg, "://");
  314. if(ptr) ptr = strchr(ptr+3,':');
  315. else ptr = strchr(optarg,':');
  316. }
  317. else ptr = strchr(ptr+1,':');
  318. if(!ptr) {
  319. fprintf(stderr,"Proxy port is not specified, as --proxy=server:port\n");
  320. return -1;
  321. }
  322. proxy_server = (char *)malloc(ptr-optarg+1);
  323. proxy_port = atoi(ptr+1);
  324. memcpy(proxy_server,optarg,ptr-optarg);
  325. proxy_server[ptr-optarg] = 0;
  326. if(!strncasecmp(optarg,"socks4://",9)) proxy_type = CURLPROXY_SOCKS4;
  327. else if(!strncasecmp(optarg,"socks5://",9)) proxy_type = CURLPROXY_SOCKS5;
  328. #if LIBCURL_VERSION_NUM >= 0x071200
  329. else if(!strncasecmp(optarg,"socks4a://",10)) proxy_type = CURLPROXY_SOCKS4A;
  330. else if(!strncasecmp(optarg,"socks5h://",10)) proxy_type = CURLPROXY_SOCKS5_HOSTNAME;
  331. #endif
  332. }
  333. else if(!strcmp(options[option_index].name, "api")) {
  334. if((curl_features & CURL_VERSION_SSL) == 0) {
  335. fprintf(stderr,"Your libcurl doesn't support HTTPS; API mode cannot be enabled.\n");
  336. return -1;
  337. }
  338. char *ptr = strchr(optarg, ':');
  339. if(!ptr) {
  340. fprintf(stderr,"API keys should be provided as AppKey:HmacKey\n");
  341. return -1;
  342. }
  343. appKey = (char *)malloc(ptr-optarg+1);
  344. memcpy(appKey,optarg,ptr-optarg);
  345. appKey[ptr-optarg] = 0;
  346. char *start = ptr+1;
  347. ptr = strchr(start, ':');
  348. if(!ptr) ptr = strchr(optarg, 0);
  349. hmacKey = (char *)malloc(ptr-start+1);
  350. memcpy(hmacKey,start,ptr-start);
  351. hmacKey[ptr-start] = 0;
  352. /*if(*ptr) {
  353. x_2ch_ua = (char *)malloc(strlen(ptr+1)+11);
  354. sprintf(x_2ch_ua,"X-2ch-UA: %s",ptr+1);
  355. }*/
  356. //fprintf(stderr,"%s,%s,%s\n",appKey,hmacKey,x_2ch_ua);
  357. //return 0;
  358. }
  359. else if(!strcmp(options[option_index].name, "api-auth-ua")) {
  360. api_ua_auth = (char *)malloc(strlen(optarg)+1);
  361. strcpy(api_ua_auth,optarg);
  362. }
  363. else if(!strcmp(options[option_index].name, "api-dat-ua")) {
  364. api_ua_dat = (char *)malloc(strlen(optarg)+1);
  365. strcpy(api_ua_dat,optarg);
  366. }
  367. else if(!strcmp(options[option_index].name, "api-auth-xua")) {
  368. x_2ch_ua_auth = (char *)malloc(strlen(optarg)+11);
  369. sprintf(x_2ch_ua_auth,"X-2ch-UA: %s",optarg);
  370. }
  371. else if(!strcmp(options[option_index].name, "api-dat-xua")) {
  372. x_2ch_ua_dat = (char *)malloc(strlen(optarg)+11);
  373. sprintf(x_2ch_ua_dat,"X-2ch-UA: %s",optarg);
  374. }
  375. else if(!strcmp(options[option_index].name, "chunked")) {
  376. allow_chunked = 1;
  377. }
  378. else if(!strcmp(options[option_index].name, "verbose")) {
  379. verbosity = 1;
  380. }
  381. else if(!strcmp(options[option_index].name, "debug")) {
  382. verbosity = 5;
  383. }
  384. else if(!strcmp(options[option_index].name, "bbsmenu")) {
  385. bbsmenu_url = (char *)malloc(strlen(optarg)+1);
  386. strcpy(bbsmenu_url, optarg);
  387. }
  388. else if(!strcmp(options[option_index].name, "api-server")) {
  389. if(api_server) free(api_server);
  390. api_server = (char *)malloc(strlen(optarg)+1);
  391. strcpy(api_server, optarg);
  392. }
  393. else if(!strcmp(options[option_index].name, "bbscgi-header")) {
  394. char *ptr = strchr(optarg, ':');
  395. if(!ptr) break;
  396. char *header = (char *)malloc(ptr-optarg+1);
  397. memcpy(header,optarg,ptr-optarg);
  398. header[ptr-optarg] = 0;
  399. char *value = ptr+1;
  400. ptr = header+(ptr-optarg-1);
  401. while(*ptr == ' ') *ptr-- = 0;
  402. while(*value == ' ') value++;
  403. bbscgi_headers[header] = value;
  404. free(header);
  405. }
  406. else if(!strcmp(options[option_index].name, "bbscgi-postorder")) {
  407. const char *ptr = optarg;
  408. while(*ptr == ' ') ptr++;
  409. while(*ptr) {
  410. const char *end = strchr(ptr, ',');
  411. if(end) {
  412. const char *next = end + 1;
  413. if(end > ptr) {
  414. end--;
  415. while(*end == ' ' && end > ptr) end--;
  416. bbscgi_postorder.push_back(std::string(ptr, end-ptr+1));
  417. }
  418. ptr = next;
  419. while(*ptr == ' ') ptr++;
  420. continue;
  421. }
  422. end = strchr(ptr, 0);
  423. while(*end == ' ' && end > ptr) end--;
  424. if(end > ptr) bbscgi_postorder.push_back(std::string(ptr, end-ptr));
  425. break;
  426. }
  427. }
  428. else if(!strcmp(options[option_index].name, "bbscgi-utf8")) {
  429. if(!strcmp(optarg, "none")) bbscgi_utf8 = 0;
  430. else if(!strcmp(optarg, "api")) bbscgi_utf8 = 1;
  431. else if(!strcmp(optarg, "all")) bbscgi_utf8 = 2;
  432. else {
  433. fprintf(stderr, "A value for --bbscgi-utf8 must be one of [none, api, all]\n");
  434. return -1;
  435. }
  436. }
  437. #ifdef USE_LUA
  438. else if(!strcmp(options[option_index].name, "bbscgi-lua")) {
  439. lua_script = (char *)malloc(strlen(optarg)+1);
  440. strcpy(lua_script, optarg);
  441. }
  442. #endif
  443. else if(!strcmp(options[option_index].name, "gikofix")) {
  444. gikofix = 1;
  445. }
  446. else if(!strcmp(options[option_index].name, "api-usage")) {
  447. if(!strcmp(optarg, "read")) api_mode = 1;
  448. else if(!strcmp(optarg, "post")) api_mode = 2;
  449. else if(!strcmp(optarg, "postinclpink")) api_mode = 4;
  450. else if(!strcmp(optarg, "all")) api_mode = 3;
  451. else if(!strcmp(optarg, "allinclpink")) api_mode = 5;
  452. else {
  453. fprintf(stderr, "A value for --api-usage must be one of [read, post, postinclpink, all, allinclpink]\n");
  454. return -1;
  455. }
  456. }
  457. else if(!strcmp(options[option_index].name, "api-override")) {
  458. api_override = 1;
  459. }
  460. #ifdef USE_MITM
  461. else if(!strcmp(options[option_index].name, "mitm")) {
  462. if(!strcmp(optarg, "minimal")) mitm_mode = 1;
  463. else if(!strcmp(optarg, "all")) mitm_mode = 2;
  464. else {
  465. fprintf(stderr, "A value for --mitm must be one of [minimal, all]\n");
  466. return -1;
  467. }
  468. }
  469. else if(!strcmp(options[option_index].name, "mitm-ca-cert")) {
  470. certpath = optarg;
  471. }
  472. else if(!strcmp(options[option_index].name, "mitm-ca-key")) {
  473. keypath = optarg;
  474. }
  475. else if(!strcmp(options[option_index].name, "mitm-certgen")) {
  476. BBS2chProxySecureSocket::generateAndPrintSelfSignedCertificate();
  477. return 0;
  478. }
  479. #endif
  480. #ifndef NO_THREAD_POOL
  481. else if(!strcmp(options[option_index].name, "num-threads")) {
  482. int num = atoi(optarg);
  483. if (num < 1) {
  484. fprintf(stderr, "Number of threads must be greater than 0\n");
  485. return -1;
  486. }
  487. if (num > 64) {
  488. fprintf(stderr, "Number of threads must be less than or equal to 64\n");
  489. return -1;
  490. }
  491. num_threads = num;
  492. }
  493. #endif
  494. else if(!strcmp(options[option_index].name, "keystore")) {
  495. keyStorage = optarg;
  496. }
  497. break;
  498. case 'p':
  499. listener.port = atoi(optarg);
  500. break;
  501. case 't':
  502. timeout = atoi(optarg);
  503. break;
  504. case 'a':
  505. user_agent = (char *)malloc(strlen(optarg)+1);
  506. strcpy(user_agent, optarg);
  507. break;
  508. case 'g':
  509. global = true;
  510. break;
  511. case 'c':
  512. accept_https = true;
  513. break;
  514. case '4':
  515. force_ipv4 = 1;
  516. break;
  517. case 'b':
  518. backlog = atoi(optarg);
  519. break;
  520. case 's':
  521. if((curl_features & CURL_VERSION_SSL) == 0) {
  522. fprintf(stderr,"Your libcurl doesn't support HTTPS; it does not work with -s option.\n");
  523. return -1;
  524. }
  525. if(strstr(data->ssl_version, "OpenSSL/0") || strstr(data->ssl_version, "OpenSSL/1.0") ||
  526. (strstr(data->ssl_version, "LibreSSL/2") && !strstr(data->ssl_version, "LibreSSL/2.9"))) {
  527. fprintf(stderr,
  528. "WARNING: OpenSSL < 1.1.0 and LibreSSL < 2.9.0 aren't thread-safe without setting callbacks for mutex. "
  529. "It may cause unintended crashes when many requests are incoming at the same time.\n");
  530. }
  531. force_5chnet_https = 1;
  532. break;
  533. default:
  534. usage();
  535. return 0;
  536. }
  537. }
  538. if (api_override && !appKey) {
  539. fprintf(stderr, "WARNING: --api-override option requires an API key.\n");
  540. }
  541. #ifdef USE_MITM
  542. if (mitm_mode) {
  543. if (!certpath || !keypath) {
  544. fprintf(stderr, "MITM is enabled but certificate and/or key is not given.\n");
  545. return -1;
  546. }
  547. if (BBS2chProxySecureSocket::initializeCerts(certpath, keypath) != 0) {
  548. fprintf(stderr, "MITM is enabled but given certificate and/or key is invalid.\n");
  549. return -1;
  550. }
  551. if (!accept_https) {
  552. fprintf(stderr, "WARNING: --mitm option is given but -c is not given. MITM mode is disabled.\n");
  553. }
  554. }
  555. #endif
  556. log_printf(0, "Global User-Agent: %s\n",user_agent?user_agent:"n/a");
  557. if(appKey) {
  558. log_printf(0, "Use API for:");
  559. if (api_mode & 1) log_printf(0, " reading");
  560. if (api_mode & 2) log_printf(0, " posting");
  561. if (api_mode & 4) log_printf(0, " posting (including bbspink)");
  562. log_printf(0, "\n");
  563. if (api_mode & 1) {
  564. const char *altUserAgent = "";
  565. if (user_agent && !strncmp(user_agent, "Monazilla/", strlen("Monazilla/"))) altUserAgent = user_agent;
  566. log_printf(0, "API gateway server: %s\n",api_server);
  567. log_printf(0, "User-Agent (for API authentication): %s\n",api_ua_auth?api_ua_auth:altUserAgent);
  568. log_printf(0, "User-Agent (for API dat retrieving): %s\n",api_ua_dat?api_ua_dat:altUserAgent);
  569. log_printf(0, "X-2ch-UA (for API authentication): %s\n",x_2ch_ua_auth?x_2ch_ua_auth+10:"");
  570. log_printf(0, "X-2ch-UA (for API dat retrieving): %s\n",x_2ch_ua_dat?x_2ch_ua_dat+10:"");
  571. }
  572. }
  573. if(!bbscgi_headers.empty()) {
  574. log_printf(0, "Custom headers for bbs.cgi:\n");
  575. for(std::map<std::string, std::string>::iterator it = bbscgi_headers.begin(); it!=bbscgi_headers.end(); it++) {
  576. log_printf(0, " %s: %s\n", it->first.c_str(), it->second.c_str());
  577. }
  578. }
  579. if(lua_script) {
  580. log_printf(0, "Use Lua script %s for bbs.cgi request modification\n", lua_script);
  581. }
  582. if(proxy_server) {
  583. log_printf(0,"Use proxy %s:%ld for connection\n",proxy_server,proxy_port);
  584. }
  585. if (keyStorage) {
  586. BBS2chProxyConnection::keyManager.setStorage(keyStorage);
  587. int loaded = BBS2chProxyConnection::keyManager.loadKeys();
  588. if (loaded) {
  589. log_printf(0, "Loaded %d keys from %s\n", loaded, keyStorage);
  590. }
  591. }
  592. BBS2chProxyConnection::compileRegex();
  593. #ifdef _WIN32
  594. WSADATA wsaData;
  595. if (WSAStartup(MAKEWORD(2, 0), &wsaData) == SOCKET_ERROR) {
  596. fprintf(stderr, "WSAStartup: error initializing WSA.\n");
  597. return -1;
  598. }
  599. #endif
  600. listener.addr_listener.sin_family = AF_INET;
  601. if(global) listener.addr_listener.sin_addr.s_addr = INADDR_ANY;
  602. else listener.addr_listener.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  603. listener.addr_listener.sin_port = htons(listener.port);
  604. #ifdef _WIN32
  605. if ((listener.sock_listener = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, 0)) == INVALID_SOCKET) {
  606. fprintf(stderr,"WSASocket: socket initialize error\n");
  607. return -1;
  608. }
  609. #else
  610. if (-1 == (listener.sock_listener = socket(AF_INET, SOCK_STREAM, 0))) {
  611. perror("socket");
  612. return -1;
  613. }
  614. #endif
  615. int optval=1;
  616. setsockopt(listener.sock_listener, SOL_SOCKET, SO_REUSEADDR, (char *)&optval, sizeof(optval));
  617. #ifdef _WIN32
  618. optval = SO_SYNCHRONOUS_NONALERT;
  619. setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE, (char *)&optval, sizeof(optval));
  620. #endif
  621. socklen_t addrlen = sizeof(listener.addr_listener);
  622. if (-1 == bind(listener.sock_listener, (struct sockaddr *)&listener.addr_listener, addrlen)) {
  623. perror("bind");
  624. return -1;
  625. }
  626. if (-1 == listen(listener.sock_listener, backlog)) {
  627. perror("listen");
  628. return -1;
  629. }
  630. if (-1 == getsockname(listener.sock_listener, (struct sockaddr *)&listener.addr_listener, &addrlen)) {
  631. perror("getsockname");
  632. return -1;
  633. }
  634. #ifndef _WIN32
  635. struct sigaction sa;
  636. memset(&sa, 0, sizeof(sa));
  637. sa.sa_handler = SIG_IGN;
  638. sigemptyset(&sa.sa_mask);
  639. if (-1 == sigaction(SIGPIPE, &sa, NULL)) {
  640. perror("sigaction");
  641. return -1;
  642. }
  643. #endif
  644. #if 0
  645. pthread_t thread_listener;
  646. if(0 != pthread_create(&thread_listener , NULL , listen , &listener))
  647. perror("pthread_create");
  648. pthread_join(thread_listener, NULL);
  649. #else
  650. listen(&listener);
  651. #endif
  652. return 0;
  653. }