main.cpp 17 KB

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