PageRenderTime 55ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/src/main/jni/badvpn/client/client.c

https://bitbucket.org/madeye/shadowsocks-android
C | 2997 lines | 2173 code | 480 blank | 344 comment | 446 complexity | 0f9a0d4b763132203a898d1a14789a57 MD5 | raw file
Possible License(s): BSD-3-Clause, GPL-2.0

Large files files are truncated, but you can click here to view the full file

  1. /**
  2. * @file client.c
  3. * @author Ambroz Bizjak <ambrop7@gmail.com>
  4. *
  5. * @section LICENSE
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions are met:
  9. * 1. Redistributions of source code must retain the above copyright
  10. * notice, this list of conditions and the following disclaimer.
  11. * 2. Redistributions in binary form must reproduce the above copyright
  12. * notice, this list of conditions and the following disclaimer in the
  13. * documentation and/or other materials provided with the distribution.
  14. * 3. Neither the name of the author nor the
  15. * names of its contributors may be used to endorse or promote products
  16. * derived from this software without specific prior written permission.
  17. *
  18. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  19. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  20. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  21. * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  22. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  23. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  24. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  25. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  27. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. */
  29. #include <stdint.h>
  30. #include <stdlib.h>
  31. #include <string.h>
  32. #include <limits.h>
  33. #include <protocol/msgproto.h>
  34. #include <protocol/addr.h>
  35. #include <protocol/dataproto.h>
  36. #include <misc/version.h>
  37. #include <misc/debug.h>
  38. #include <misc/offset.h>
  39. #include <misc/byteorder.h>
  40. #include <misc/nsskey.h>
  41. #include <misc/loglevel.h>
  42. #include <misc/loggers_string.h>
  43. #include <misc/string_begins_with.h>
  44. #include <misc/open_standard_streams.h>
  45. #include <structure/LinkedList1.h>
  46. #include <base/DebugObject.h>
  47. #include <base/BLog.h>
  48. #include <security/BSecurity.h>
  49. #include <security/BRandom.h>
  50. #include <system/BSignal.h>
  51. #include <system/BTime.h>
  52. #include <system/BNetwork.h>
  53. #include <nspr_support/DummyPRFileDesc.h>
  54. #include <nspr_support/BSSLConnection.h>
  55. #include <server_connection/ServerConnection.h>
  56. #include <tuntap/BTap.h>
  57. #include <threadwork/BThreadWork.h>
  58. #ifndef BADVPN_USE_WINAPI
  59. #include <base/BLog_syslog.h>
  60. #endif
  61. #include <client/client.h>
  62. #include <generated/blog_channel_client.h>
  63. #define TRANSPORT_MODE_UDP 0
  64. #define TRANSPORT_MODE_TCP 1
  65. #define LOGGER_STDOUT 1
  66. #define LOGGER_SYSLOG 2
  67. // command-line options
  68. struct ext_addr_option {
  69. char *addr;
  70. char *scope;
  71. };
  72. struct bind_addr_option {
  73. char *addr;
  74. int num_ports;
  75. int num_ext_addrs;
  76. struct ext_addr_option ext_addrs[MAX_EXT_ADDRS];
  77. };
  78. struct {
  79. int help;
  80. int version;
  81. int logger;
  82. #ifndef BADVPN_USE_WINAPI
  83. char *logger_syslog_facility;
  84. char *logger_syslog_ident;
  85. #endif
  86. int loglevel;
  87. int loglevels[BLOG_NUM_CHANNELS];
  88. int threads;
  89. int use_threads_for_ssl_handshake;
  90. int use_threads_for_ssl_data;
  91. int ssl;
  92. char *nssdb;
  93. char *client_cert_name;
  94. char *server_name;
  95. char *server_addr;
  96. char *tapdev;
  97. int num_scopes;
  98. char *scopes[MAX_SCOPES];
  99. int num_bind_addrs;
  100. struct bind_addr_option bind_addrs[MAX_BIND_ADDRS];
  101. int transport_mode;
  102. int encryption_mode;
  103. int hash_mode;
  104. int otp_mode;
  105. int otp_num;
  106. int otp_num_warn;
  107. int fragmentation_latency;
  108. int peer_ssl;
  109. int peer_tcp_socket_sndbuf;
  110. int send_buffer_size;
  111. int send_buffer_relay_size;
  112. int max_macs;
  113. int max_groups;
  114. int igmp_group_membership_interval;
  115. int igmp_last_member_query_time;
  116. int allow_peer_talk_without_ssl;
  117. int max_peers;
  118. } options;
  119. // bind addresses
  120. struct ext_addr {
  121. int server_reported_port;
  122. BAddr addr; // if server_reported_port>=0, defined only after hello received
  123. char scope[64];
  124. };
  125. struct bind_addr {
  126. BAddr addr;
  127. int num_ports;
  128. int num_ext_addrs;
  129. struct ext_addr ext_addrs[MAX_EXT_ADDRS];
  130. };
  131. int num_bind_addrs;
  132. struct bind_addr bind_addrs[MAX_BIND_ADDRS];
  133. // TCP listeners
  134. PasswordListener listeners[MAX_BIND_ADDRS];
  135. // SPProto parameters (UDP only)
  136. struct spproto_security_params sp_params;
  137. // server address we connect to
  138. BAddr server_addr;
  139. // server name to use for SSL
  140. char server_name[256];
  141. // reactor
  142. BReactor ss;
  143. // thread work dispatcher
  144. BThreadWorkDispatcher twd;
  145. // client certificate if using SSL
  146. CERTCertificate *client_cert;
  147. // client private key if using SSL
  148. SECKEYPrivateKey *client_key;
  149. // device
  150. BTap device;
  151. int device_mtu;
  152. // DataProtoSource for device input (reading)
  153. DataProtoSource device_dpsource;
  154. // DPReceiveDevice for device output (writing)
  155. DPReceiveDevice device_output_dprd;
  156. // data communication MTU
  157. int data_mtu;
  158. // peers list
  159. LinkedList1 peers;
  160. int num_peers;
  161. // frame decider
  162. FrameDecider frame_decider;
  163. // peers that can be user as relays
  164. LinkedList1 relays;
  165. // peers than need a relay
  166. LinkedList1 waiting_relay_peers;
  167. // server connection
  168. ServerConnection server;
  169. // my ID, defined only after server_ready
  170. peerid_t my_id;
  171. // fair queue for sending peer messages to the server
  172. PacketPassFairQueue server_queue;
  173. // whether server is ready
  174. int server_ready;
  175. // dying server flow
  176. struct server_flow *dying_server_flow;
  177. // stops event processing, causing the program to exit
  178. static void terminate (void);
  179. // prints program name and version to standard output
  180. static void print_help (const char *name);
  181. // prints program name and version to standard output
  182. static void print_version (void);
  183. // parses the command line
  184. static int parse_arguments (int argc, char *argv[]);
  185. // processes certain command line options
  186. static int process_arguments (void);
  187. static int ssl_flags (void);
  188. // handler for program termination request
  189. static void signal_handler (void *unused);
  190. // adds a new peer
  191. static void peer_add (peerid_t id, int flags, const uint8_t *cert, int cert_len);
  192. // removes a peer
  193. static void peer_remove (struct peer_data *peer, int exiting);
  194. // appends the peer log prefix to the logger
  195. static void peer_logfunc (struct peer_data *peer);
  196. // passes a message to the logger, prepending it info about the peer
  197. static void peer_log (struct peer_data *peer, int level, const char *fmt, ...);
  198. // see if we are the master relative to this peer
  199. static int peer_am_master (struct peer_data *peer);
  200. // frees PeerChat, disconnecting it from the server flow
  201. static void peer_free_chat (struct peer_data *peer);
  202. // initializes the link
  203. static int peer_init_link (struct peer_data *peer);
  204. // frees link resources
  205. static void peer_free_link (struct peer_data *peer);
  206. // frees link, relaying, waiting relaying
  207. static void peer_cleanup_connections (struct peer_data *peer);
  208. // registers the peer as a relay provider
  209. static void peer_enable_relay_provider (struct peer_data *peer);
  210. // unregisters the peer as a relay provider
  211. static void peer_disable_relay_provider (struct peer_data *peer);
  212. // install relaying for a peer
  213. static void peer_install_relaying (struct peer_data *peer, struct peer_data *relay);
  214. // uninstall relaying for a peer
  215. static void peer_free_relaying (struct peer_data *peer);
  216. // handle a peer that needs a relay
  217. static void peer_need_relay (struct peer_data *peer);
  218. // inserts the peer into the need relay list
  219. static void peer_register_need_relay (struct peer_data *peer);
  220. // removes the peer from the need relay list
  221. static void peer_unregister_need_relay (struct peer_data *peer);
  222. // handle a link setup failure
  223. static void peer_reset (struct peer_data *peer);
  224. // fees chat and sends resetpeer
  225. static void peer_resetpeer (struct peer_data *peer);
  226. // chat handlers
  227. static void peer_chat_handler_error (struct peer_data *peer);
  228. static void peer_chat_handler_message (struct peer_data *peer, uint8_t *data, int data_len);
  229. // handlers for different message types
  230. static void peer_msg_youconnect (struct peer_data *peer, uint8_t *data, int data_len);
  231. static void peer_msg_cannotconnect (struct peer_data *peer, uint8_t *data, int data_len);
  232. static void peer_msg_cannotbind (struct peer_data *peer, uint8_t *data, int data_len);
  233. static void peer_msg_seed (struct peer_data *peer, uint8_t *data, int data_len);
  234. static void peer_msg_confirmseed (struct peer_data *peer, uint8_t *data, int data_len);
  235. static void peer_msg_youretry (struct peer_data *peer, uint8_t *data, int data_len);
  236. // handler from DatagramPeerIO when we should generate a new OTP send seed
  237. static void peer_udp_pio_handler_seed_warning (struct peer_data *peer);
  238. // handler from DatagramPeerIO when a new OTP seed can be recognized once it was provided to it
  239. static void peer_udp_pio_handler_seed_ready (struct peer_data *peer);
  240. // handler from DatagramPeerIO when an error occurs on the connection
  241. static void peer_udp_pio_handler_error (struct peer_data *peer);
  242. // handler from StreamPeerIO when an error occurs on the connection
  243. static void peer_tcp_pio_handler_error (struct peer_data *peer);
  244. // peer retry timer handler. The timer is used only on the master side,
  245. // wither when we detect an error, or the peer reports an error.
  246. static void peer_reset_timer_handler (struct peer_data *peer);
  247. // start binding, according to the protocol
  248. static void peer_start_binding (struct peer_data *peer);
  249. // tries binding on one address, according to the protocol
  250. static void peer_bind (struct peer_data *peer);
  251. static void peer_bind_one_address (struct peer_data *peer, int addr_index, int *cont);
  252. static void peer_connect (struct peer_data *peer, BAddr addr, uint8_t *encryption_key, uint64_t password);
  253. static int peer_start_msg (struct peer_data *peer, void **data, int type, int len);
  254. static void peer_end_msg (struct peer_data *peer);
  255. // sends a message with no payload to the peer
  256. static void peer_send_simple (struct peer_data *peer, int msgid);
  257. static void peer_send_conectinfo (struct peer_data *peer, int addr_index, int port_adjust, uint8_t *enckey, uint64_t pass);
  258. static void peer_send_confirmseed (struct peer_data *peer, uint16_t seed_id);
  259. // handler for peer DataProto up state changes
  260. static void peer_dataproto_handler (struct peer_data *peer, int up);
  261. // looks for a peer with the given ID
  262. static struct peer_data * find_peer_by_id (peerid_t id);
  263. // device error handler
  264. static void device_error_handler (void *unused);
  265. // DataProtoSource handler for packets from the device
  266. static void device_dpsource_handler (void *unused, const uint8_t *frame, int frame_len);
  267. // assign relays to clients waiting for them
  268. static void assign_relays (void);
  269. // checks if the given address scope is known (i.e. we can connect to an address in it)
  270. static char * address_scope_known (uint8_t *name, int name_len);
  271. // handlers for server messages
  272. static void server_handler_error (void *user);
  273. static void server_handler_ready (void *user, peerid_t param_my_id, uint32_t ext_ip);
  274. static void server_handler_newclient (void *user, peerid_t peer_id, int flags, const uint8_t *cert, int cert_len);
  275. static void server_handler_endclient (void *user, peerid_t peer_id);
  276. static void server_handler_message (void *user, peerid_t peer_id, uint8_t *data, int data_len);
  277. // jobs
  278. static void peer_job_send_seed (struct peer_data *peer);
  279. static void peer_job_init (struct peer_data *peer);
  280. // server flows
  281. static struct server_flow * server_flow_init (void);
  282. static void server_flow_free (struct server_flow *flow);
  283. static void server_flow_die (struct server_flow *flow);
  284. static void server_flow_qflow_handler_busy (struct server_flow *flow);
  285. static void server_flow_connect (struct server_flow *flow, PacketRecvInterface *input);
  286. static void server_flow_disconnect (struct server_flow *flow);
  287. int main (int argc, char *argv[])
  288. {
  289. if (argc <= 0) {
  290. return 1;
  291. }
  292. // open standard streams
  293. open_standard_streams();
  294. // parse command-line arguments
  295. if (!parse_arguments(argc, argv)) {
  296. fprintf(stderr, "Failed to parse arguments\n");
  297. print_help(argv[0]);
  298. goto fail0;
  299. }
  300. // handle --help and --version
  301. if (options.help) {
  302. print_version();
  303. print_help(argv[0]);
  304. return 0;
  305. }
  306. if (options.version) {
  307. print_version();
  308. return 0;
  309. }
  310. // initialize logger
  311. switch (options.logger) {
  312. case LOGGER_STDOUT:
  313. BLog_InitStdout();
  314. break;
  315. #ifndef BADVPN_USE_WINAPI
  316. case LOGGER_SYSLOG:
  317. if (!BLog_InitSyslog(options.logger_syslog_ident, options.logger_syslog_facility)) {
  318. fprintf(stderr, "Failed to initialize syslog logger\n");
  319. goto fail0;
  320. }
  321. break;
  322. #endif
  323. default:
  324. ASSERT(0);
  325. }
  326. // configure logger channels
  327. for (int i = 0; i < BLOG_NUM_CHANNELS; i++) {
  328. if (options.loglevels[i] >= 0) {
  329. BLog_SetChannelLoglevel(i, options.loglevels[i]);
  330. }
  331. else if (options.loglevel >= 0) {
  332. BLog_SetChannelLoglevel(i, options.loglevel);
  333. }
  334. }
  335. BLog(BLOG_NOTICE, "initializing "GLOBAL_PRODUCT_NAME" "PROGRAM_NAME" "GLOBAL_VERSION);
  336. if (options.ssl) {
  337. // init NSPR
  338. PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0);
  339. // register local NSPR file types
  340. if (!DummyPRFileDesc_GlobalInit()) {
  341. BLog(BLOG_ERROR, "DummyPRFileDesc_GlobalInit failed");
  342. goto fail01;
  343. }
  344. if (!BSSLConnection_GlobalInit()) {
  345. BLog(BLOG_ERROR, "BSSLConnection_GlobalInit failed");
  346. goto fail01;
  347. }
  348. // init NSS
  349. if (NSS_Init(options.nssdb) != SECSuccess) {
  350. BLog(BLOG_ERROR, "NSS_Init failed (%d)", (int)PR_GetError());
  351. goto fail01;
  352. }
  353. // set cipher policy
  354. if (NSS_SetDomesticPolicy() != SECSuccess) {
  355. BLog(BLOG_ERROR, "NSS_SetDomesticPolicy failed (%d)", (int)PR_GetError());
  356. goto fail02;
  357. }
  358. // init server cache
  359. if (SSL_ConfigServerSessionIDCache(0, 0, 0, NULL) != SECSuccess) {
  360. BLog(BLOG_ERROR, "SSL_ConfigServerSessionIDCache failed (%d)", (int)PR_GetError());
  361. goto fail02;
  362. }
  363. // open server certificate and private key
  364. if (!open_nss_cert_and_key(options.client_cert_name, &client_cert, &client_key)) {
  365. BLog(BLOG_ERROR, "Cannot open certificate and key");
  366. goto fail03;
  367. }
  368. }
  369. // initialize network
  370. if (!BNetwork_GlobalInit()) {
  371. BLog(BLOG_ERROR, "BNetwork_GlobalInit failed");
  372. goto fail1;
  373. }
  374. // init time
  375. BTime_Init();
  376. // process arguments
  377. if (!process_arguments()) {
  378. BLog(BLOG_ERROR, "Failed to process arguments");
  379. goto fail1;
  380. }
  381. // init reactor
  382. if (!BReactor_Init(&ss)) {
  383. BLog(BLOG_ERROR, "BReactor_Init failed");
  384. goto fail1;
  385. }
  386. // setup signal handler
  387. if (!BSignal_Init(&ss, signal_handler, NULL)) {
  388. BLog(BLOG_ERROR, "BSignal_Init failed");
  389. goto fail2;
  390. }
  391. // init thread work dispatcher
  392. if (!BThreadWorkDispatcher_Init(&twd, &ss, options.threads)) {
  393. BLog(BLOG_ERROR, "BThreadWorkDispatcher_Init failed");
  394. goto fail3;
  395. }
  396. // init BSecurity
  397. if (BThreadWorkDispatcher_UsingThreads(&twd)) {
  398. if (!BSecurity_GlobalInitThreadSafe()) {
  399. BLog(BLOG_ERROR, "BSecurity_GlobalInitThreadSafe failed");
  400. goto fail4;
  401. }
  402. }
  403. // init listeners
  404. int num_listeners = 0;
  405. if (options.transport_mode == TRANSPORT_MODE_TCP) {
  406. while (num_listeners < num_bind_addrs) {
  407. struct bind_addr *addr = &bind_addrs[num_listeners];
  408. if (!PasswordListener_Init(&listeners[num_listeners], &ss, &twd, addr->addr, TCP_MAX_PASSWORD_LISTENER_CLIENTS, options.peer_ssl, ssl_flags(), client_cert, client_key)) {
  409. BLog(BLOG_ERROR, "PasswordListener_Init failed");
  410. goto fail8;
  411. }
  412. num_listeners++;
  413. }
  414. }
  415. // init device
  416. if (!BTap_Init(&device, &ss, options.tapdev, device_error_handler, NULL, 0)) {
  417. BLog(BLOG_ERROR, "BTap_Init failed");
  418. goto fail8;
  419. }
  420. // remember device MTU
  421. device_mtu = BTap_GetMTU(&device);
  422. BLog(BLOG_INFO, "device MTU is %d", device_mtu);
  423. // calculate data MTU
  424. if (device_mtu > INT_MAX - DATAPROTO_MAX_OVERHEAD) {
  425. BLog(BLOG_ERROR, "Device MTU is too large");
  426. goto fail9;
  427. }
  428. data_mtu = DATAPROTO_MAX_OVERHEAD + device_mtu;
  429. // init device input
  430. if (!DataProtoSource_Init(&device_dpsource, BTap_GetOutput(&device), device_dpsource_handler, NULL, &ss)) {
  431. BLog(BLOG_ERROR, "DataProtoSource_Init failed");
  432. goto fail9;
  433. }
  434. // init device output
  435. if (!DPReceiveDevice_Init(&device_output_dprd, device_mtu, (DPReceiveDevice_output_func)BTap_Send, &device, &ss, options.send_buffer_relay_size, PEER_RELAY_FLOW_INACTIVITY_TIME)) {
  436. BLog(BLOG_ERROR, "DPReceiveDevice_Init failed");
  437. goto fail10;
  438. }
  439. // init peers list
  440. LinkedList1_Init(&peers);
  441. num_peers = 0;
  442. // init frame decider
  443. FrameDecider_Init(&frame_decider, options.max_macs, options.max_groups, options.igmp_group_membership_interval, options.igmp_last_member_query_time, &ss);
  444. // init relays list
  445. LinkedList1_Init(&relays);
  446. // init need relay list
  447. LinkedList1_Init(&waiting_relay_peers);
  448. // start connecting to server
  449. if (!ServerConnection_Init(&server, &ss, &twd, server_addr, SC_KEEPALIVE_INTERVAL, SERVER_BUFFER_MIN_PACKETS, options.ssl, ssl_flags(), client_cert, client_key, server_name, NULL,
  450. server_handler_error, server_handler_ready, server_handler_newclient, server_handler_endclient, server_handler_message
  451. )) {
  452. BLog(BLOG_ERROR, "ServerConnection_Init failed");
  453. goto fail11;
  454. }
  455. // set server not ready
  456. server_ready = 0;
  457. // set no dying flow
  458. dying_server_flow = NULL;
  459. // enter event loop
  460. BLog(BLOG_NOTICE, "entering event loop");
  461. BReactor_Exec(&ss);
  462. if (server_ready) {
  463. // allow freeing server queue flows
  464. PacketPassFairQueue_PrepareFree(&server_queue);
  465. // make ServerConnection stop using buffers from peers before they are freed
  466. ServerConnection_ReleaseBuffers(&server);
  467. }
  468. // free peers
  469. LinkedList1Node *node;
  470. while (node = LinkedList1_GetFirst(&peers)) {
  471. struct peer_data *peer = UPPER_OBJECT(node, struct peer_data, list_node);
  472. peer_remove(peer, 1);
  473. }
  474. // free dying server flow
  475. if (dying_server_flow) {
  476. server_flow_free(dying_server_flow);
  477. }
  478. if (server_ready) {
  479. PacketPassFairQueue_Free(&server_queue);
  480. }
  481. ServerConnection_Free(&server);
  482. fail11:
  483. FrameDecider_Free(&frame_decider);
  484. DPReceiveDevice_Free(&device_output_dprd);
  485. fail10:
  486. DataProtoSource_Free(&device_dpsource);
  487. fail9:
  488. BTap_Free(&device);
  489. fail8:
  490. if (options.transport_mode == TRANSPORT_MODE_TCP) {
  491. while (num_listeners-- > 0) {
  492. PasswordListener_Free(&listeners[num_listeners]);
  493. }
  494. }
  495. if (BThreadWorkDispatcher_UsingThreads(&twd)) {
  496. BSecurity_GlobalFreeThreadSafe();
  497. }
  498. fail4:
  499. // NOTE: BThreadWorkDispatcher must be freed before NSPR and stuff
  500. BThreadWorkDispatcher_Free(&twd);
  501. fail3:
  502. BSignal_Finish();
  503. fail2:
  504. BReactor_Free(&ss);
  505. fail1:
  506. if (options.ssl) {
  507. CERT_DestroyCertificate(client_cert);
  508. SECKEY_DestroyPrivateKey(client_key);
  509. fail03:
  510. ASSERT_FORCE(SSL_ShutdownServerSessionIDCache() == SECSuccess)
  511. fail02:
  512. SSL_ClearSessionCache();
  513. ASSERT_FORCE(NSS_Shutdown() == SECSuccess)
  514. fail01:
  515. ASSERT_FORCE(PR_Cleanup() == PR_SUCCESS)
  516. PL_ArenaFinish();
  517. }
  518. BLog(BLOG_NOTICE, "exiting");
  519. BLog_Free();
  520. fail0:
  521. // finish objects
  522. DebugObjectGlobal_Finish();
  523. return 1;
  524. }
  525. void terminate (void)
  526. {
  527. BLog(BLOG_NOTICE, "tearing down");
  528. // exit event loop
  529. BReactor_Quit(&ss, 0);
  530. }
  531. void print_help (const char *name)
  532. {
  533. printf(
  534. "Usage:\n"
  535. " %s\n"
  536. " [--help]\n"
  537. " [--version]\n"
  538. " [--logger <"LOGGERS_STRING">]\n"
  539. #ifndef BADVPN_USE_WINAPI
  540. " (logger=syslog?\n"
  541. " [--syslog-facility <string>]\n"
  542. " [--syslog-ident <string>]\n"
  543. " )\n"
  544. #endif
  545. " [--loglevel <0-5/none/error/warning/notice/info/debug>]\n"
  546. " [--channel-loglevel <channel-name> <0-5/none/error/warning/notice/info/debug>] ...\n"
  547. " [--threads <integer>]\n"
  548. " [--use-threads-for-ssl-handshake]\n"
  549. " [--use-threads-for-ssl-data]\n"
  550. " [--ssl --nssdb <string> --client-cert-name <string>]\n"
  551. " [--server-name <string>]\n"
  552. " --server-addr <addr>\n"
  553. " [--tapdev <name>]\n"
  554. " [--scope <scope_name>] ...\n"
  555. " [\n"
  556. " --bind-addr <addr>\n"
  557. " (transport-mode=udp? --num-ports <num>)\n"
  558. " [--ext-addr <addr / {server_reported}:port> <scope_name>] ...\n"
  559. " ] ...\n"
  560. " --transport-mode <udp/tcp>\n"
  561. " (transport-mode=udp?\n"
  562. " --encryption-mode <blowfish/aes/none>\n"
  563. " --hash-mode <md5/sha1/none>\n"
  564. " [--otp <blowfish/aes> <num> <num-warn>]\n"
  565. " [--fragmentation-latency <milliseconds>]\n"
  566. " )\n"
  567. " (transport-mode=tcp?\n"
  568. " (ssl? [--peer-ssl])\n"
  569. " [--peer-tcp-socket-sndbuf <bytes / 0>]\n"
  570. " )\n"
  571. " [--send-buffer-size <num-packets>]\n"
  572. " [--send-buffer-relay-size <num-packets>]\n"
  573. " [--max-macs <num>]\n"
  574. " [--max-groups <num>]\n"
  575. " [--igmp-group-membership-interval <ms>]\n"
  576. " [--igmp-last-member-query-time <ms>]\n"
  577. " [--allow-peer-talk-without-ssl]\n"
  578. " [--max-peers <number>]\n"
  579. "Address format is a.b.c.d:port (IPv4) or [addr]:port (IPv6).\n",
  580. name
  581. );
  582. }
  583. void print_version (void)
  584. {
  585. printf(GLOBAL_PRODUCT_NAME" "PROGRAM_NAME" "GLOBAL_VERSION"\n"GLOBAL_COPYRIGHT_NOTICE"\n");
  586. }
  587. int parse_arguments (int argc, char *argv[])
  588. {
  589. if (argc <= 0) {
  590. return 0;
  591. }
  592. options.help = 0;
  593. options.version = 0;
  594. options.logger = LOGGER_STDOUT;
  595. #ifndef BADVPN_USE_WINAPI
  596. options.logger_syslog_facility = "daemon";
  597. options.logger_syslog_ident = argv[0];
  598. #endif
  599. options.loglevel = -1;
  600. for (int i = 0; i < BLOG_NUM_CHANNELS; i++) {
  601. options.loglevels[i] = -1;
  602. }
  603. options.threads = 0;
  604. options.use_threads_for_ssl_handshake = 0;
  605. options.use_threads_for_ssl_data = 0;
  606. options.ssl = 0;
  607. options.nssdb = NULL;
  608. options.client_cert_name = NULL;
  609. options.server_name = NULL;
  610. options.server_addr = NULL;
  611. options.tapdev = NULL;
  612. options.num_scopes = 0;
  613. options.num_bind_addrs = 0;
  614. options.transport_mode = -1;
  615. options.encryption_mode = -1;
  616. options.hash_mode = -1;
  617. options.otp_mode = SPPROTO_OTP_MODE_NONE;
  618. options.fragmentation_latency = PEER_DEFAULT_UDP_FRAGMENTATION_LATENCY;
  619. options.peer_ssl = 0;
  620. options.peer_tcp_socket_sndbuf = -1;
  621. options.send_buffer_size = PEER_DEFAULT_SEND_BUFFER_SIZE;
  622. options.send_buffer_relay_size = PEER_DEFAULT_SEND_BUFFER_RELAY_SIZE;
  623. options.max_macs = PEER_DEFAULT_MAX_MACS;
  624. options.max_groups = PEER_DEFAULT_MAX_GROUPS;
  625. options.igmp_group_membership_interval = DEFAULT_IGMP_GROUP_MEMBERSHIP_INTERVAL;
  626. options.igmp_last_member_query_time = DEFAULT_IGMP_LAST_MEMBER_QUERY_TIME;
  627. options.allow_peer_talk_without_ssl = 0;
  628. options.max_peers = DEFAULT_MAX_PEERS;
  629. int have_fragmentation_latency = 0;
  630. int i;
  631. for (i = 1; i < argc; i++) {
  632. char *arg = argv[i];
  633. if (!strcmp(arg, "--help")) {
  634. options.help = 1;
  635. }
  636. else if (!strcmp(arg, "--version")) {
  637. options.version = 1;
  638. }
  639. else if (!strcmp(arg, "--logger")) {
  640. if (1 >= argc - i) {
  641. fprintf(stderr, "%s: requires an argument\n", arg);
  642. return 0;
  643. }
  644. char *arg2 = argv[i + 1];
  645. if (!strcmp(arg2, "stdout")) {
  646. options.logger = LOGGER_STDOUT;
  647. }
  648. #ifndef BADVPN_USE_WINAPI
  649. else if (!strcmp(arg2, "syslog")) {
  650. options.logger = LOGGER_SYSLOG;
  651. }
  652. #endif
  653. else {
  654. fprintf(stderr, "%s: wrong argument\n", arg);
  655. return 0;
  656. }
  657. i++;
  658. }
  659. #ifndef BADVPN_USE_WINAPI
  660. else if (!strcmp(arg, "--syslog-facility")) {
  661. if (1 >= argc - i) {
  662. fprintf(stderr, "%s: requires an argument\n", arg);
  663. return 0;
  664. }
  665. options.logger_syslog_facility = argv[i + 1];
  666. i++;
  667. }
  668. else if (!strcmp(arg, "--syslog-ident")) {
  669. if (1 >= argc - i) {
  670. fprintf(stderr, "%s: requires an argument\n", arg);
  671. return 0;
  672. }
  673. options.logger_syslog_ident = argv[i + 1];
  674. i++;
  675. }
  676. #endif
  677. else if (!strcmp(arg, "--loglevel")) {
  678. if (1 >= argc - i) {
  679. fprintf(stderr, "%s: requires an argument\n", arg);
  680. return 0;
  681. }
  682. if ((options.loglevel = parse_loglevel(argv[i + 1])) < 0) {
  683. fprintf(stderr, "%s: wrong argument\n", arg);
  684. return 0;
  685. }
  686. i++;
  687. }
  688. else if (!strcmp(arg, "--channel-loglevel")) {
  689. if (2 >= argc - i) {
  690. fprintf(stderr, "%s: requires two arguments\n", arg);
  691. return 0;
  692. }
  693. int channel = BLogGlobal_GetChannelByName(argv[i + 1]);
  694. if (channel < 0) {
  695. fprintf(stderr, "%s: wrong channel argument\n", arg);
  696. return 0;
  697. }
  698. int loglevel = parse_loglevel(argv[i + 2]);
  699. if (loglevel < 0) {
  700. fprintf(stderr, "%s: wrong loglevel argument\n", arg);
  701. return 0;
  702. }
  703. options.loglevels[channel] = loglevel;
  704. i += 2;
  705. }
  706. else if (!strcmp(arg, "--threads")) {
  707. if (1 >= argc - i) {
  708. fprintf(stderr, "%s: requires an argument\n", arg);
  709. return 0;
  710. }
  711. options.threads = atoi(argv[i + 1]);
  712. i++;
  713. }
  714. else if (!strcmp(arg, "--use-threads-for-ssl-handshake")) {
  715. options.use_threads_for_ssl_handshake = 1;
  716. }
  717. else if (!strcmp(arg, "--use-threads-for-ssl-data")) {
  718. options.use_threads_for_ssl_data = 1;
  719. }
  720. else if (!strcmp(arg, "--ssl")) {
  721. options.ssl = 1;
  722. }
  723. else if (!strcmp(arg, "--nssdb")) {
  724. if (1 >= argc - i) {
  725. fprintf(stderr, "%s: requires an argument\n", arg);
  726. return 0;
  727. }
  728. options.nssdb = argv[i + 1];
  729. i++;
  730. }
  731. else if (!strcmp(arg, "--client-cert-name")) {
  732. if (1 >= argc - i) {
  733. fprintf(stderr, "%s: requires an argument\n", arg);
  734. return 0;
  735. }
  736. options.client_cert_name = argv[i + 1];
  737. i++;
  738. }
  739. else if (!strcmp(arg, "--server-name")) {
  740. if (1 >= argc - i) {
  741. fprintf(stderr, "%s: requires an argument\n", arg);
  742. return 0;
  743. }
  744. options.server_name = argv[i + 1];
  745. i++;
  746. }
  747. else if (!strcmp(arg, "--server-addr")) {
  748. if (1 >= argc - i) {
  749. fprintf(stderr, "%s: requires an argument\n", arg);
  750. return 0;
  751. }
  752. options.server_addr = argv[i + 1];
  753. i++;
  754. }
  755. else if (!strcmp(arg, "--tapdev")) {
  756. if (1 >= argc - i) {
  757. fprintf(stderr, "%s: requires an argument\n", arg);
  758. return 0;
  759. }
  760. options.tapdev = argv[i + 1];
  761. i++;
  762. }
  763. else if (!strcmp(arg, "--scope")) {
  764. if (1 >= argc - i) {
  765. fprintf(stderr, "%s: requires an argument\n", arg);
  766. return 0;
  767. }
  768. if (options.num_scopes == MAX_SCOPES) {
  769. fprintf(stderr, "%s: too many\n", arg);
  770. return 0;
  771. }
  772. options.scopes[options.num_scopes] = argv[i + 1];
  773. options.num_scopes++;
  774. i++;
  775. }
  776. else if (!strcmp(arg, "--bind-addr")) {
  777. if (1 >= argc - i) {
  778. fprintf(stderr, "%s: requires an argument\n", arg);
  779. return 0;
  780. }
  781. if (options.num_bind_addrs == MAX_BIND_ADDRS) {
  782. fprintf(stderr, "%s: too many\n", arg);
  783. return 0;
  784. }
  785. struct bind_addr_option *addr = &options.bind_addrs[options.num_bind_addrs];
  786. addr->addr = argv[i + 1];
  787. addr->num_ports = -1;
  788. addr->num_ext_addrs = 0;
  789. options.num_bind_addrs++;
  790. i++;
  791. }
  792. else if (!strcmp(arg, "--num-ports")) {
  793. if (1 >= argc - i) {
  794. fprintf(stderr, "%s: requires an argument\n", arg);
  795. return 0;
  796. }
  797. if (options.num_bind_addrs == 0) {
  798. fprintf(stderr, "%s: must folow --bind-addr\n", arg);
  799. return 0;
  800. }
  801. struct bind_addr_option *addr = &options.bind_addrs[options.num_bind_addrs - 1];
  802. if ((addr->num_ports = atoi(argv[i + 1])) < 0) {
  803. fprintf(stderr, "%s: wrong argument\n", arg);
  804. return 0;
  805. }
  806. i++;
  807. }
  808. else if (!strcmp(arg, "--ext-addr")) {
  809. if (2 >= argc - i) {
  810. fprintf(stderr, "%s: requires two arguments\n", arg);
  811. return 0;
  812. }
  813. if (options.num_bind_addrs == 0) {
  814. fprintf(stderr, "%s: must folow --bind-addr\n", arg);
  815. return 0;
  816. }
  817. struct bind_addr_option *addr = &options.bind_addrs[options.num_bind_addrs - 1];
  818. if (addr->num_ext_addrs == MAX_EXT_ADDRS) {
  819. fprintf(stderr, "%s: too many\n", arg);
  820. return 0;
  821. }
  822. struct ext_addr_option *eaddr = &addr->ext_addrs[addr->num_ext_addrs];
  823. eaddr->addr = argv[i + 1];
  824. eaddr->scope = argv[i + 2];
  825. addr->num_ext_addrs++;
  826. i += 2;
  827. }
  828. else if (!strcmp(arg, "--transport-mode")) {
  829. if (1 >= argc - i) {
  830. fprintf(stderr, "%s: requires an argument\n", arg);
  831. return 0;
  832. }
  833. char *arg2 = argv[i + 1];
  834. if (!strcmp(arg2, "udp")) {
  835. options.transport_mode = TRANSPORT_MODE_UDP;
  836. }
  837. else if (!strcmp(arg2, "tcp")) {
  838. options.transport_mode = TRANSPORT_MODE_TCP;
  839. }
  840. else {
  841. fprintf(stderr, "%s: wrong argument\n", arg);
  842. return 0;
  843. }
  844. i++;
  845. }
  846. else if (!strcmp(arg, "--encryption-mode")) {
  847. if (1 >= argc - i) {
  848. fprintf(stderr, "%s: requires an argument\n", arg);
  849. return 0;
  850. }
  851. char *arg2 = argv[i + 1];
  852. if (!strcmp(arg2, "none")) {
  853. options.encryption_mode = SPPROTO_ENCRYPTION_MODE_NONE;
  854. }
  855. else if (!strcmp(arg2, "blowfish")) {
  856. options.encryption_mode = BENCRYPTION_CIPHER_BLOWFISH;
  857. }
  858. else if (!strcmp(arg2, "aes")) {
  859. options.encryption_mode = BENCRYPTION_CIPHER_AES;
  860. }
  861. else {
  862. fprintf(stderr, "%s: wrong argument\n", arg);
  863. return 0;
  864. }
  865. i++;
  866. }
  867. else if (!strcmp(arg, "--hash-mode")) {
  868. if (1 >= argc - i) {
  869. fprintf(stderr, "%s: requires an argument\n", arg);
  870. return 0;
  871. }
  872. char *arg2 = argv[i + 1];
  873. if (!strcmp(arg2, "none")) {
  874. options.hash_mode = SPPROTO_HASH_MODE_NONE;
  875. }
  876. else if (!strcmp(arg2, "md5")) {
  877. options.hash_mode = BHASH_TYPE_MD5;
  878. }
  879. else if (!strcmp(arg2, "sha1")) {
  880. options.hash_mode = BHASH_TYPE_SHA1;
  881. }
  882. else {
  883. fprintf(stderr, "%s: wrong argument\n", arg);
  884. return 0;
  885. }
  886. i++;
  887. }
  888. else if (!strcmp(arg, "--otp")) {
  889. if (3 >= argc - i) {
  890. fprintf(stderr, "%s: requires three arguments\n", arg);
  891. return 0;
  892. }
  893. char *otp_mode = argv[i + 1];
  894. char *otp_num = argv[i + 2];
  895. char *otp_num_warn = argv[i + 3];
  896. if (!strcmp(otp_mode, "blowfish")) {
  897. options.otp_mode = BENCRYPTION_CIPHER_BLOWFISH;
  898. }
  899. else if (!strcmp(otp_mode, "aes")) {
  900. options.otp_mode = BENCRYPTION_CIPHER_AES;
  901. }
  902. else {
  903. fprintf(stderr, "%s: wrong mode\n", arg);
  904. return 0;
  905. }
  906. if ((options.otp_num = atoi(otp_num)) <= 0) {
  907. fprintf(stderr, "%s: wrong num\n", arg);
  908. return 0;
  909. }
  910. options.otp_num_warn = atoi(otp_num_warn);
  911. if (options.otp_num_warn <= 0 || options.otp_num_warn > options.otp_num) {
  912. fprintf(stderr, "%s: wrong num warn\n", arg);
  913. return 0;
  914. }
  915. i += 3;
  916. }
  917. else if (!strcmp(arg, "--fragmentation-latency")) {
  918. if (1 >= argc - i) {
  919. fprintf(stderr, "%s: requires an argument\n", arg);
  920. return 0;
  921. }
  922. options.fragmentation_latency = atoi(argv[i + 1]);
  923. have_fragmentation_latency = 1;
  924. i++;
  925. }
  926. else if (!strcmp(arg, "--peer-ssl")) {
  927. options.peer_ssl = 1;
  928. }
  929. else if (!strcmp(arg, "--peer-tcp-socket-sndbuf")) {
  930. if (1 >= argc - i) {
  931. fprintf(stderr, "%s: requires an argument\n", arg);
  932. return 0;
  933. }
  934. if ((options.peer_tcp_socket_sndbuf = atoi(argv[i + 1])) < 0) {
  935. fprintf(stderr, "%s: wrong argument\n", arg);
  936. return 0;
  937. }
  938. i++;
  939. }
  940. else if (!strcmp(arg, "--send-buffer-size")) {
  941. if (1 >= argc - i) {
  942. fprintf(stderr, "%s: requires an argument\n", arg);
  943. return 0;
  944. }
  945. if ((options.send_buffer_size = atoi(argv[i + 1])) <= 0) {
  946. fprintf(stderr, "%s: wrong argument\n", arg);
  947. return 0;
  948. }
  949. i++;
  950. }
  951. else if (!strcmp(arg, "--send-buffer-relay-size")) {
  952. if (1 >= argc - i) {
  953. fprintf(stderr, "%s: requires an argument\n", arg);
  954. return 0;
  955. }
  956. if ((options.send_buffer_relay_size = atoi(argv[i + 1])) <= 0) {
  957. fprintf(stderr, "%s: wrong argument\n", arg);
  958. return 0;
  959. }
  960. i++;
  961. }
  962. else if (!strcmp(arg, "--max-macs")) {
  963. if (1 >= argc - i) {
  964. fprintf(stderr, "%s: requires an argument\n", arg);
  965. return 0;
  966. }
  967. if ((options.max_macs = atoi(argv[i + 1])) <= 0) {
  968. fprintf(stderr, "%s: wrong argument\n", arg);
  969. return 0;
  970. }
  971. i++;
  972. }
  973. else if (!strcmp(arg, "--max-groups")) {
  974. if (1 >= argc - i) {
  975. fprintf(stderr, "%s: requires an argument\n", arg);
  976. return 0;
  977. }
  978. if ((options.max_groups = atoi(argv[i + 1])) <= 0) {
  979. fprintf(stderr, "%s: wrong argument\n", arg);
  980. return 0;
  981. }
  982. i++;
  983. }
  984. else if (!strcmp(arg, "--igmp-group-membership-interval")) {
  985. if (1 >= argc - i) {
  986. fprintf(stderr, "%s: requires an argument\n", arg);
  987. return 0;
  988. }
  989. if ((options.igmp_group_membership_interval = atoi(argv[i + 1])) <= 0) {
  990. fprintf(stderr, "%s: wrong argument\n", arg);
  991. return 0;
  992. }
  993. i++;
  994. }
  995. else if (!strcmp(arg, "--igmp-last-member-query-time")) {
  996. if (1 >= argc - i) {
  997. fprintf(stderr, "%s: requires an argument\n", arg);
  998. return 0;
  999. }
  1000. if ((options.igmp_last_member_query_time = atoi(argv[i + 1])) <= 0) {
  1001. fprintf(stderr, "%s: wrong argument\n", arg);
  1002. return 0;
  1003. }
  1004. i++;
  1005. }
  1006. else if (!strcmp(arg, "--max-peers")) {
  1007. if (1 >= argc - i) {
  1008. fprintf(stderr, "%s: requires an argument\n", arg);
  1009. return 0;
  1010. }
  1011. if ((options.max_peers = atoi(argv[i + 1])) <= 0) {
  1012. fprintf(stderr, "%s: wrong argument\n", arg);
  1013. return 0;
  1014. }
  1015. i++;
  1016. }
  1017. else if (!strcmp(arg, "--allow-peer-talk-without-ssl")) {
  1018. options.allow_peer_talk_without_ssl = 1;
  1019. }
  1020. else {
  1021. fprintf(stderr, "unknown option: %s\n", arg);
  1022. return 0;
  1023. }
  1024. }
  1025. if (options.help || options.version) {
  1026. return 1;
  1027. }
  1028. if (options.ssl != !!options.nssdb) {
  1029. fprintf(stderr, "False: --ssl <=> --nssdb\n");
  1030. return 0;
  1031. }
  1032. if (options.ssl != !!options.client_cert_name) {
  1033. fprintf(stderr, "False: --ssl <=> --client-cert-name\n");
  1034. return 0;
  1035. }
  1036. if (!options.server_addr) {
  1037. fprintf(stderr, "False: --server-addr\n");
  1038. return 0;
  1039. }
  1040. if (options.transport_mode < 0) {
  1041. fprintf(stderr, "False: --transport-mode\n");
  1042. return 0;
  1043. }
  1044. if ((options.transport_mode == TRANSPORT_MODE_UDP) != (options.encryption_mode >= 0)) {
  1045. fprintf(stderr, "False: UDP <=> --encryption-mode\n");
  1046. return 0;
  1047. }
  1048. if ((options.transport_mode == TRANSPORT_MODE_UDP) != (options.hash_mode >= 0)) {
  1049. fprintf(stderr, "False: UDP <=> --hash-mode\n");
  1050. return 0;
  1051. }
  1052. if (!(!(options.otp_mode != SPPROTO_OTP_MODE_NONE) || (options.transport_mode == TRANSPORT_MODE_UDP))) {
  1053. fprintf(stderr, "False: --otp => UDP\n");
  1054. return 0;
  1055. }
  1056. if (!(!have_fragmentation_latency || (options.transport_mode == TRANSPORT_MODE_UDP))) {
  1057. fprintf(stderr, "False: --fragmentation-latency => UDP\n");
  1058. return 0;
  1059. }
  1060. if (!(!options.peer_ssl || (options.ssl && options.transport_mode == TRANSPORT_MODE_TCP))) {
  1061. fprintf(stderr, "False: --peer-ssl => (--ssl && TCP)\n");
  1062. return 0;
  1063. }
  1064. if (!(!(options.peer_tcp_socket_sndbuf >= 0) || options.transport_mode == TRANSPORT_MODE_TCP)) {
  1065. fprintf(stderr, "False: --peer-tcp-socket-sndbuf => TCP\n");
  1066. return 0;
  1067. }
  1068. return 1;
  1069. }
  1070. int process_arguments (void)
  1071. {
  1072. // resolve server address
  1073. ASSERT(options.server_addr)
  1074. if (!BAddr_Parse(&server_addr, options.server_addr, server_name, sizeof(server_name))) {
  1075. BLog(BLOG_ERROR, "server addr: BAddr_Parse failed");
  1076. return 0;
  1077. }
  1078. // override server name if requested
  1079. if (options.server_name) {
  1080. if (strlen(options.server_name) >= sizeof(server_name)) {
  1081. BLog(BLOG_ERROR, "server name: too long");
  1082. return 0;
  1083. }
  1084. strcpy(server_name, options.server_name);
  1085. }
  1086. // resolve bind addresses and external addresses
  1087. num_bind_addrs = 0;
  1088. for (int i = 0; i < options.num_bind_addrs; i++) {
  1089. struct bind_addr_option *addr = &options.bind_addrs[i];
  1090. struct bind_addr *out = &bind_addrs[num_bind_addrs];
  1091. // read addr
  1092. if (!BAddr_Parse(&out->addr, addr->addr, NULL, 0)) {
  1093. BLog(BLOG_ERROR, "bind addr: BAddr_Parse failed");
  1094. return 0;
  1095. }
  1096. // read num ports
  1097. if (options.transport_mode == TRANSPORT_MODE_UDP) {
  1098. if (addr->num_ports < 0) {
  1099. BLog(BLOG_ERROR, "bind addr: num ports missing");
  1100. return 0;
  1101. }
  1102. out->num_ports = addr->num_ports;
  1103. }
  1104. else if (addr->num_ports >= 0) {
  1105. BLog(BLOG_ERROR, "bind addr: num ports given, but not using UDP");
  1106. return 0;
  1107. }
  1108. // read ext addrs
  1109. out->num_ext_addrs = 0;
  1110. for (int j = 0; j < addr->num_ext_addrs; j++) {
  1111. struct ext_addr_option *eaddr = &addr->ext_addrs[j];
  1112. struct ext_addr *eout = &out->ext_addrs[out->num_ext_addrs];
  1113. // read addr
  1114. if (string_begins_with(eaddr->addr, "{server_reported}:")) {
  1115. char *colon = strstr(eaddr->addr, ":");
  1116. if ((eout->server_reported_port = atoi(colon + 1)) < 0) {
  1117. BLog(BLOG_ERROR, "ext addr: wrong port");
  1118. return 0;
  1119. }
  1120. } else {
  1121. eout->server_reported_port = -1;
  1122. if (!BAddr_Parse(&eout->addr, eaddr->addr, NULL, 0)) {
  1123. BLog(BLOG_ERROR, "ext addr: BAddr_Parse failed");
  1124. return 0;
  1125. }
  1126. if (!addr_supported(eout->addr)) {
  1127. BLog(BLOG_ERROR, "ext addr: addr_supported failed");
  1128. return 0;
  1129. }
  1130. }
  1131. // read scope
  1132. if (strlen(eaddr->scope) >= sizeof(eout->scope)) {
  1133. BLog(BLOG_ERROR, "ext addr: too long");
  1134. return 0;
  1135. }
  1136. strcpy(eout->scope, eaddr->scope);
  1137. out->num_ext_addrs++;
  1138. }
  1139. num_bind_addrs++;
  1140. }
  1141. // initialize SPProto parameters
  1142. if (options.transport_mode == TRANSPORT_MODE_UDP) {
  1143. sp_params.encryption_mode = options.encryption_mode;
  1144. sp_params.hash_mode = options.hash_mode;
  1145. sp_params.otp_mode = options.otp_mode;
  1146. if (options.otp_mode > 0) {
  1147. sp_params.otp_num = options.otp_num;
  1148. }
  1149. }
  1150. return 1;
  1151. }
  1152. int ssl_flags (void)
  1153. {
  1154. int flags = 0;
  1155. if (options.use_threads_for_ssl_handshake) {
  1156. flags |= BSSLCONNECTION_FLAG_THREADWORK_HANDSHAKE;
  1157. }
  1158. if (options.use_threads_for_ssl_data) {
  1159. flags |= BSSLCONNECTION_FLAG_THREADWORK_IO;
  1160. }
  1161. return flags;
  1162. }
  1163. void signal_handler (void *unused)
  1164. {
  1165. BLog(BLOG_NOTICE, "termination requested");
  1166. terminate();
  1167. }
  1168. void peer_add (peerid_t id, int flags, const uint8_t *cert, int cert_len)
  1169. {
  1170. ASSERT(server_ready)
  1171. ASSERT(num_peers < options.max_peers)
  1172. ASSERT(!find_peer_by_id(id))
  1173. ASSERT(id != my_id)
  1174. ASSERT(cert_len >= 0)
  1175. ASSERT(cert_len <= SCID_NEWCLIENT_MAX_CERT_LEN)
  1176. // allocate structure
  1177. struct peer_data *peer = (struct peer_data *)malloc(sizeof(*peer));
  1178. if (!peer) {
  1179. BLog(BLOG_ERROR, "peer %d: failed to allocate memory", (int)id);
  1180. goto fail0;
  1181. }
  1182. // remember id
  1183. peer->id = id;
  1184. // remember flags
  1185. peer->flags = flags;
  1186. // set no common name
  1187. peer->common_name = NULL;
  1188. if (options.ssl) {
  1189. // remember certificate
  1190. memcpy(peer->cert, cert, cert_len);
  1191. peer->cert_len = cert_len;
  1192. // make sure that CERT_DecodeCertFromPackage will interpretet the input as raw DER and not base64,
  1193. // in which case following workaroud wouldn't help
  1194. if (!(cert_len > 0 && (cert[0] & 0x1f) == 0x10)) {
  1195. peer_log(peer, BLOG_ERROR, "certificate does not look like DER");
  1196. goto fail1;
  1197. }
  1198. // copy the certificate and append it a good load of zero bytes,
  1199. // hopefully preventing the crappy CERT_DecodeCertFromPackage from crashing
  1200. // by reading past the of its input
  1201. uint8_t *certbuf = (uint8_t *)malloc(cert_len + 100);
  1202. if (!certbuf) {
  1203. peer_log(peer, BLOG_ERROR, "malloc failed");
  1204. goto fail1;
  1205. }
  1206. memcpy(certbuf, cert, cert_len);
  1207. memset(certbuf + cert_len, 0, 100);
  1208. // decode certificate, so we can extract the common name
  1209. CERTCertificate *nsscert = CERT_DecodeCertFromPackage((char *)certbuf, cert_len);
  1210. if (!nsscert) {
  1211. peer_log(peer, BLOG_ERROR, "CERT_DecodeCertFromPackage failed (%d)", PORT_GetError());
  1212. free(certbuf);
  1213. goto fail1;
  1214. }
  1215. free(certbuf);
  1216. // remember common name
  1217. if (!(peer->common_name = CERT_GetCommonName(&nsscert->subject))) {
  1218. peer_log(peer, BLOG_ERROR, "CERT_GetCommonName failed");
  1219. CERT_DestroyCertificate(nsscert);
  1220. goto fail1;
  1221. }
  1222. CERT_DestroyCertificate(nsscert);
  1223. }
  1224. // init and set init job (must be before initing server flow so we can send)
  1225. BPending_Init(&peer->job_init, BReactor_PendingGroup(&ss), (BPending_handler)peer_job_init, peer);
  1226. BPending_Set(&peer->job_init);
  1227. // init server flow
  1228. if (!(peer->server_flow = server_flow_init())) {
  1229. peer_log(peer, BLOG_ERROR, "server_flow_init failed");
  1230. goto fail2;
  1231. }
  1232. if ((peer->flags & SCID_NEWCLIENT_FLAG_SSL) && !options.ssl) {
  1233. peer_log(peer, BLOG_ERROR, "peer requires talking with SSL, but we're not using SSL!?");
  1234. goto fail3;
  1235. }
  1236. if (options.ssl && !(peer->flags & SCID_NEWCLIENT_FLAG_SSL) && !options.allow_peer_talk_without_ssl) {
  1237. peer_log(peer, BLOG_ERROR, "peer requires talking without SSL, but we don't allow that");
  1238. goto fail3;
  1239. }
  1240. // choose chat SSL mode
  1241. int chat_ssl_mode = PEERCHAT_SSL_NONE;
  1242. if ((peer->flags & SCID_NEWCLIENT_FLAG_SSL)) {
  1243. chat_ssl_mode = (peer_am_master(peer) ? PEERCHAT_SSL_SERVER : PEERCHAT_SSL_CLIENT);
  1244. }
  1245. // init chat
  1246. if (!PeerChat_Init(&peer->chat, peer->id, chat_ssl_mode, ssl_flags(), client_cert, client_key, peer->cert, peer->cert_len, BReactor_PendingGroup(&ss), &twd, peer,
  1247. (BLog_logfunc)peer_logfunc,
  1248. (PeerChat_handler_error)peer_chat_handler_error,
  1249. (PeerChat_handler_message)peer_chat_handler_message
  1250. )) {
  1251. peer_log(peer, BLOG_ERROR, "PeerChat_Init failed");
  1252. goto fail3;
  1253. }
  1254. // set no message
  1255. peer->chat_send_msg_len = -1;
  1256. // connect server flow to chat
  1257. server_flow_connect(peer->server_flow, PeerChat_GetSendOutput(&peer->chat));
  1258. // set have chat
  1259. peer->have_chat = 1;
  1260. // set have no resetpeer
  1261. peer->have_resetpeer = 0;
  1262. // init local flow
  1263. if (!DataProtoFlow_Init(&peer->local_dpflow, &device_dpsource, my_id, peer->id, options.send_buffer_size, -1, NULL, NULL)) {
  1264. peer_log(peer, BLOG_ERROR, "DataProtoFlow_Init failed");
  1265. goto fail4;
  1266. }
  1267. // init frame decider peer
  1268. if (!FrameDeciderPeer_Init(&peer->decider_peer, &frame_decider, peer, (BLog_logfunc)peer_logfunc)) {
  1269. peer_log(peer, BLOG_ERROR, "FrameDeciderPeer_Init failed");
  1270. goto fail5;
  1271. }
  1272. // init receive peer
  1273. DPReceivePeer_Init(&peer->receive_peer, &device_output_dprd, peer->id, &peer->decider_peer, !!(peer->flags & SCID_NEWCLIENT_FLAG_RELAY_CLIENT));
  1274. // have no link
  1275. peer->have_link = 0;
  1276. // have no relaying
  1277. peer->relaying_peer = NULL;
  1278. // not waiting for relay
  1279. peer->waiting_relay = 0;
  1280. // init reset timer
  1281. BTimer_Init(&peer->reset_timer, PEER_RETRY_TIME, (BTimer_handler)peer_reset_timer_handler, peer);
  1282. // is not relay server
  1283. peer->is_relay = 0;
  1284. // init binding
  1285. peer->binding = 0;
  1286. // add to peers list
  1287. LinkedList1_Append(&peers, &peer->list_node);
  1288. num_peers++;
  1289. switch (chat_ssl_mode) {
  1290. case PEERCHAT_SSL_NONE:
  1291. peer_log(peer, BLOG_INFO, "initialized; talking to peer in plaintext mode");
  1292. break;
  1293. case PEERCHAT_SSL_CLIENT:
  1294. peer_log(peer, BLOG_INFO, "initialized; talking to peer in SSL client mode");
  1295. break;
  1296. case PEERCHAT_SSL_SERVER:
  1297. peer_log(peer, BLOG_INFO, "initialized; talking to peer in SSL server mode");
  1298. break;
  1299. }
  1300. return;
  1301. fail5:
  1302. DataProtoFlow_Free(&peer->local_dpflow);
  1303. fail4:
  1304. server_flow_disconnect(peer->server_flow);
  1305. PeerChat_Free(&peer->chat);
  1306. fail3:
  1307. server_flow_free(peer->server_flow);
  1308. fail2:
  1309. BPending_Free(&peer->job_init);
  1310. if (peer->common_name) {
  1311. PORT_Free(peer->common_name);
  1312. }
  1313. fail1:
  1314. free(peer);
  1315. fail0:
  1316. return;
  1317. }
  1318. void peer_remove (struct peer_data *peer, int exiting)
  1319. {
  1320. peer_log(peer, BLOG_INFO, "removing");

Large files files are truncated, but you can click here to view the full file