client.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  1. #include <time.h>
  2. /* MacOS related */
  3. #ifdef __MACH__
  4. #include "mach.h"
  5. #endif
  6. #include "log.h"
  7. #include "main.h"
  8. #include "client.h"
  9. /* The state machine */
  10. int state = CLIENT_STATE_INITIAL;
  11. /* Used in ping mode */
  12. struct timespec ping_sent_time;
  13. /* Client mode tunnel */
  14. tunnel client_tunnel;
  15. /* Sock representing the local port - call accept() on it */
  16. int bind_sockfd;
  17. fd_set client_master_fdset;
  18. int handle_pong_frame()
  19. {
  20. struct timespec pong_rcvd_time;
  21. double secs1, secs2;
  22. clock_gettime(CLOCK_MONOTONIC, &pong_rcvd_time);
  23. secs1 = (1.0 * ping_sent_time.tv_sec) + (1e-9 * ping_sent_time.tv_nsec);
  24. secs2 = (1.0 * pong_rcvd_time.tv_sec) + (1e-9 * pong_rcvd_time.tv_nsec);
  25. log_printf(L_INFO, "GOT PONG! Time = %.3fs\n", secs2-secs1);
  26. if(ping_mode)
  27. {
  28. state = CLIENT_STATE_SEND_PING;
  29. }
  30. return 0;
  31. }
  32. int local_bind()
  33. {
  34. struct addrinfo hints, *res;
  35. char port[6];
  36. int yes = 1;
  37. int flags;
  38. int gai_status;
  39. int setsockopt_status;
  40. snprintf(port, 6, "%d", local_port);
  41. memset(&hints, 0, sizeof hints);
  42. hints.ai_family = AF_UNSPEC; // use IPv4 or IPv6, whichever
  43. hints.ai_socktype = SOCK_STREAM;
  44. hints.ai_flags = AI_PASSIVE; // fill in my IP for me
  45. gai_status = getaddrinfo(NULL, port, &hints, &res);
  46. if(gai_status != 0)
  47. {
  48. log_printf(L_ERROR, "getaddrinfo: %s\n", gai_strerror(gai_status));
  49. exit(1);
  50. }
  51. bind_sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
  52. if(bind_sockfd < 0)
  53. {
  54. log_printf(L_ERROR, "Could not create a socket for local listening: %s\n", strerror(errno));
  55. freeaddrinfo(res);
  56. exit(1);
  57. }
  58. setsockopt_status = setsockopt(bind_sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));
  59. if(setsockopt_status < 0)
  60. {
  61. log_printf(L_ERROR, "Could not set socket options: %s\n",
  62. strerror(errno));
  63. freeaddrinfo(res);
  64. exit(1);
  65. }
  66. /* Set O_NONBLOCK to make accept() non-blocking */
  67. if (-1 == (flags = fcntl(bind_sockfd, F_GETFL, 0)))
  68. {
  69. flags = 0;
  70. }
  71. if(fcntl(bind_sockfd, F_SETFL, flags | O_NONBLOCK) < 0)
  72. {
  73. log_printf(L_ERROR, "Could not make the socket non-blocking: %s\n", strerror(errno));
  74. freeaddrinfo(res);
  75. exit(1);
  76. }
  77. if(bind(bind_sockfd, res->ai_addr, res->ai_addrlen) < 0)
  78. {
  79. log_printf(L_ERROR, "Bind to port %d failed: %s\n", local_port, strerror(errno));
  80. freeaddrinfo(res);
  81. close(bind_sockfd);
  82. exit(1);
  83. }
  84. freeaddrinfo(res);
  85. if(listen(bind_sockfd, 1) < 0)
  86. {
  87. log_printf(L_ERROR, "Listening on port %d failed: %s\n", local_port, strerror(errno));
  88. close(bind_sockfd);
  89. exit(1);
  90. }
  91. log_printf(L_DEBUG, "Bound to local port %d\n", local_port);
  92. return 0;
  93. }
  94. /* Bind the client.sockfd to a tunnel */
  95. int handle_acktunnel_frame(protocol_frame *rcvd_frame)
  96. {
  97. tunnel *tun;
  98. if(!client_mode)
  99. {
  100. log_printf(L_WARNING, "Got ACK tunnel frame when not in client mode!?\n");
  101. return -1;
  102. }
  103. tun = tunnel_create(
  104. client_tunnel.sockfd,
  105. rcvd_frame->connid,
  106. rcvd_frame->friendnumber
  107. );
  108. /* Mark that we can accept() another connection */
  109. client_tunnel.sockfd = -1;
  110. // printf("New tunnel ID: %d\n", tun->connid);
  111. if(client_local_port_mode || client_pipe_mode)
  112. {
  113. update_select_nfds(tun->sockfd);
  114. FD_SET(tun->sockfd, &client_master_fdset);
  115. if(client_local_port_mode)
  116. {
  117. log_printf(L_INFO, "Accepted a new connection on port %d\n", local_port);
  118. }
  119. }
  120. else
  121. {
  122. log_printf(L_ERROR, "This tunnel mode is not supported yet\n");
  123. exit(1);
  124. }
  125. return 0;
  126. }
  127. /* Handle a TCP frame received from server */
  128. int handle_server_tcp_frame(protocol_frame *rcvd_frame)
  129. {
  130. int offset = 0;
  131. tunnel *tun = NULL;
  132. int tun_id = rcvd_frame->connid;
  133. HASH_FIND_INT(by_id, &tun_id, tun);
  134. if(!tun)
  135. {
  136. log_printf(L_WARNING, "Got TCP frame with unknown tunnel ID %d\n", rcvd_frame->connid);
  137. return -1;
  138. }
  139. while(offset < rcvd_frame->data_length)
  140. {
  141. int sent_bytes;
  142. if(client_pipe_mode)
  143. {
  144. sent_bytes = write(
  145. 1, /* STDOUT */
  146. rcvd_frame->data + offset,
  147. rcvd_frame->data_length - offset
  148. );
  149. }
  150. else
  151. {
  152. sent_bytes = send(
  153. tun->sockfd,
  154. rcvd_frame->data + offset,
  155. rcvd_frame->data_length - offset,
  156. MSG_NOSIGNAL
  157. );
  158. }
  159. if(sent_bytes < 0)
  160. {
  161. uint8_t data[PROTOCOL_BUFFER_OFFSET];
  162. protocol_frame frame_st, *frame;
  163. log_printf(L_INFO, "Could not write to socket: %s\n", strerror(errno));
  164. frame = &frame_st;
  165. memset(frame, 0, sizeof(protocol_frame));
  166. frame->friendnumber = tun->friendnumber;
  167. frame->packet_type = PACKET_TYPE_TCP_FIN;
  168. frame->connid = tun->connid;
  169. frame->data_length = 0;
  170. send_frame(frame, data);
  171. if(tun->sockfd)
  172. {
  173. FD_CLR(tun->sockfd, &client_master_fdset);
  174. }
  175. tunnel_delete(tun);
  176. return -1;
  177. }
  178. offset += sent_bytes;
  179. }
  180. // printf("Got %d bytes from server - wrote to fd %d\n", rcvd_frame->data_length, tun->sockfd);
  181. return 0;
  182. }
  183. /* Delete tunnel and clear client-side fdset */
  184. void client_close_tunnel(tunnel *tun)
  185. {
  186. if(tun->sockfd)
  187. {
  188. FD_CLR(tun->sockfd, &client_master_fdset);
  189. }
  190. tunnel_delete(tun);
  191. }
  192. /* Handle close-tunnel frame recived from the server */
  193. int handle_server_tcp_fin_frame(protocol_frame *rcvd_frame)
  194. {
  195. tunnel *tun=NULL;
  196. int connid = rcvd_frame->connid;
  197. HASH_FIND_INT(by_id, &connid, tun);
  198. if(!tun)
  199. {
  200. log_printf(L_WARNING, "Got TCP FIN frame with unknown tunnel ID %d\n", rcvd_frame->connid);
  201. return -1;
  202. }
  203. if(tun->friendnumber != rcvd_frame->friendnumber)
  204. {
  205. log_printf(L_WARNING, "Friend #%d tried to close tunnel while server is #%d\n", rcvd_frame->friendnumber, tun->friendnumber);
  206. return -1;
  207. }
  208. client_close_tunnel(tun);
  209. return 0;
  210. }
  211. /* Close and delete all tunnels (when server went offline) */
  212. void client_close_all_connections()
  213. {
  214. tunnel *tmp = NULL;
  215. tunnel *tun = NULL;
  216. HASH_ITER(hh, by_id, tun, tmp)
  217. {
  218. client_close_tunnel(tun);
  219. }
  220. }
  221. /* Main loop for the client */
  222. int do_client_loop(uint8_t *tox_id_str)
  223. {
  224. unsigned char tox_packet_buf[PROTOCOL_MAX_PACKET_SIZE];
  225. unsigned char tox_id[TOX_ADDRESS_SIZE];
  226. uint32_t friendnumber = 0;
  227. TOX_CONNECTION last_friend_connection_status = TOX_CONNECTION_NONE;
  228. time_t last_friend_connection_status_received = 0;
  229. time_t connection_lost_timestamp = 0;
  230. struct timeval tv;
  231. fd_set fds;
  232. static time_t invitation_sent_time = 0;
  233. uint32_t invitations_sent = 0;
  234. TOX_ERR_FRIEND_QUERY friend_query_error;
  235. TOX_ERR_FRIEND_CUSTOM_PACKET custom_packet_error;
  236. client_tunnel.sockfd = 0;
  237. FD_ZERO(&client_master_fdset);
  238. tox_callback_friend_lossless_packet(tox, parse_lossless_packet);
  239. if(!string_to_id(tox_id, tox_id_str))
  240. {
  241. log_printf(L_ERROR, "Invalid Tox ID");
  242. exit(1);
  243. }
  244. if(!ping_mode && !client_pipe_mode)
  245. {
  246. local_bind();
  247. signal(SIGPIPE, SIG_IGN);
  248. }
  249. log_printf(L_INFO, "Connecting to Tox...\n");
  250. while(1)
  251. {
  252. /* Let tox do its stuff */
  253. tox_iterate(tox, NULL);
  254. switch(state)
  255. {
  256. /*
  257. * Send friend request
  258. */
  259. case CLIENT_STATE_INITIAL:
  260. if(connection_status != TOX_CONNECTION_NONE)
  261. {
  262. state = CLIENT_STATE_CONNECTED;
  263. }
  264. break;
  265. case CLIENT_STATE_CONNECTED:
  266. {
  267. uint8_t* data = (uint8_t *)"Hi, fellow tuntox instance!";
  268. uint16_t length = sizeof(data);
  269. /* https://github.com/TokTok/c-toxcore/blob/acb6b2d8543c8f2ea0c2e60dc046767cf5cc0de8/toxcore/tox.h#L1168 */
  270. TOX_ERR_FRIEND_ADD add_error;
  271. if(use_shared_secret)
  272. {
  273. data = (uint8_t *)shared_secret;
  274. data[TOX_MAX_FRIEND_REQUEST_LENGTH-1] = '\0';
  275. length = strlen((char *)data)+1;
  276. log_printf(L_DEBUG, "Sent shared secret of length %u\n", length);
  277. }
  278. if(invitations_sent == 0)
  279. {
  280. log_printf(L_INFO, "Connected. Sending friend request.\n");
  281. }
  282. else
  283. {
  284. log_printf(L_INFO, "Sending another friend request.\n");
  285. }
  286. friendnumber = tox_friend_add(
  287. tox,
  288. tox_id,
  289. data,
  290. length,
  291. &add_error
  292. );
  293. if(add_error != TOX_ERR_FRIEND_ADD_OK)
  294. {
  295. unsigned char tox_printable_id[TOX_ADDRESS_SIZE * 2 + 1];
  296. id_to_string(tox_printable_id, tox_id);
  297. log_printf(L_ERROR, "Error %u adding friend %s\n", add_error, tox_printable_id);
  298. exit(-1);
  299. }
  300. invitation_sent_time = time(NULL);
  301. invitations_sent++;
  302. state = CLIENT_STATE_SENTREQUEST;
  303. log_printf(L_INFO, "Waiting for friend to accept us...\n");
  304. }
  305. break;
  306. case CLIENT_STATE_SENTREQUEST:
  307. {
  308. TOX_CONNECTION friend_connection_status;
  309. friend_connection_status = tox_friend_get_connection_status(tox, friendnumber, &friend_query_error);
  310. if(friend_query_error != TOX_ERR_FRIEND_QUERY_OK)
  311. {
  312. log_printf(L_DEBUG, "tox_friend_get_connection_status: error %u", friend_query_error);
  313. }
  314. else
  315. {
  316. last_friend_connection_status_received = time(NULL);
  317. last_friend_connection_status = friend_connection_status;
  318. if(friend_connection_status != TOX_CONNECTION_NONE)
  319. {
  320. const char* status = readable_connection_status(friend_connection_status);
  321. log_printf(L_INFO, "Friend request accepted (%s)!\n", status);
  322. state = CLIENT_STATE_REQUEST_ACCEPTED;
  323. }
  324. else
  325. {
  326. if(1 && (time(NULL) - invitation_sent_time > 45))
  327. {
  328. TOX_ERR_FRIEND_DELETE error = 0;
  329. log_printf(L_INFO, "Sending another friend request...");
  330. tox_friend_delete(
  331. tox,
  332. friendnumber,
  333. &error);
  334. if(error != TOX_ERR_FRIEND_DELETE_OK)
  335. {
  336. log_printf(L_ERROR, "Error %u deleting friend before reconnection\n", error);
  337. exit(-1);
  338. }
  339. state = CLIENT_STATE_CONNECTED;
  340. }
  341. }
  342. }
  343. break;
  344. }
  345. case CLIENT_STATE_REQUEST_ACCEPTED:
  346. if(ping_mode)
  347. {
  348. state = CLIENT_STATE_SEND_PING;
  349. }
  350. else if(client_pipe_mode)
  351. {
  352. state = CLIENT_STATE_SETUP_PIPE;
  353. }
  354. else
  355. {
  356. state = CLIENT_STATE_BIND_PORT;
  357. }
  358. break;
  359. case CLIENT_STATE_SEND_PING:
  360. /* Send the ping packet */
  361. {
  362. uint8_t data[] = {
  363. 0xa2, 0x6a, 0x01, 0x08, 0x00, 0x00, 0x00, 0x05,
  364. 0x48, 0x65, 0x6c, 0x6c, 0x6f
  365. };
  366. clock_gettime(CLOCK_MONOTONIC, &ping_sent_time);
  367. tox_friend_send_lossless_packet(
  368. tox,
  369. friendnumber,
  370. data,
  371. sizeof(data),
  372. &custom_packet_error
  373. );
  374. }
  375. if(custom_packet_error == TOX_ERR_FRIEND_CUSTOM_PACKET_OK)
  376. {
  377. state = CLIENT_STATE_PING_SENT;
  378. }
  379. else
  380. {
  381. log_printf(L_WARNING, "When sending ping packet: %u", custom_packet_error);
  382. }
  383. break;
  384. case CLIENT_STATE_PING_SENT:
  385. /* Just sit there and wait for pong */
  386. break;
  387. case CLIENT_STATE_BIND_PORT:
  388. if(bind_sockfd < 0)
  389. {
  390. log_printf(L_ERROR, "Shutting down - could not bind to listening port\n");
  391. state = CLIENT_STATE_SHUTDOWN;
  392. }
  393. else
  394. {
  395. state = CLIENT_STATE_FORWARDING;
  396. }
  397. break;
  398. case CLIENT_STATE_SETUP_PIPE:
  399. send_tunnel_request_packet(
  400. remote_host,
  401. remote_port,
  402. friendnumber
  403. );
  404. state = CLIENT_STATE_FORWARDING;
  405. break;
  406. case CLIENT_STATE_REQUEST_TUNNEL:
  407. send_tunnel_request_packet(
  408. remote_host,
  409. remote_port,
  410. friendnumber
  411. );
  412. state = CLIENT_STATE_WAIT_FOR_ACKTUNNEL;
  413. break;
  414. case CLIENT_STATE_WAIT_FOR_ACKTUNNEL:
  415. client_tunnel.sockfd = 0;
  416. send_tunnel_request_packet(
  417. remote_host,
  418. remote_port,
  419. friendnumber
  420. );
  421. break;
  422. case CLIENT_STATE_FORWARDING:
  423. {
  424. int accept_fd = 0;
  425. int select_rv = 0;
  426. tunnel *tmp = NULL;
  427. tunnel *tun = NULL;
  428. tv.tv_sec = 0;
  429. tv.tv_usec = 20000;
  430. fds = client_master_fdset;
  431. /* Handle accepting new connections */
  432. if(!client_pipe_mode &&
  433. client_tunnel.sockfd <= 0) /* Don't accept if we're already waiting to establish a tunnel */
  434. {
  435. accept_fd = accept(bind_sockfd, NULL, NULL);
  436. if(accept_fd != -1)
  437. {
  438. log_printf(L_INFO, "Accepting a new connection - requesting tunnel...\n");
  439. /* Open a new tunnel for this FD */
  440. client_tunnel.sockfd = accept_fd;
  441. send_tunnel_request_packet(
  442. remote_host,
  443. remote_port,
  444. friendnumber
  445. );
  446. }
  447. }
  448. /* Handle reading from sockets */
  449. select_rv = select(select_nfds, &fds, NULL, NULL, &tv);
  450. if(select_rv == -1 || select_rv == 0)
  451. {
  452. if(select_rv == -1)
  453. {
  454. log_printf(L_DEBUG, "Reading from local socket failed: code=%d (%s)\n",
  455. errno, strerror(errno));
  456. }
  457. else
  458. {
  459. log_printf(L_DEBUG2, "Nothing to read...");
  460. }
  461. }
  462. else
  463. {
  464. HASH_ITER(hh, by_id, tun, tmp)
  465. {
  466. if(FD_ISSET(tun->sockfd, &fds))
  467. {
  468. int nbytes;
  469. if(client_local_port_mode)
  470. {
  471. nbytes = recv(tun->sockfd,
  472. tox_packet_buf + PROTOCOL_BUFFER_OFFSET,
  473. READ_BUFFER_SIZE, 0);
  474. }
  475. else
  476. {
  477. nbytes = read(tun->sockfd,
  478. tox_packet_buf + PROTOCOL_BUFFER_OFFSET,
  479. READ_BUFFER_SIZE
  480. );
  481. }
  482. /* Check if connection closed */
  483. if(nbytes == 0)
  484. {
  485. uint8_t data[PROTOCOL_BUFFER_OFFSET];
  486. protocol_frame frame_st, *frame;
  487. log_printf(L_INFO, "Connection closed\n");
  488. frame = &frame_st;
  489. memset(frame, 0, sizeof(protocol_frame));
  490. frame->friendnumber = tun->friendnumber;
  491. frame->packet_type = PACKET_TYPE_TCP_FIN;
  492. frame->connid = tun->connid;
  493. frame->data_length = 0;
  494. send_frame(frame, data);
  495. if(tun->sockfd)
  496. {
  497. FD_CLR(tun->sockfd, &client_master_fdset);
  498. }
  499. tunnel_delete(tun);
  500. }
  501. else
  502. {
  503. protocol_frame frame_st, *frame;
  504. frame = &frame_st;
  505. memset(frame, 0, sizeof(protocol_frame));
  506. frame->friendnumber = tun->friendnumber;
  507. frame->packet_type = PACKET_TYPE_TCP;
  508. frame->connid = tun->connid;
  509. frame->data_length = nbytes;
  510. send_frame(frame, tox_packet_buf);
  511. // printf("Wrote %d bytes from sock %d to tunnel %d\n", nbytes, tun->sockfd, tun->connid);
  512. }
  513. }
  514. }
  515. }
  516. fds = client_master_fdset;
  517. /* Check friend connection status changes */
  518. /* TODO: learned about tox_friend_connection_status_cb after writing this... */
  519. /* TODO: also check friend status tox_callback_friend_status */
  520. if(time(NULL) - last_friend_connection_status_received > 15)
  521. {
  522. TOX_CONNECTION friend_connection_status;
  523. friend_connection_status = tox_friend_get_connection_status(tox, friendnumber, &friend_query_error);
  524. if(friend_query_error != TOX_ERR_FRIEND_QUERY_OK)
  525. {
  526. log_printf(L_DEBUG, "tox_friend_get_connection_status: error %u\n", friend_query_error);
  527. }
  528. else
  529. {
  530. if(friend_connection_status != last_friend_connection_status)
  531. {
  532. const char* status = readable_connection_status(friend_connection_status);
  533. log_printf(L_INFO, "Friend connection status changed to: %s (%d)\n", status, friend_connection_status);
  534. if(friend_connection_status == TOX_CONNECTION_NONE)
  535. {
  536. state = CLIENT_STATE_CONNECTION_LOST;
  537. connection_lost_timestamp = time(NULL);
  538. }
  539. }
  540. last_friend_connection_status_received = time(NULL);
  541. last_friend_connection_status = friend_connection_status;
  542. }
  543. }
  544. }
  545. break;
  546. case CLIENT_STATE_CONNECTION_LOST:
  547. {
  548. TOX_CONNECTION friend_connection_status;
  549. friend_connection_status = tox_friend_get_connection_status(tox, friendnumber, &friend_query_error);
  550. if(friend_query_error != TOX_ERR_FRIEND_QUERY_OK)
  551. {
  552. log_printf(L_DEBUG, "tox_friend_get_connection_status: error %u\n", friend_query_error);
  553. }
  554. else
  555. {
  556. if(friend_connection_status == TOX_CONNECTION_NONE)
  557. {
  558. /* https://github.com/TokTok/c-toxcore/blob/acb6b2d8543c8f2ea0c2e60dc046767cf5cc0de8/toxcore/tox.h#L1267 */
  559. TOX_ERR_FRIEND_DELETE tox_delete_error;
  560. log_printf(L_WARNING, "Lost connection to server, closing all tunnels and re-adding friend\n");
  561. client_close_all_connections();
  562. tox_friend_delete(tox, friendnumber, &tox_delete_error);
  563. if(tox_delete_error)
  564. {
  565. log_printf(L_ERROR, "Error when deleting server from friend list: %d\n", tox_delete_error);
  566. }
  567. state = CLIENT_STATE_INITIAL;
  568. }
  569. else
  570. {
  571. state = CLIENT_STATE_FORWARDING;
  572. }
  573. }
  574. }
  575. break;
  576. case 0xffffffff:
  577. log_printf(L_ERROR, "You forgot a break statement\n");
  578. case CLIENT_STATE_SHUTDOWN:
  579. exit(0);
  580. break;
  581. }
  582. usleep(tox_iteration_interval(tox) * 1000);
  583. }
  584. }