main.c 33 KB

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