main.c 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287
  1. #include "main.h"
  2. #include "client.h"
  3. #include "tox_bootstrap.h"
  4. #include "log.h"
  5. #ifdef __MACH__
  6. #include "mach.h"
  7. #endif
  8. static struct Tox_Options tox_options;
  9. Tox *tox;
  10. int client_socket = 0;
  11. TOX_CONNECTION connection_status = TOX_CONNECTION_NONE;
  12. /** CONFIGURATION OPTIONS **/
  13. /* Whether we're a client */
  14. int client_mode = 0;
  15. /* Just send a ping and exit */
  16. int ping_mode = 0;
  17. /* Open a local port and forward it */
  18. int client_local_port_mode = 0;
  19. /* Forward stdin/stdout to remote machine - SSH ProxyCommand mode */
  20. int client_pipe_mode = 0;
  21. /* Remote Tox ID in client mode */
  22. char *remote_tox_id = NULL;
  23. /* Directory with config and tox save */
  24. char config_path[500] = "/etc/tuntox/";
  25. /* Ports and hostname for port forwarding */
  26. int remote_port = 0;
  27. char *remote_host = NULL;
  28. int local_port = 0;
  29. /* Whether to daemonize/fork after startup */
  30. int daemonize = 0;
  31. /* Path to the pidfile */
  32. char *pidfile = NULL;
  33. /* Username to which we suid() in daemon mode */
  34. char *daemon_username = NULL;
  35. /* Shared secret used for authentication */
  36. int use_shared_secret = 0;
  37. char shared_secret[TOX_MAX_FRIEND_REQUEST_LENGTH];
  38. /* Only let in a whitelisted client */
  39. int server_whitelist_mode = 0;
  40. allowed_toxid *allowed_toxids = NULL;
  41. int load_saved_toxid_in_client_mode = 0;
  42. fd_set master_server_fds;
  43. /* We keep two hash tables: one indexed by sockfd and another by "connection id" */
  44. tunnel *by_id = NULL;
  45. /* Highest used fd + 1 for select() */
  46. int select_nfds = 4;
  47. /* Generate an unique tunnel ID. To be used in a server. */
  48. uint16_t get_random_tunnel_id()
  49. {
  50. while(1)
  51. {
  52. int key;
  53. uint16_t tunnel_id;
  54. tunnel *tun;
  55. tunnel_id = (uint16_t)rand();
  56. key = tunnel_id;
  57. HASH_FIND_INT(by_id, &key, tun);
  58. if(!tun)
  59. {
  60. return tunnel_id;
  61. }
  62. log_printf(L_WARNING, "[i] Found duplicated tunnel ID %d\n", key);
  63. }
  64. }
  65. /* Comparison function for allowed_toxid objects */
  66. int allowed_toxid_cmp(allowed_toxid *a, allowed_toxid *b)
  67. {
  68. return memcmp(a->toxid, b->toxid, TOX_PUBLIC_KEY_SIZE);
  69. }
  70. void update_select_nfds(int fd)
  71. {
  72. /* TODO maybe replace with a scan every time to make select() more efficient in the long run? */
  73. if(fd + 1 > select_nfds)
  74. {
  75. select_nfds = fd + 1;
  76. }
  77. }
  78. /* Constructor. Returns NULL on failure. */
  79. tunnel *tunnel_create(int sockfd, int connid, uint32_t friendnumber)
  80. {
  81. tunnel *t = NULL;
  82. t = calloc(1, sizeof(tunnel));
  83. if(!t)
  84. {
  85. return NULL;
  86. }
  87. t->sockfd = sockfd;
  88. t->connid = connid;
  89. t->friendnumber = friendnumber;
  90. log_printf(L_INFO, "Created a new tunnel object connid=%d sockfd=%d\n", connid, sockfd);
  91. update_select_nfds(t->sockfd);
  92. HASH_ADD_INT( by_id, connid, t );
  93. return t;
  94. }
  95. void tunnel_delete(tunnel *t)
  96. {
  97. log_printf(L_INFO, "Deleting tunnel #%d\n", t->connid);
  98. if(t->sockfd)
  99. {
  100. close(t->sockfd);
  101. FD_CLR(t->sockfd, &master_server_fds);
  102. }
  103. HASH_DEL( by_id, t );
  104. free(t);
  105. }
  106. /* bootstrap to dht with bootstrap_nodes */
  107. /* From uTox/tox.c */
  108. static void do_bootstrap(Tox *tox)
  109. {
  110. static unsigned int j = 0;
  111. if (j == 0)
  112. j = rand();
  113. int i = 0;
  114. while(i < 4) {
  115. struct bootstrap_node *d = &bootstrap_nodes[j % countof(bootstrap_nodes)];
  116. tox_bootstrap(tox, d->address, d->port, d->key, 0);
  117. tox_add_tcp_relay(tox, d->address, d->port, d->key, 0);
  118. i++;
  119. j++;
  120. }
  121. }
  122. /* Set username to the machine's FQDN */
  123. void set_tox_username(Tox *tox)
  124. {
  125. unsigned char hostname[1024];
  126. struct addrinfo hints, *info, *p;
  127. int gai_result;
  128. TOX_ERR_SET_INFO error;
  129. gethostname(hostname, 1024);
  130. hostname[1023] = '\0';
  131. tox_self_set_name(tox, hostname, strlen(hostname), &error);
  132. if(error != TOX_ERR_SET_INFO_OK)
  133. {
  134. log_printf(L_DEBUG, "tox_self_set_name() failed (%u)", error);
  135. }
  136. }
  137. /* Get sockaddr, IPv4 or IPv6 */
  138. void *get_in_addr(struct sockaddr *sa)
  139. {
  140. if (sa->sa_family == AF_INET)
  141. {
  142. return &(((struct sockaddr_in*)sa)->sin_addr);
  143. }
  144. return &(((struct sockaddr_in6*)sa)->sin6_addr);
  145. }
  146. int get_client_socket(char *hostname, int port)
  147. {
  148. int sockfd, numbytes;
  149. char buf[READ_BUFFER_SIZE];
  150. struct addrinfo hints, *servinfo, *p;
  151. int rv;
  152. char s[INET6_ADDRSTRLEN];
  153. char port_str[6];
  154. snprintf(port_str, 6, "%d", port);
  155. memset(&hints, 0, sizeof hints);
  156. hints.ai_family = AF_INET;
  157. hints.ai_socktype = SOCK_STREAM;
  158. if ((rv = getaddrinfo(hostname, port_str, &hints, &servinfo)) != 0)
  159. {
  160. /* Add a special case for "localhost" when name resolution is broken */
  161. if(!strncmp("localhost", hostname, 256))
  162. {
  163. const char localhostname[] = "127.0.0.1";
  164. if ((rv = getaddrinfo(localhostname, port_str, &hints, &servinfo)) != 0) {
  165. log_printf(L_WARNING, "getaddrinfo failed for 127.0.0.1: %s\n", gai_strerror(rv));
  166. return -1;
  167. }
  168. }
  169. else
  170. {
  171. log_printf(L_WARNING, "getaddrinfo: %s\n", gai_strerror(rv));
  172. return -1;
  173. }
  174. }
  175. // loop through all the results and connect to the first we can
  176. for(p = servinfo; p != NULL; p = p->ai_next)
  177. {
  178. if (p->ai_family != AF_INET && p->ai_family != AF_INET6)
  179. continue;
  180. if ((sockfd = socket(p->ai_family, p->ai_socktype,
  181. p->ai_protocol)) == -1) {
  182. perror("client: socket");
  183. continue;
  184. }
  185. if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
  186. close(sockfd);
  187. perror("client: connect");
  188. continue;
  189. }
  190. break;
  191. }
  192. if (p == NULL) {
  193. log_printf(L_WARNING, "failed to connect to %s:%d\n", hostname, port);
  194. freeaddrinfo(servinfo);
  195. return -1;
  196. }
  197. inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr), s, sizeof s);
  198. log_printf(L_DEBUG, "connecting to %s\n", s);
  199. freeaddrinfo(servinfo); // all done with this structure
  200. log_printf(L_DEBUG, "Connected to %s:%d\n", hostname, port);
  201. return sockfd;
  202. }
  203. /* Proto - our protocol handling */
  204. /*
  205. * send_frame: (almost) zero-copy. Overwrites first PROTOCOL_BUFFER_OFFSET bytes of data
  206. * so actual data should start at position PROTOCOL_BUFFER_OFFSET
  207. */
  208. int send_frame(protocol_frame *frame, uint8_t *data)
  209. {
  210. int rv = -1;
  211. int try = 0;
  212. int i;
  213. TOX_ERR_FRIEND_CUSTOM_PACKET custom_packet_error;
  214. data[0] = PROTOCOL_MAGIC_HIGH;
  215. data[1] = PROTOCOL_MAGIC_LOW;
  216. data[2] = BYTE2(frame->packet_type);
  217. data[3] = BYTE1(frame->packet_type);
  218. data[4] = BYTE2(frame->connid);
  219. data[5] = BYTE1(frame->connid);
  220. data[6] = BYTE2(frame->data_length);
  221. data[7] = BYTE1(frame->data_length);
  222. for(i = 0; i < 65;) /* 1.27 seconds per packet max */
  223. {
  224. int j;
  225. try++;
  226. rv = tox_friend_send_lossless_packet(
  227. tox,
  228. frame->friendnumber,
  229. data,
  230. frame->data_length + PROTOCOL_BUFFER_OFFSET,
  231. &custom_packet_error
  232. );
  233. if(custom_packet_error == TOX_ERR_FRIEND_CUSTOM_PACKET_OK)
  234. {
  235. break;
  236. }
  237. else
  238. {
  239. /* If this branch is ran, most likely we've hit congestion control. */
  240. if(custom_packet_error == TOX_ERR_FRIEND_CUSTOM_PACKET_SENDQ)
  241. {
  242. log_printf(L_DEBUG, "[%d] Failed to send packet to friend %d (Packet queue is full)\n", i, frame->friendnumber);
  243. }
  244. else if(custom_packet_error == TOX_ERR_FRIEND_CUSTOM_PACKET_FRIEND_NOT_CONNECTED)
  245. {
  246. log_printf(L_DEBUG, "[%d] Failed to send packet to friend %d (Friend gone)\n", i, frame->friendnumber);
  247. break;
  248. }
  249. else
  250. {
  251. log_printf(L_DEBUG, "[%d] Failed to send packet to friend %d (err: %u)\n", i, frame->friendnumber, custom_packet_error);
  252. }
  253. }
  254. if(i == 0) i = 2;
  255. else i = i * 2;
  256. for(j = 0; j < i; j++)
  257. {
  258. tox_iterate(tox);
  259. usleep(j * 10000);
  260. }
  261. }
  262. if(i > 0 && rv >= 0)
  263. {
  264. log_printf(L_DEBUG, "Packet succeeded at try %d\n", try);
  265. }
  266. return rv;
  267. }
  268. int send_tunnel_ack_frame(tunnel *tun)
  269. {
  270. protocol_frame frame_st;
  271. protocol_frame *frame;
  272. char data[PROTOCOL_BUFFER_OFFSET];
  273. frame = &frame_st;
  274. memset(frame, 0, sizeof(protocol_frame));
  275. frame->packet_type = PACKET_TYPE_ACKTUNNEL;
  276. frame->connid = tun->connid;
  277. frame->data_length = 0;
  278. frame->friendnumber = tun->friendnumber;
  279. return send_frame(frame, data);
  280. }
  281. int handle_ping_frame(protocol_frame *rcvd_frame)
  282. {
  283. uint8_t data[TOX_MAX_CUSTOM_PACKET_SIZE];
  284. protocol_frame frame_s;
  285. protocol_frame *frame = &frame_s;
  286. frame->data = data + PROTOCOL_BUFFER_OFFSET;
  287. memcpy(frame->data, rcvd_frame->data, rcvd_frame->data_length);
  288. frame->friendnumber = rcvd_frame->friendnumber;
  289. frame->packet_type = PACKET_TYPE_PONG;
  290. frame->data_length = rcvd_frame->data_length;
  291. send_frame(frame, data);
  292. return 0;
  293. }
  294. int handle_request_tunnel_frame(protocol_frame *rcvd_frame)
  295. {
  296. char *hostname = NULL;
  297. tunnel *tun;
  298. int port = -1;
  299. int sockfd = 0;
  300. uint16_t tunnel_id;
  301. if(client_mode)
  302. {
  303. log_printf(L_WARNING, "Got tunnel request frame from friend #%d when in client mode\n", rcvd_frame->friendnumber);
  304. return -1;
  305. }
  306. port = rcvd_frame->connid;
  307. hostname = calloc(1, rcvd_frame->data_length + 1);
  308. if(!hostname)
  309. {
  310. log_printf(L_ERROR, "Could not allocate memory for tunnel request hostname\n");
  311. return -1;
  312. }
  313. strncpy(hostname, rcvd_frame->data, rcvd_frame->data_length);
  314. hostname[rcvd_frame->data_length] = '\0';
  315. log_printf(L_INFO, "Got a request to forward data from %s:%d\n", hostname, port);
  316. tunnel_id = get_random_tunnel_id();
  317. log_printf(L_DEBUG, "Tunnel ID: %d\n", tunnel_id);
  318. sockfd = get_client_socket(hostname, port);
  319. if(sockfd >= 0)
  320. {
  321. tun = tunnel_create(sockfd, tunnel_id, rcvd_frame->friendnumber);
  322. if(tun)
  323. {
  324. FD_SET(sockfd, &master_server_fds);
  325. update_select_nfds(sockfd);
  326. log_printf(L_DEBUG, "Created tunnel, yay!\n");
  327. send_tunnel_ack_frame(tun);
  328. }
  329. else
  330. {
  331. log_printf(L_ERROR, "Couldn't allocate memory for tunnel\n");
  332. close(sockfd);
  333. }
  334. }
  335. else
  336. {
  337. log_printf(L_WARNING, "Could not connect to %s:%d\n", hostname, port);
  338. /* TODO send reject */
  339. }
  340. free(hostname);
  341. return 0;
  342. }
  343. /* Handle a TCP frame received from client */
  344. int handle_client_tcp_frame(protocol_frame *rcvd_frame)
  345. {
  346. tunnel *tun=NULL;
  347. int offset = 0;
  348. int connid = rcvd_frame->connid;
  349. HASH_FIND_INT(by_id, &connid, tun);
  350. if(!tun)
  351. {
  352. log_printf(L_WARNING, "Got TCP frame with unknown tunnel ID %d\n", rcvd_frame->connid);
  353. return -1;
  354. }
  355. if(tun->friendnumber != rcvd_frame->friendnumber)
  356. {
  357. log_printf(L_WARNING, "Friend #%d tried to send packet to a tunnel which belongs to #%d\n", rcvd_frame->friendnumber, tun->friendnumber);
  358. return -1;
  359. }
  360. while(offset < rcvd_frame->data_length)
  361. {
  362. int sent_bytes;
  363. sent_bytes = send(
  364. tun->sockfd,
  365. rcvd_frame->data + offset,
  366. rcvd_frame->data_length - offset,
  367. MSG_NOSIGNAL
  368. );
  369. if(sent_bytes < 0)
  370. {
  371. log_printf(L_WARNING, "Could not write to socket %d: %s\n", tun->sockfd, strerror(errno));
  372. return -1;
  373. }
  374. offset += sent_bytes;
  375. }
  376. return 0;
  377. }
  378. /* Handle close-tunnel frame received from the client */
  379. int handle_client_tcp_fin_frame(protocol_frame *rcvd_frame)
  380. {
  381. tunnel *tun=NULL;
  382. int offset = 0;
  383. int connid = rcvd_frame->connid;
  384. HASH_FIND_INT(by_id, &connid, tun);
  385. if(!tun)
  386. {
  387. log_printf(L_WARNING, "Got TCP FIN frame with unknown tunnel ID %d\n", rcvd_frame->connid);
  388. return -1;
  389. }
  390. if(tun->friendnumber != rcvd_frame->friendnumber)
  391. {
  392. log_printf(L_WARNING, "Friend #%d tried to close tunnel which belongs to #%d\n", rcvd_frame->friendnumber, tun->friendnumber);
  393. return -1;
  394. }
  395. tunnel_delete(tun);
  396. return 0;
  397. }
  398. /* This is a dispatcher for our encapsulated protocol */
  399. int handle_frame(protocol_frame *frame)
  400. {
  401. switch(frame->packet_type)
  402. {
  403. case PACKET_TYPE_PING:
  404. return handle_ping_frame(frame);
  405. break;
  406. case PACKET_TYPE_PONG:
  407. return handle_pong_frame(frame);
  408. break;
  409. case PACKET_TYPE_TCP:
  410. if(client_mode)
  411. {
  412. return handle_server_tcp_frame(frame);
  413. }
  414. else
  415. {
  416. return handle_client_tcp_frame(frame);
  417. }
  418. break;
  419. case PACKET_TYPE_REQUESTTUNNEL:
  420. handle_request_tunnel_frame(frame);
  421. break;
  422. case PACKET_TYPE_ACKTUNNEL:
  423. handle_acktunnel_frame(frame);
  424. break;
  425. case PACKET_TYPE_TCP_FIN:
  426. if(client_mode)
  427. {
  428. return handle_server_tcp_fin_frame(frame);
  429. }
  430. else
  431. {
  432. return handle_client_tcp_fin_frame(frame);
  433. }
  434. break;
  435. default:
  436. log_printf(L_DEBUG, "Got unknown packet type 0x%x from friend %d\n",
  437. frame->packet_type,
  438. frame->friendnumber
  439. );
  440. }
  441. return 0;
  442. }
  443. /*
  444. * This is a callback which gets a packet from Tox core.
  445. * It checks for basic inconsistiencies and allocates the
  446. * protocol_frame structure.
  447. */
  448. void parse_lossless_packet(Tox *tox, uint32_t friendnumber, const uint8_t *data, size_t len, void *tmp)
  449. {
  450. protocol_frame *frame = NULL;
  451. if(len < PROTOCOL_BUFFER_OFFSET)
  452. {
  453. log_printf(L_WARNING, "Received too short data frame - only %d bytes, at least %d expected\n", len, PROTOCOL_BUFFER_OFFSET);
  454. return;
  455. }
  456. if(!data)
  457. {
  458. log_printf(L_ERROR, "Got NULL pointer from toxcore - WTF?\n");
  459. return;
  460. }
  461. if(data[0] != PROTOCOL_MAGIC_HIGH || data[1] != PROTOCOL_MAGIC_LOW)
  462. {
  463. log_printf(L_WARNING, "Received data frame with invalid protocol magic number 0x%x%x\n", data[0], data[1]);
  464. return;
  465. }
  466. frame = calloc(1, sizeof(protocol_frame));
  467. if(!frame)
  468. {
  469. log_printf(L_ERROR, "Could not allocate memory for protocol_frame_t\n");
  470. return;
  471. }
  472. /* TODO check if friendnumber is the same in sender and connid tunnel*/
  473. frame->magic = INT16_AT(data, 0);
  474. frame->packet_type = INT16_AT(data, 2);
  475. frame->connid = INT16_AT(data, 4);
  476. frame->data_length = INT16_AT(data, 6);
  477. frame->data = (uint8_t *)(data + PROTOCOL_BUFFER_OFFSET);
  478. frame->friendnumber = friendnumber;
  479. log_printf(L_DEBUG, "Got protocol frame magic 0x%x type 0x%x from friend %d\n", frame->magic, frame->packet_type, frame->friendnumber);
  480. if(len < frame->data_length + PROTOCOL_BUFFER_OFFSET)
  481. {
  482. log_printf(L_WARNING, "Received frame too small (attempted buffer overflow?): %d bytes, excepted at least %d bytes\n", len, frame->data_length + PROTOCOL_BUFFER_OFFSET);
  483. free(frame);
  484. return;
  485. }
  486. if(frame->data_length > (TOX_MAX_CUSTOM_PACKET_SIZE - PROTOCOL_BUFFER_OFFSET))
  487. {
  488. log_printf(L_WARNING, "Declared data length too big (attempted buffer overflow?): %d bytes, excepted at most %d bytes\n", frame->data_length, (TOX_MAX_CUSTOM_PACKET_SIZE - PROTOCOL_BUFFER_OFFSET));
  489. free(frame);
  490. return;
  491. }
  492. handle_frame(frame);
  493. free(frame);
  494. }
  495. int send_tunnel_request_packet(char *remote_host, int remote_port, int friend_number)
  496. {
  497. int packet_length = 0;
  498. protocol_frame frame_i, *frame;
  499. char *data = NULL;
  500. log_printf(L_INFO, "Sending packet to friend #%d to forward %s:%d\n", friend_number, remote_host, remote_port);
  501. packet_length = PROTOCOL_BUFFER_OFFSET + strlen(remote_host);
  502. frame = &frame_i;
  503. data = calloc(1, packet_length);
  504. if(!data)
  505. {
  506. log_printf(L_ERROR, "Could not allocate memory for tunnel request packet\n");
  507. exit(1);
  508. }
  509. strcpy(data+PROTOCOL_BUFFER_OFFSET, remote_host);
  510. frame->friendnumber = friend_number;
  511. frame->packet_type = PACKET_TYPE_REQUESTTUNNEL;
  512. frame->connid = remote_port;
  513. frame->data_length = strlen(remote_host);
  514. send_frame(frame, data);
  515. free(data);
  516. return 0;
  517. }
  518. /* End proto */
  519. /* Save tox identity to a file */
  520. static void write_save(Tox *tox)
  521. {
  522. void *data;
  523. uint32_t size;
  524. uint8_t path_tmp[512], path_real[512], *p;
  525. FILE *file;
  526. size = tox_get_savedata_size(tox);
  527. data = malloc(size);
  528. tox_get_savedata(tox, data);
  529. strncpy(path_real, config_path, sizeof(config_path));
  530. p = path_real + strlen(path_real);
  531. memcpy(p, "tox_save", sizeof("tox_save"));
  532. unsigned int path_len = (p - path_real) + sizeof("tox_save");
  533. memcpy(path_tmp, path_real, path_len);
  534. memcpy(path_tmp + (path_len - 1), ".tmp", sizeof(".tmp"));
  535. file = fopen((char*)path_tmp, "wb");
  536. if(file) {
  537. fwrite(data, size, 1, file);
  538. fflush(file);
  539. fclose(file);
  540. if (rename((char*)path_tmp, (char*)path_real) != 0) {
  541. log_printf(L_WARNING, "Failed to rename file. %s to %s deleting and trying again\n", path_tmp, path_real);
  542. if(remove((const char *)path_real) < 0) {
  543. log_printf(L_WARNING, "Failed to remove old save file %s\n", path_real);
  544. }
  545. if (rename((char*)path_tmp, (char*)path_real) != 0) {
  546. log_printf(L_WARNING, "Saving Failed\n");
  547. } else {
  548. log_printf(L_DEBUG, "Saved data\n");
  549. }
  550. } else {
  551. log_printf(L_DEBUG, "Saved data\n");
  552. }
  553. }
  554. else
  555. {
  556. log_printf(L_WARNING, "Could not open save file\n");
  557. }
  558. free(data);
  559. }
  560. /* Load tox identity from a file */
  561. static size_t load_save(uint8_t **out_data)
  562. {
  563. void *data;
  564. uint32_t size;
  565. uint8_t path_tmp[512], path_real[512], *p;
  566. FILE *file;
  567. strncpy(path_real, config_path, sizeof(config_path));
  568. p = path_real + strlen(path_real);
  569. memcpy(p, "tox_save", sizeof("tox_save"));
  570. unsigned int path_len = (p - path_real) + sizeof("tox_save");
  571. data = file_raw((char *)path_real, &size);
  572. if(data)
  573. {
  574. *out_data = data;
  575. return size;
  576. }
  577. else
  578. {
  579. log_printf(L_WARNING, "Could not open save file\n");
  580. return 0;
  581. }
  582. }
  583. void accept_friend_request(Tox *tox, const uint8_t *public_key, const uint8_t *message, size_t length, void *userdata)
  584. {
  585. unsigned char tox_printable_id[TOX_ADDRESS_SIZE * 2 + 1];
  586. int32_t friendnumber;
  587. TOX_ERR_FRIEND_ADD friend_add_error;
  588. log_printf(L_DEBUG, "Got friend request\n");
  589. if(use_shared_secret)
  590. {
  591. if(!message)
  592. {
  593. log_printf(L_WARNING, "Friend sent NULL message - not accepting request");
  594. return;
  595. }
  596. if(message[length - 1] != '\0')
  597. {
  598. log_printf(L_WARNING, "Message of size %u is not NULL terminated - not accepting request", length);
  599. return;
  600. }
  601. if(strncmp(message, shared_secret, TOX_MAX_FRIEND_REQUEST_LENGTH-1))
  602. {
  603. log_printf(L_WARNING, "Received shared secret \"%s\" differs from our shared secret - not accepting request", message);
  604. return;
  605. }
  606. }
  607. memset(tox_printable_id, '\0', sizeof(tox_printable_id));
  608. id_to_string(tox_printable_id, public_key);
  609. if(server_whitelist_mode)
  610. {
  611. allowed_toxid etmp, *found = NULL;
  612. memcpy(etmp.toxid, public_key, TOX_PUBLIC_KEY_SIZE);
  613. LL_SEARCH(allowed_toxids, found, &etmp, allowed_toxid_cmp);
  614. if(!found)
  615. {
  616. log_printf(L_WARNING, "Rejected friend request from non-whitelisted friend %s", tox_printable_id);
  617. return;
  618. }
  619. log_printf(L_DEBUG, "Friend %s passed whitelist check", tox_printable_id);
  620. }
  621. friendnumber = tox_friend_add_norequest(tox, public_key, &friend_add_error);
  622. if(friend_add_error != TOX_ERR_FRIEND_ADD_OK)
  623. {
  624. log_printf(L_WARNING, "Could not add friend: err %u", friend_add_error);
  625. return;
  626. }
  627. log_printf(L_INFO, "Accepted friend request from %s as %d\n", tox_printable_id, friendnumber);
  628. }
  629. /* Callback for tox_callback_self_connection_status() */
  630. void handle_connection_status_change(Tox *tox, TOX_CONNECTION p_connection_status, void *user_data)
  631. {
  632. const char *status = NULL;
  633. connection_status = p_connection_status;
  634. status = readable_connection_status(connection_status);
  635. log_printf(L_INFO, "Connection status changed: %s", status);
  636. }
  637. void cleanup()
  638. {
  639. log_printf(L_DEBUG, "kthxbye\n");
  640. fflush(stdout);
  641. tox_kill(tox);
  642. if(client_socket)
  643. {
  644. close(client_socket);
  645. }
  646. log_close();
  647. }
  648. int do_server_loop()
  649. {
  650. struct timeval tv, tv_start, tv_end;
  651. unsigned long long ms_start, ms_end;
  652. fd_set fds;
  653. unsigned char tox_packet_buf[PROTOCOL_MAX_PACKET_SIZE];
  654. tunnel *tun = NULL;
  655. tunnel *tmp = NULL;
  656. TOX_CONNECTION connected = 0;
  657. tox_callback_friend_lossless_packet(tox, parse_lossless_packet, NULL);
  658. tv.tv_sec = 0;
  659. tv.tv_usec = 20000;
  660. FD_ZERO(&master_server_fds);
  661. while(1)
  662. {
  663. TOX_CONNECTION tmp_isconnected = 0;
  664. uint32_t tox_do_interval_ms;
  665. int select_rv = 0;
  666. /* Let tox do its stuff */
  667. tox_iterate(tox);
  668. /* Get the desired sleep time, used in select() later */
  669. tox_do_interval_ms = tox_iteration_interval(tox);
  670. tv.tv_usec = (tox_do_interval_ms % 1000) * 1000;
  671. tv.tv_sec = tox_do_interval_ms / 1000;
  672. log_printf(L_DEBUG2, "Iteration interval: %dms\n", tox_do_interval_ms);
  673. gettimeofday(&tv_start, NULL);
  674. /* Check change in connection state */
  675. tmp_isconnected = connection_status;
  676. if(tmp_isconnected != connected)
  677. {
  678. connected = tmp_isconnected;
  679. if(connected)
  680. {
  681. log_printf(L_DEBUG, "Connected to Tox network\n");
  682. }
  683. else
  684. {
  685. log_printf(L_DEBUG, "Disconnected from Tox network\n");
  686. }
  687. }
  688. fds = master_server_fds;
  689. /* Poll for data from our client connection */
  690. select_rv = select(select_nfds, &fds, NULL, NULL, &tv);
  691. if(select_rv == -1 || select_rv == 0)
  692. {
  693. if(select_rv == -1)
  694. {
  695. log_printf(L_DEBUG, "Reading from local socket failed: code=%d (%s)\n",
  696. errno, strerror(errno));
  697. }
  698. else
  699. {
  700. log_printf(L_DEBUG2, "Nothing to read...");
  701. }
  702. }
  703. else
  704. {
  705. HASH_ITER(hh, by_id, tun, tmp)
  706. {
  707. if(FD_ISSET(tun->sockfd, &fds))
  708. {
  709. int nbytes = recv(tun->sockfd,
  710. tox_packet_buf+PROTOCOL_BUFFER_OFFSET,
  711. READ_BUFFER_SIZE, 0);
  712. /* Check if connection closed */
  713. if(nbytes <= 0)
  714. {
  715. char data[PROTOCOL_BUFFER_OFFSET];
  716. protocol_frame frame_st, *frame;
  717. if(nbytes == 0)
  718. {
  719. log_printf(L_WARNING, "conn closed!\n");
  720. }
  721. else
  722. {
  723. log_printf(L_WARNING, "conn closed, code=%d (%s)\n",
  724. errno, strerror(errno));
  725. }
  726. frame = &frame_st;
  727. memset(frame, 0, sizeof(protocol_frame));
  728. frame->friendnumber = tun->friendnumber;
  729. frame->packet_type = PACKET_TYPE_TCP_FIN;
  730. frame->connid = tun->connid;
  731. frame->data_length = 0;
  732. send_frame(frame, data);
  733. tunnel_delete(tun);
  734. continue;
  735. }
  736. else
  737. {
  738. protocol_frame frame_st, *frame;
  739. frame = &frame_st;
  740. memset(frame, 0, sizeof(protocol_frame));
  741. frame->friendnumber = tun->friendnumber;
  742. frame->packet_type = PACKET_TYPE_TCP;
  743. frame->connid = tun->connid;
  744. frame->data_length = nbytes;
  745. send_frame(frame, tox_packet_buf);
  746. }
  747. }
  748. }
  749. }
  750. gettimeofday(&tv_end, NULL);
  751. ms_start = 1000 * tv_start.tv_sec + tv_start.tv_usec/1000;
  752. ms_end = 1000 * tv_end.tv_sec + tv_end.tv_usec/1000;
  753. if(ms_end - ms_start < tox_do_interval_ms)
  754. {
  755. /*log_printf(L_DEBUG, "Sleeping for %d ms extra to prevent high CPU usage\n", (tox_do_interval_ms - (ms_end - ms_start)));*/
  756. usleep((tox_do_interval_ms - (ms_end - ms_start)) * 1000);
  757. }
  758. }
  759. }
  760. /* Signal handler used when daemonizing */
  761. static void child_handler(int signum)
  762. {
  763. switch(signum) {
  764. case SIGALRM: exit(1); break;
  765. case SIGUSR1: exit(0); break;
  766. case SIGCHLD: exit(1); break;
  767. }
  768. }
  769. /*
  770. * Daemonize the process if -D is set
  771. * Optionally drop privileges and create a lock file
  772. */
  773. void do_daemonize()
  774. {
  775. pid_t pid, sid, parent;
  776. FILE *pidf = NULL;
  777. /* already a daemon */
  778. if (getppid() == 1)
  779. {
  780. return;
  781. }
  782. /* Drop user if there is one, and we were run as root */
  783. if (daemon_username && (getuid() == 0 || geteuid() == 0))
  784. {
  785. struct passwd *pw = getpwnam(daemon_username);
  786. if(pw)
  787. {
  788. log_printf(L_DEBUG, "Setuid to user %s", daemon_username);
  789. setuid(pw->pw_uid);
  790. }
  791. else
  792. {
  793. char *tmp;
  794. int uid = 0;
  795. uid = strtol(daemon_username, &tmp, 10);
  796. if(uid)
  797. {
  798. setuid(uid);
  799. log_printf(L_DEBUG, "Setuid to user ID %ld", (long)uid);
  800. }
  801. else
  802. {
  803. log_printf(L_DEBUG, "Could not setuid to user %s - no pwnam (static build?) or invalid numeric UID", daemon_username);
  804. }
  805. }
  806. }
  807. /* Trap signals that we expect to recieve */
  808. signal(SIGCHLD,child_handler);
  809. signal(SIGUSR1,child_handler);
  810. signal(SIGALRM,child_handler);
  811. /* Fork off the parent process */
  812. pid = fork();
  813. if (pid < 0)
  814. {
  815. log_printf(L_ERROR, "Unable to fork daemon, code=%d (%s)",
  816. errno, strerror(errno));
  817. exit(1);
  818. }
  819. /* If we got a good PID, then we can exit the parent process. */
  820. if (pid > 0)
  821. {
  822. /* Wait for confirmation from the child via SIGTERM or SIGCHLD, or
  823. for two seconds to elapse (SIGALRM). pause() should not return. */
  824. alarm(2);
  825. pause();
  826. exit(1);
  827. }
  828. /* At this point we are executing as the child process */
  829. parent = getppid();
  830. /* Cancel certain signals */
  831. signal(SIGCHLD,SIG_DFL); /* A child process dies */
  832. signal(SIGTSTP,SIG_IGN); /* Various TTY signals */
  833. signal(SIGTTOU,SIG_IGN);
  834. signal(SIGTTIN,SIG_IGN);
  835. signal(SIGHUP, SIG_IGN); /* Ignore hangup signal */
  836. signal(SIGTERM,SIG_DFL); /* Die on SIGTERM */
  837. /* Change the file mode mask */
  838. umask(S_IWGRP | S_IWOTH);
  839. /* Reinitialize the syslog connection */
  840. log_init();
  841. /* Create a new SID for the child process */
  842. sid = setsid();
  843. if (sid < 0)
  844. {
  845. log_printf(L_ERROR, "unable to create a new session, code %d (%s)",
  846. errno, strerror(errno));
  847. exit(1);
  848. }
  849. /* Change the current working directory. This prevents the current
  850. directory from being locked; hence not being able to remove it. */
  851. if ((chdir("/")) < 0)
  852. {
  853. log_printf(L_ERROR, "Unable to change directory to %s, code %d (%s)",
  854. "/", errno, strerror(errno) );
  855. exit(1);
  856. }
  857. /* Redirect standard files to /dev/null */
  858. freopen( "/dev/null", "r", stdin);
  859. freopen( "/dev/null", "w", stdout);
  860. freopen( "/dev/null", "w", stderr);
  861. /* Create the pid file as the new user */
  862. if (pidfile && pidfile[0])
  863. {
  864. pidf = fopen(pidfile, "w");
  865. if (!pidf)
  866. {
  867. log_printf(L_ERROR, "Unable to create PID file %s, code=%d (%s)",
  868. pidfile, errno, strerror(errno));
  869. exit(1);
  870. }
  871. fprintf(pidf, "%ld", (long)getpid());
  872. fclose(pidf);
  873. }
  874. /* Tell the parent process that we are A-okay */
  875. kill( parent, SIGUSR1 );
  876. }
  877. void help()
  878. {
  879. fprintf(stderr, "tuntox - Forward ports over the Tox protocol\n");
  880. fprintf(stderr, "USAGE:\n\n");
  881. fprintf(stderr, "-i <toxid> - remote point Tox ID\n");
  882. fprintf(stderr, "-L <localport>:<remotehostname>:<remoteport> - forward <remotehostname>:<remoteport> to 127.0.0.1:<localport>\n");
  883. fprintf(stderr, "-P <remotehostname>:<remoteport> - forward <remotehostname>:<remoteport> to stdin/stdout (SSH ProxyCommand mode)\n");
  884. fprintf(stderr, "-p - ping the server from -i and exit\n");
  885. fprintf(stderr, "-C <dir> - save private key in <dir> instead of /etc/tuntox in server mode\n");
  886. fprintf(stderr, "-s <secret> - shared secret used for connection authentication (max %u characters)\n", TOX_MAX_FRIEND_REQUEST_LENGTH-1);
  887. fprintf(stderr, "-d - debug mode\n");
  888. fprintf(stderr, "-q - quiet mode\n");
  889. fprintf(stderr, "-S - send output to syslog instead of stderr\n");
  890. fprintf(stderr, "-D - daemonize (fork) and exit (implies -S)\n");
  891. fprintf(stderr, "-F <path> - create a PID file named <path>\n");
  892. fprintf(stderr, "-U <username|userid> - drop privileges to <username> before forking. Use numeric <userid> in static builds.\n");
  893. fprintf(stderr, "-h - this help message\n");
  894. }
  895. int main(int argc, char *argv[])
  896. {
  897. unsigned char tox_id[TOX_ADDRESS_SIZE];
  898. unsigned char tox_printable_id[TOX_ADDRESS_SIZE * 2 + 1];
  899. TOX_ERR_NEW tox_new_err;
  900. int oc;
  901. size_t save_size = 0;
  902. uint8_t *save_data = NULL;
  903. allowed_toxid *allowed_toxid_obj = NULL;
  904. log_init();
  905. while ((oc = getopt(argc, argv, "L:pi:C:s:P:dqhSF:DU:")) != -1)
  906. {
  907. switch(oc)
  908. {
  909. case 'L':
  910. /* Local port forwarding */
  911. client_mode = 1;
  912. client_local_port_mode = 1;
  913. if(parse_local_port_forward(optarg, &local_port, &remote_host, &remote_port) < 0)
  914. {
  915. log_printf(L_ERROR, "Invalid value for -L option - use something like -L 22:127.0.0.1:22\n");
  916. exit(1);
  917. }
  918. if(min_log_level == L_UNSET)
  919. {
  920. min_log_level = L_INFO;
  921. }
  922. log_printf(L_DEBUG, "Forwarding remote port %d to local port %d\n", remote_port, local_port);
  923. break;
  924. case 'P':
  925. /* Pipe forwarding */
  926. client_mode = 1;
  927. client_pipe_mode = 1;
  928. if(parse_pipe_port_forward(optarg, &remote_host, &remote_port) < 0)
  929. {
  930. log_printf(L_ERROR, "Invalid value for -P option - use something like -P 127.0.0.1:22\n");
  931. exit(1);
  932. }
  933. if(min_log_level == L_UNSET)
  934. {
  935. min_log_level = L_ERROR;
  936. }
  937. log_printf(L_INFO, "Forwarding remote port %d to stdin/out\n", remote_port);
  938. break;
  939. case 'p':
  940. /* Ping */
  941. client_mode = 1;
  942. ping_mode = 1;
  943. if(min_log_level == L_UNSET)
  944. {
  945. min_log_level = L_INFO;
  946. }
  947. break;
  948. case 'i':
  949. /* Tox ID */
  950. server_whitelist_mode = 1;
  951. log_printf(L_DEBUG, "Server whitelist mode enabled");
  952. allowed_toxid_obj = (allowed_toxid *)calloc(sizeof(allowed_toxid), 1);
  953. if(!allowed_toxid_obj)
  954. {
  955. log_printf(L_ERROR, "Could not allocate memory for allowed_toxid");
  956. exit(1);
  957. }
  958. remote_tox_id = optarg;
  959. if(!string_to_id(allowed_toxid_obj->toxid, optarg))
  960. {
  961. log_printf(L_ERROR, "Invalid Tox ID");
  962. exit(1);
  963. }
  964. LL_APPEND(allowed_toxids, allowed_toxid_obj);
  965. break;
  966. case 'C':
  967. /* Config directory */
  968. strncpy(config_path, optarg, sizeof(config_path) - 1);
  969. if(optarg[strlen(optarg) - 1] != '/')
  970. {
  971. int optarg_len = strlen(optarg);
  972. config_path[optarg_len] = '/';
  973. config_path[optarg_len + 1] = '\0';
  974. }
  975. load_saved_toxid_in_client_mode = 1;
  976. break;
  977. case 's':
  978. /* Shared secret */
  979. use_shared_secret = 1;
  980. memset(shared_secret, 0, TOX_MAX_FRIEND_REQUEST_LENGTH);
  981. strncpy(shared_secret, optarg, TOX_MAX_FRIEND_REQUEST_LENGTH-1);
  982. break;
  983. case 'd':
  984. min_log_level = L_DEBUG;
  985. break;
  986. case 'q':
  987. min_log_level = L_ERROR;
  988. break;
  989. case 'S':
  990. use_syslog = 1;
  991. break;
  992. case 'D':
  993. daemonize = 1;
  994. use_syslog = 1;
  995. break;
  996. case 'F':
  997. pidfile = optarg;
  998. break;
  999. case 'U':
  1000. daemon_username = optarg;
  1001. break;
  1002. case '?':
  1003. case 'h':
  1004. default:
  1005. print_version();
  1006. help();
  1007. exit(1);
  1008. }
  1009. }
  1010. if(!client_mode && min_log_level == L_UNSET)
  1011. {
  1012. min_log_level = L_INFO;
  1013. }
  1014. if(!client_mode && server_whitelist_mode)
  1015. {
  1016. log_printf(L_INFO, "Server in ToxID whitelisting mode - only clients listed with -i can connect");
  1017. }
  1018. if(daemonize)
  1019. {
  1020. do_daemonize();
  1021. }
  1022. atexit(cleanup);
  1023. print_version();
  1024. /* Bootstrap tox */
  1025. tox_options_default(&tox_options);
  1026. if((!client_mode) || load_saved_toxid_in_client_mode)
  1027. {
  1028. uint8_t *save_data = NULL;
  1029. save_size = load_save(&save_data);
  1030. if(save_data && save_size)
  1031. {
  1032. tox_options.savedata_type = TOX_SAVEDATA_TYPE_TOX_SAVE;
  1033. tox_options.savedata_data = save_data;
  1034. tox_options.savedata_length = save_size;
  1035. }
  1036. }
  1037. tox = tox_new(&tox_options, &tox_new_err);
  1038. if(tox == NULL)
  1039. {
  1040. log_printf(L_DEBUG, "tox_new() failed (%u) - trying without proxy\n", tox_new_err);
  1041. if((tox_options.proxy_type != TOX_PROXY_TYPE_NONE) || (tox_options.proxy_type = TOX_PROXY_TYPE_NONE, (tox = tox_new(&tox_options, &tox_new_err)) == NULL))
  1042. {
  1043. log_printf(L_DEBUG, "tox_new() failed (%u) - trying without IPv6\n", tox_new_err);
  1044. if(!tox_options.ipv6_enabled || (tox_options.ipv6_enabled = 0, (tox = tox_new(&tox_options, &tox_new_err)) == NULL))
  1045. {
  1046. log_printf(L_DEBUG, "tox_new() failed (%u) - trying with Tor\n", tox_new_err);
  1047. if((tox_options.proxy_type = TOX_PROXY_TYPE_SOCKS5, tox_options.proxy_host="127.0.0.1", tox_options.proxy_port=9050, (tox = tox_new(&tox_options, &tox_new_err)) == NULL))
  1048. {
  1049. log_printf(L_ERROR, "tox_new() failed (%u) - exiting\n", tox_new_err);
  1050. exit(1);
  1051. }
  1052. }
  1053. }
  1054. }
  1055. if(save_size && save_data)
  1056. {
  1057. free(save_data);
  1058. }
  1059. set_tox_username(tox);
  1060. tox_callback_self_connection_status(tox, handle_connection_status_change, NULL);
  1061. do_bootstrap(tox);
  1062. if(client_mode)
  1063. {
  1064. tox_self_get_address(tox, tox_id);
  1065. id_to_string(tox_printable_id, tox_id);
  1066. tox_printable_id[TOX_ADDRESS_SIZE * 2] = '\0';
  1067. log_printf(L_DEBUG, "Generated Tox ID: %s\n", tox_printable_id);
  1068. if(!remote_tox_id)
  1069. {
  1070. log_printf(L_ERROR, "Tox id is required in client mode. Use -i 58435984ABCDEF475...\n");
  1071. exit(1);
  1072. }
  1073. do_client_loop(remote_tox_id);
  1074. }
  1075. else
  1076. {
  1077. write_save(tox);
  1078. if(!use_shared_secret)
  1079. {
  1080. log_printf(L_WARNING, "Shared secret authentication is not used - skilled attackers may connect to your tuntox server");
  1081. }
  1082. tox_self_get_address(tox, tox_id);
  1083. memset(tox_printable_id, '\0', sizeof(tox_printable_id));
  1084. id_to_string(tox_printable_id, tox_id);
  1085. tox_printable_id[TOX_ADDRESS_SIZE * 2] = '\0';
  1086. log_printf(L_INFO, "Using Tox ID: %s\n", tox_printable_id);
  1087. tox_callback_friend_request(tox, accept_friend_request, NULL);
  1088. do_server_loop();
  1089. }
  1090. return 0;
  1091. }