main.c 46 KB

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