connection.c 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586
  1. /* Copyright 2001 Matej Pfajfar.
  2. * Copyright 2001-2004 Roger Dingledine.
  3. * Copyright 2004 Roger Dingledine, Nick Mathewson. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. const char connection_c_id[] = "$Id$";
  7. /**
  8. * \file connection.c
  9. * \brief General high-level functions to handle reading and writing
  10. * on connections.
  11. **/
  12. #include "or.h"
  13. /********* START VARIABLES **********/
  14. /** Array of strings to make conn-\>type human-readable. */
  15. const char *conn_type_to_string[] = {
  16. "", /* 0 */
  17. "OP listener", /* 1 */
  18. "OP", /* 2 */
  19. "OR listener", /* 3 */
  20. "OR", /* 4 */
  21. "Exit", /* 5 */
  22. "App listener",/* 6 */
  23. "App", /* 7 */
  24. "Dir listener",/* 8 */
  25. "Dir", /* 9 */
  26. "DNS worker", /* 10 */
  27. "CPU worker", /* 11 */
  28. "Control listener", /* 12 */
  29. "Control", /* 13 */
  30. };
  31. /** Array of string arrays to make {conn-\>type,conn-\>state} human-readable. */
  32. const char *conn_state_to_string[][_CONN_TYPE_MAX+1] = {
  33. { NULL }, /* no type associated with 0 */
  34. { NULL }, /* op listener, obsolete */
  35. { NULL }, /* op, obsolete */
  36. { "ready" }, /* or listener, 0 */
  37. { "", /* OR, 0 */
  38. "connect()ing", /* 1 */
  39. "handshaking", /* 2 */
  40. "open" }, /* 3 */
  41. { "", /* exit, 0 */
  42. "waiting for dest info", /* 1 */
  43. "connecting", /* 2 */
  44. "open", /* 3 */
  45. "resolve failed" }, /* 4 */
  46. { "ready" }, /* app listener, 0 */
  47. { "", /* 0 */
  48. "", /* 1 */
  49. "", /* 2 */
  50. "", /* 3 */
  51. "", /* 4 */
  52. "awaiting dest info", /* app, 5 */
  53. "waiting for rendezvous desc", /* 6 */
  54. "waiting for safe circuit", /* 7 */
  55. "waiting for connected", /* 8 */
  56. "waiting for resolve", /* 9 */
  57. "open" }, /* 10 */
  58. { "ready" }, /* dir listener, 0 */
  59. { "", /* dir, 0 */
  60. "connecting", /* 1 */
  61. "client sending", /* 2 */
  62. "client reading", /* 3 */
  63. "awaiting command", /* 4 */
  64. "writing" }, /* 5 */
  65. { "", /* dns worker, 0 */
  66. "idle", /* 1 */
  67. "busy" }, /* 2 */
  68. { "", /* cpu worker, 0 */
  69. "idle", /* 1 */
  70. "busy with onion", /* 2 */
  71. "busy with handshake" }, /* 3 */
  72. { "ready" }, /* control listener, 0 */
  73. { "", /* control, 0 */
  74. "ready", /* 1 */
  75. "waiting for authentication", }, /* 2 */
  76. };
  77. /********* END VARIABLES ************/
  78. static int connection_create_listener(const char *bindaddress,
  79. uint16_t bindport, int type);
  80. static int connection_init_accepted_conn(connection_t *conn);
  81. static int connection_handle_listener_read(connection_t *conn, int new_type);
  82. static int connection_receiver_bucket_should_increase(connection_t *conn);
  83. static int connection_finished_flushing(connection_t *conn);
  84. static int connection_finished_connecting(connection_t *conn);
  85. static int connection_reached_eof(connection_t *conn);
  86. static int connection_read_to_buf(connection_t *conn, int *max_to_read);
  87. static int connection_process_inbuf(connection_t *conn, int package_partial);
  88. static int connection_bucket_read_limit(connection_t *conn);
  89. /**************************************************************/
  90. /** Allocate space for a new connection_t. This function just initializes
  91. * conn; you must call connection_add() to link it into the main array.
  92. *
  93. * Set conn-\>type to <b>type</b>. Set conn-\>s and conn-\>poll_index to
  94. * -1 to signify they are not yet assigned.
  95. *
  96. * If conn is not a listener type, allocate buffers for it. If it's
  97. * an AP type, allocate space to store the socks_request.
  98. *
  99. * Assign a pseudorandom next_circ_id between 0 and 2**15.
  100. *
  101. * Initialize conn's timestamps to now.
  102. */
  103. connection_t *connection_new(int type) {
  104. connection_t *conn;
  105. time_t now = time(NULL);
  106. conn = tor_malloc_zero(sizeof(connection_t));
  107. conn->magic = CONNECTION_MAGIC;
  108. conn->s = -1; /* give it a default of 'not used' */
  109. conn->poll_index = -1; /* also default to 'not used' */
  110. conn->type = type;
  111. if (!connection_is_listener(conn)) { /* listeners never use their buf */
  112. conn->inbuf = buf_new();
  113. conn->outbuf = buf_new();
  114. }
  115. if (type == CONN_TYPE_AP) {
  116. conn->socks_request = tor_malloc_zero(sizeof(socks_request_t));
  117. }
  118. conn->next_circ_id = crypto_pseudo_rand_int(1<<15);
  119. conn->timestamp_created = now;
  120. conn->timestamp_lastread = now;
  121. conn->timestamp_lastwritten = now;
  122. return conn;
  123. }
  124. /** Deallocate memory used by <b>conn</b>. Deallocate its buffers if necessary,
  125. * close its socket if necessary, and mark the directory as dirty if <b>conn</b>
  126. * is an OR or OP connection.
  127. */
  128. static void
  129. _connection_free(connection_t *conn) {
  130. tor_assert(conn->magic == CONNECTION_MAGIC);
  131. if (!connection_is_listener(conn)) {
  132. buf_free(conn->inbuf);
  133. buf_free(conn->outbuf);
  134. }
  135. tor_free(conn->address);
  136. tor_free(conn->chosen_exit_name);
  137. if (connection_speaks_cells(conn)) {
  138. if (conn->state == OR_CONN_STATE_OPEN)
  139. directory_set_dirty();
  140. if (conn->tls)
  141. tor_tls_free(conn->tls);
  142. }
  143. if (conn->identity_pkey)
  144. crypto_free_pk_env(conn->identity_pkey);
  145. tor_free(conn->nickname);
  146. tor_free(conn->socks_request);
  147. if (conn->s >= 0) {
  148. log_fn(LOG_INFO,"closing fd %d.",conn->s);
  149. tor_close_socket(conn->s);
  150. }
  151. if (conn->read_event) {
  152. event_del(conn->read_event);
  153. tor_free(conn->read_event);
  154. }
  155. if (conn->write_event) {
  156. event_del(conn->write_event);
  157. tor_free(conn->write_event);
  158. }
  159. memset(conn, 0xAA, sizeof(connection_t)); /* poison memory */
  160. tor_free(conn);
  161. }
  162. /** Make sure <b>conn</b> isn't in any of the global conn lists; then free it.
  163. */
  164. void connection_free(connection_t *conn) {
  165. tor_assert(conn);
  166. tor_assert(!connection_is_on_closeable_list(conn));
  167. tor_assert(!connection_in_array(conn));
  168. _connection_free(conn);
  169. }
  170. /** Call _connection_free() on every connection in our array.
  171. * This is used by cpuworkers and dnsworkers when they fork,
  172. * so they don't keep resources held open (especially sockets).
  173. *
  174. * Don't do the checks in connection_free(), because they will
  175. * fail.
  176. */
  177. void connection_free_all(void) {
  178. int i, n;
  179. connection_t **carray;
  180. get_connection_array(&carray,&n);
  181. for (i=0;i<n;i++)
  182. _connection_free(carray[i]);
  183. }
  184. /** Do any cleanup needed:
  185. * - Directory conns that failed to fetch a rendezvous descriptor
  186. * need to inform pending rendezvous streams.
  187. * - OR conns need to call rep_hist_note_*() to record status.
  188. * - AP conns need to send a socks reject if necessary.
  189. * - Exit conns need to call connection_dns_remove() if necessary.
  190. * - AP and Exit conns need to send an end cell if they can.
  191. * - DNS conns need to fail any resolves that are pending on them.
  192. */
  193. void connection_about_to_close_connection(connection_t *conn)
  194. {
  195. circuit_t *circ;
  196. assert(conn->marked_for_close);
  197. if (conn->type == CONN_TYPE_AP || conn->type == CONN_TYPE_EXIT) {
  198. if (!conn->has_sent_end)
  199. log_fn(LOG_WARN,"Bug: Edge connection hasn't sent end yet?");
  200. }
  201. switch (conn->type) {
  202. case CONN_TYPE_DIR:
  203. if (conn->state == DIR_CONN_STATE_CONNECTING) {
  204. /* it's a directory server and connecting failed: forget about
  205. this router */
  206. connection_dir_connect_failed(conn);
  207. }
  208. if (conn->purpose == DIR_PURPOSE_FETCH_RENDDESC)
  209. rend_client_desc_here(conn->rend_query); /* give it a try */
  210. break;
  211. case CONN_TYPE_OR:
  212. /* Remember why we're closing this connection. */
  213. if (conn->state != OR_CONN_STATE_OPEN) {
  214. if (connection_or_nonopen_was_started_here(conn)) {
  215. rep_hist_note_connect_failed(conn->identity_digest, time(NULL));
  216. control_event_or_conn_status(conn, OR_CONN_EVENT_FAILED);
  217. }
  218. } else if (conn->hold_open_until_flushed) {
  219. /* XXXX009 We used to have an arg that told us whether we closed the
  220. * connection on purpose or not. Can we use hold_open_until_flushed
  221. * instead? We only set it when we are intentionally closing a
  222. * connection. -NM
  223. *
  224. * (Of course, now things we set to close which expire rather than
  225. * flushing still get noted as dead, not disconnected. But this is an
  226. * improvement. -NM
  227. */
  228. rep_hist_note_disconnect(conn->identity_digest, time(NULL));
  229. control_event_or_conn_status(conn, OR_CONN_EVENT_CLOSED);
  230. } else if (conn->identity_digest) {
  231. rep_hist_note_connection_died(conn->identity_digest, time(NULL));
  232. control_event_or_conn_status(conn, OR_CONN_EVENT_CLOSED);
  233. }
  234. break;
  235. case CONN_TYPE_AP:
  236. if (conn->socks_request->has_finished == 0) {
  237. log_fn(LOG_INFO,"Cleaning up AP -- sending socks reject.");
  238. conn->hold_open_until_flushed = 1;
  239. /* XXX this socks_reply never gets sent, since conn
  240. * gets removed right after this function finishes. */
  241. connection_ap_handshake_socks_reply(conn, NULL, 0, -1);
  242. conn->socks_request->has_finished = 1;
  243. } else {
  244. control_event_stream_status(conn, STREAM_EVENT_CLOSED);
  245. }
  246. break;
  247. case CONN_TYPE_EXIT:
  248. if (conn->state == EXIT_CONN_STATE_RESOLVING) {
  249. circ = circuit_get_by_conn(conn);
  250. if (circ)
  251. circuit_detach_stream(circ, conn);
  252. connection_dns_remove(conn);
  253. }
  254. break;
  255. case CONN_TYPE_DNSWORKER:
  256. if (conn->state == DNSWORKER_STATE_BUSY) {
  257. dns_cancel_pending_resolve(conn->address);
  258. }
  259. break;
  260. }
  261. }
  262. /** Close the underlying socket for <b>conn</b>, so we don't try to
  263. * flush it. Must be used in conjunction with (right before)
  264. * connection_mark_for_close().
  265. */
  266. void connection_close_immediate(connection_t *conn)
  267. {
  268. assert_connection_ok(conn,0);
  269. if (conn->s < 0) {
  270. log_fn(LOG_WARN,"Bug: Attempt to close already-closed connection.");
  271. return;
  272. }
  273. if (conn->outbuf_flushlen) {
  274. log_fn(LOG_INFO,"fd %d, type %s, state %d, %d bytes on outbuf.",
  275. conn->s, CONN_TYPE_TO_STRING(conn->type),
  276. conn->state, (int)conn->outbuf_flushlen);
  277. }
  278. tor_close_socket(conn->s);
  279. conn->s = -1;
  280. if (!connection_is_listener(conn)) {
  281. buf_clear(conn->outbuf);
  282. conn->outbuf_flushlen = 0;
  283. }
  284. }
  285. /** Mark <b>conn</b> to be closed next time we loop through
  286. * conn_close_if_marked() in main.c. */
  287. int
  288. _connection_mark_for_close(connection_t *conn)
  289. {
  290. assert_connection_ok(conn,0);
  291. if (conn->marked_for_close) {
  292. log(LOG_WARN, "Bug: Double mark-for-close on connection.");
  293. return -1;
  294. }
  295. conn->marked_for_close = 1;
  296. add_connection_to_closeable_list(conn);
  297. /* in case we're going to be held-open-til-flushed, reset
  298. * the number of seconds since last successful write, so
  299. * we get our whole 15 seconds */
  300. conn->timestamp_lastwritten = time(NULL);
  301. return 0;
  302. }
  303. /** Find each connection that has hold_open_until_flushed set to
  304. * 1 but hasn't written in the past 15 seconds, and set
  305. * hold_open_until_flushed to 0. This means it will get cleaned
  306. * up in the next loop through close_if_marked() in main.c.
  307. */
  308. void connection_expire_held_open(void)
  309. {
  310. connection_t **carray, *conn;
  311. int n, i;
  312. time_t now;
  313. now = time(NULL);
  314. get_connection_array(&carray, &n);
  315. for (i = 0; i < n; ++i) {
  316. conn = carray[i];
  317. /* If we've been holding the connection open, but we haven't written
  318. * for 15 seconds...
  319. */
  320. if (conn->hold_open_until_flushed) {
  321. tor_assert(conn->marked_for_close);
  322. if (now - conn->timestamp_lastwritten >= 15) {
  323. log_fn(LOG_NOTICE,"Giving up on marked_for_close conn that's been flushing for 15s (fd %d, type %s, state %d).",
  324. conn->s, CONN_TYPE_TO_STRING(conn->type), conn->state);
  325. conn->hold_open_until_flushed = 0;
  326. }
  327. }
  328. }
  329. }
  330. /** Bind a new non-blocking socket listening to
  331. * <b>bindaddress</b>:<b>bindport</b>, and add this new connection
  332. * (of type <b>type</b>) to the connection array.
  333. *
  334. * If <b>bindaddress</b> includes a port, we bind on that port; otherwise, we
  335. * use bindport.
  336. */
  337. static int connection_create_listener(const char *bindaddress, uint16_t bindport, int type) {
  338. struct sockaddr_in bindaddr; /* where to bind */
  339. connection_t *conn;
  340. uint16_t usePort;
  341. uint32_t addr;
  342. int s; /* the socket we're going to make */
  343. int one=1;
  344. memset(&bindaddr,0,sizeof(struct sockaddr_in));
  345. if (parse_addr_port(bindaddress, NULL, &addr, &usePort)<0) {
  346. log_fn(LOG_WARN, "Error parsing/resolving BindAddress %s",bindaddress);
  347. return -1;
  348. }
  349. if (usePort==0)
  350. usePort = bindport;
  351. bindaddr.sin_addr.s_addr = htonl(addr);
  352. bindaddr.sin_family = AF_INET;
  353. bindaddr.sin_port = htons((uint16_t) usePort);
  354. s = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
  355. if (s < 0) {
  356. log_fn(LOG_WARN,"Socket creation failed.");
  357. return -1;
  358. } else if (!SOCKET_IS_POLLABLE(s)) {
  359. log_fn(LOG_WARN,"Too many connections; can't create pollable listener.");
  360. tor_close_socket(s);
  361. return -1;
  362. }
  363. setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void*) &one, sizeof(one));
  364. if (bind(s,(struct sockaddr *)&bindaddr,sizeof(bindaddr)) < 0) {
  365. log_fn(LOG_WARN,"Could not bind to port %u: %s",usePort,
  366. tor_socket_strerror(tor_socket_errno(s)));
  367. return -1;
  368. }
  369. if (listen(s,SOMAXCONN) < 0) {
  370. log_fn(LOG_WARN,"Could not listen on port %u: %s",usePort,
  371. tor_socket_strerror(tor_socket_errno(s)));
  372. return -1;
  373. }
  374. set_socket_nonblocking(s);
  375. conn = connection_new(type);
  376. conn->s = s;
  377. if (connection_add(conn) < 0) { /* no space, forget it */
  378. log_fn(LOG_WARN,"connection_add failed. Giving up.");
  379. connection_free(conn);
  380. return -1;
  381. }
  382. log_fn(LOG_DEBUG,"%s listening on port %u.",conn_type_to_string[type], usePort);
  383. conn->state = LISTENER_STATE_READY;
  384. connection_start_reading(conn);
  385. return 0;
  386. }
  387. /** The listener connection <b>conn</b> told poll() it wanted to read.
  388. * Call accept() on conn-\>s, and add the new connection if necessary.
  389. */
  390. static int connection_handle_listener_read(connection_t *conn, int new_type) {
  391. int news; /* the new socket */
  392. connection_t *newconn;
  393. /* information about the remote peer when connecting to other routers */
  394. struct sockaddr_in remote;
  395. /* length of the remote address. Must be an int, since accept() needs that. */
  396. int remotelen = sizeof(struct sockaddr_in);
  397. news = accept(conn->s,(struct sockaddr *)&remote,&remotelen);
  398. if (!SOCKET_IS_POLLABLE(news)) {
  399. /* accept() error, or too many conns to poll */
  400. int e;
  401. if (news>=0) {
  402. /* Too many conns to poll. */
  403. log_fn(LOG_WARN,"Too many connections; couldn't accept connection.");
  404. tor_close_socket(news);
  405. return 0;
  406. }
  407. e = tor_socket_errno(conn->s);
  408. if (ERRNO_IS_ACCEPT_EAGAIN(e)) {
  409. return 0; /* he hung up before we could accept(). that's fine. */
  410. } else if (ERRNO_IS_ACCEPT_RESOURCE_LIMIT(e)) {
  411. log_fn(LOG_NOTICE,"accept failed: %s. Dropping incoming connection.",
  412. tor_socket_strerror(e));
  413. return 0;
  414. }
  415. /* else there was a real error. */
  416. log_fn(LOG_WARN,"accept() failed: %s. Closing listener.",
  417. tor_socket_strerror(e));
  418. connection_mark_for_close(conn);
  419. return -1;
  420. }
  421. log(LOG_INFO,"Connection accepted on socket %d (child of fd %d).",news, conn->s);
  422. set_socket_nonblocking(news);
  423. /* process entrance policies here, before we even create the connection */
  424. if (new_type == CONN_TYPE_AP) {
  425. /* check sockspolicy to see if we should accept it */
  426. if (socks_policy_permits_address(ntohl(remote.sin_addr.s_addr)) == 0) {
  427. log_fn(LOG_NOTICE,"Denying socks connection from untrusted address %s.",
  428. inet_ntoa(remote.sin_addr));
  429. tor_close_socket(news);
  430. return 0;
  431. }
  432. }
  433. if (new_type == CONN_TYPE_DIR) {
  434. /* check dirpolicy to see if we should accept it */
  435. if (dir_policy_permits_address(ntohl(remote.sin_addr.s_addr)) == 0) {
  436. log_fn(LOG_NOTICE,"Denying dir connection from address %s.",
  437. inet_ntoa(remote.sin_addr));
  438. tor_close_socket(news);
  439. return 0;
  440. }
  441. }
  442. newconn = connection_new(new_type);
  443. newconn->s = news;
  444. newconn->address = tor_strdup(inet_ntoa(remote.sin_addr)); /* remember the remote address */
  445. newconn->addr = ntohl(remote.sin_addr.s_addr);
  446. newconn->port = ntohs(remote.sin_port);
  447. if (connection_add(newconn) < 0) { /* no space, forget it */
  448. connection_free(newconn);
  449. return 0; /* no need to tear down the parent */
  450. }
  451. if (connection_init_accepted_conn(newconn) < 0) {
  452. connection_mark_for_close(newconn);
  453. return 0;
  454. }
  455. return 0;
  456. }
  457. /** Initialize states for newly accepted connection <b>conn</b>.
  458. * If conn is an OR, start the tls handshake.
  459. */
  460. static int connection_init_accepted_conn(connection_t *conn) {
  461. connection_start_reading(conn);
  462. switch (conn->type) {
  463. case CONN_TYPE_OR:
  464. return connection_tls_start_handshake(conn, 1);
  465. case CONN_TYPE_AP:
  466. conn->state = AP_CONN_STATE_SOCKS_WAIT;
  467. break;
  468. case CONN_TYPE_DIR:
  469. conn->purpose = DIR_PURPOSE_SERVER;
  470. conn->state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
  471. break;
  472. case CONN_TYPE_CONTROL:
  473. conn->state = CONTROL_CONN_STATE_NEEDAUTH;
  474. break;
  475. }
  476. return 0;
  477. }
  478. /** Take conn, make a nonblocking socket; try to connect to
  479. * addr:port (they arrive in *host order*). If fail, return -1. Else
  480. * assign s to conn->\s: if connected return 1, if EAGAIN return 0.
  481. *
  482. * address is used to make the logs useful.
  483. *
  484. * On success, add conn to the list of polled connections.
  485. */
  486. int connection_connect(connection_t *conn, char *address, uint32_t addr, uint16_t port) {
  487. int s;
  488. struct sockaddr_in dest_addr;
  489. or_options_t *options = get_options();
  490. s = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
  491. if (s < 0) {
  492. log_fn(LOG_WARN,"Error creating network socket: %s",
  493. tor_socket_strerror(tor_socket_errno(-1)));
  494. return -1;
  495. } else if (!SOCKET_IS_POLLABLE(s)) {
  496. log_fn(LOG_WARN,
  497. "Too many connections; can't create pollable connection to %s", address);
  498. tor_close_socket(s);
  499. return -1;
  500. }
  501. if (options->OutboundBindAddress) {
  502. struct sockaddr_in ext_addr;
  503. memset(&ext_addr, 0, sizeof(ext_addr));
  504. ext_addr.sin_family = AF_INET;
  505. ext_addr.sin_port = 0;
  506. if (!tor_inet_aton(options->OutboundBindAddress, &ext_addr.sin_addr)) {
  507. log_fn(LOG_WARN,"Outbound bind address '%s' didn't parse. Ignoring.",
  508. options->OutboundBindAddress);
  509. } else {
  510. if (bind(s, (struct sockaddr*)&ext_addr, sizeof(ext_addr)) < 0) {
  511. log_fn(LOG_WARN,"Error binding network socket: %s",
  512. tor_socket_strerror(tor_socket_errno(s)));
  513. return -1;
  514. }
  515. }
  516. }
  517. set_socket_nonblocking(s);
  518. memset(&dest_addr,0,sizeof(dest_addr));
  519. dest_addr.sin_family = AF_INET;
  520. dest_addr.sin_port = htons(port);
  521. dest_addr.sin_addr.s_addr = htonl(addr);
  522. log_fn(LOG_DEBUG,"Connecting to %s:%u.",address,port);
  523. if (connect(s,(struct sockaddr *)&dest_addr,sizeof(dest_addr)) < 0) {
  524. int e = tor_socket_errno(s);
  525. if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
  526. /* yuck. kill it. */
  527. log_fn(LOG_INFO,"Connect() to %s:%u failed: %s",address,port,
  528. tor_socket_strerror(e));
  529. tor_close_socket(s);
  530. return -1;
  531. } else {
  532. /* it's in progress. set state appropriately and return. */
  533. conn->s = s;
  534. if (connection_add(conn) < 0) /* no space, forget it */
  535. return -1;
  536. log_fn(LOG_DEBUG,"connect in progress, socket %d.",s);
  537. return 0;
  538. }
  539. }
  540. /* it succeeded. we're connected. */
  541. log_fn(LOG_INFO,"Connection to %s:%u established.",address,port);
  542. conn->s = s;
  543. if (connection_add(conn) < 0) /* no space, forget it */
  544. return -1;
  545. return 1;
  546. }
  547. /** If there exist any listeners of type <b>type</b> in the connection
  548. * array, mark them for close.
  549. */
  550. static void listener_close_if_present(int type) {
  551. connection_t *conn;
  552. connection_t **carray;
  553. int i,n;
  554. tor_assert(type == CONN_TYPE_OR_LISTENER ||
  555. type == CONN_TYPE_AP_LISTENER ||
  556. type == CONN_TYPE_DIR_LISTENER ||
  557. type == CONN_TYPE_CONTROL_LISTENER);
  558. get_connection_array(&carray,&n);
  559. for (i=0;i<n;i++) {
  560. conn = carray[i];
  561. if (conn->type == type && !conn->marked_for_close) {
  562. connection_close_immediate(conn);
  563. connection_mark_for_close(conn);
  564. }
  565. }
  566. }
  567. /**
  568. * Launch any configured listener connections of type <b>type</b>. (A
  569. * listener is configured if <b>port_option</b> is non-zero. If any
  570. * BindAddress configuration options are given in <b>cfg</b>, create a
  571. * connection binding to each one. Otherwise, create a single
  572. * connection binding to the address <b>default_addr</b>.)
  573. *
  574. * If <b>force</b> is true, close and re-open all listener connections.
  575. * Otherwise, only relaunch the listeners of this type if the number of
  576. * existing connections is not as configured (e.g., because one died).
  577. */
  578. static int retry_listeners(int type, struct config_line_t *cfg,
  579. int port_option, const char *default_addr,
  580. int force)
  581. {
  582. if (!force) {
  583. int want, have, n_conn, i;
  584. struct config_line_t *c;
  585. connection_t *conn;
  586. connection_t **carray;
  587. /* How many should there be? */
  588. if (cfg && port_option) {
  589. want = 0;
  590. for (c = cfg; c; c = c->next)
  591. ++want;
  592. } else if (port_option) {
  593. want = 1;
  594. } else {
  595. want = 0;
  596. }
  597. /* How many are there actually? */
  598. have = 0;
  599. get_connection_array(&carray,&n_conn);
  600. for (i=0;i<n_conn;i++) {
  601. conn = carray[i];
  602. if (conn->type == type && !conn->marked_for_close)
  603. ++have;
  604. }
  605. /* If we have the right number of listeners, do nothing. */
  606. if (have == want)
  607. return 0;
  608. /* Otherwise, warn the user and relaunch. */
  609. log_fn(LOG_NOTICE,"We have %d %s(s) open, but we want %d; relaunching.",
  610. have, conn_type_to_string[type], want);
  611. }
  612. listener_close_if_present(type);
  613. if (port_option) {
  614. if (!cfg) {
  615. if (connection_create_listener(default_addr, (uint16_t) port_option,
  616. type)<0)
  617. return -1;
  618. } else {
  619. for ( ; cfg; cfg = cfg->next) {
  620. if (connection_create_listener(cfg->value, (uint16_t) port_option,
  621. type)<0)
  622. return -1;
  623. }
  624. }
  625. }
  626. return 0;
  627. }
  628. /** (Re)launch listeners for each port you should have open. If
  629. * <b>force</b> is true, close and relaunch all listeners. If <b>force</b>
  630. * is false, then only relaunch listeners when we have the wrong number of
  631. * connections for a given type.
  632. */
  633. int retry_all_listeners(int force) {
  634. or_options_t *options = get_options();
  635. if (retry_listeners(CONN_TYPE_OR_LISTENER, options->ORBindAddress,
  636. options->ORPort, "0.0.0.0", force)<0)
  637. return -1;
  638. if (retry_listeners(CONN_TYPE_DIR_LISTENER, options->DirBindAddress,
  639. options->DirPort, "0.0.0.0", force)<0)
  640. return -1;
  641. if (retry_listeners(CONN_TYPE_AP_LISTENER, options->SocksBindAddress,
  642. options->SocksPort, "127.0.0.1", force)<0)
  643. return -1;
  644. if (retry_listeners(CONN_TYPE_CONTROL_LISTENER, NULL,
  645. options->ControlPort, "127.0.0.1", force)<0)
  646. return -1;
  647. return 0;
  648. }
  649. extern int global_read_bucket, global_write_bucket;
  650. /** How many bytes at most can we read onto this connection? */
  651. static int connection_bucket_read_limit(connection_t *conn) {
  652. int at_most;
  653. /* do a rudimentary round-robin so one circuit can't hog a connection */
  654. if (connection_speaks_cells(conn)) {
  655. at_most = 32*(CELL_NETWORK_SIZE);
  656. } else {
  657. at_most = 32*(RELAY_PAYLOAD_SIZE);
  658. }
  659. if (at_most > global_read_bucket)
  660. at_most = global_read_bucket;
  661. if (connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN)
  662. if (at_most > conn->receiver_bucket)
  663. at_most = conn->receiver_bucket;
  664. if (at_most < 0)
  665. return 0;
  666. return at_most;
  667. }
  668. /** We just read num_read onto conn. Decrement buckets appropriately. */
  669. static void connection_read_bucket_decrement(connection_t *conn, int num_read) {
  670. global_read_bucket -= num_read; //tor_assert(global_read_bucket >= 0);
  671. if (connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN) {
  672. conn->receiver_bucket -= num_read; //tor_assert(conn->receiver_bucket >= 0);
  673. }
  674. }
  675. static void connection_consider_empty_buckets(connection_t *conn) {
  676. if (global_read_bucket <= 0) {
  677. log_fn(LOG_DEBUG,"global bucket exhausted. Pausing.");
  678. conn->wants_to_read = 1;
  679. connection_stop_reading(conn);
  680. return;
  681. }
  682. if (connection_speaks_cells(conn) &&
  683. conn->state == OR_CONN_STATE_OPEN &&
  684. conn->receiver_bucket <= 0) {
  685. log_fn(LOG_DEBUG,"receiver bucket exhausted. Pausing.");
  686. conn->wants_to_read = 1;
  687. connection_stop_reading(conn);
  688. }
  689. }
  690. /** Initialize the global read bucket to options->BandwidthBurst,
  691. * and current_time to the current time. */
  692. void connection_bucket_init(void) {
  693. or_options_t *options = get_options();
  694. global_read_bucket = (int)options->BandwidthBurst; /* start it at max traffic */
  695. global_write_bucket = (int)options->BandwidthBurst; /* start it at max traffic */
  696. }
  697. /** A second has rolled over; increment buckets appropriately. */
  698. void connection_bucket_refill(struct timeval *now) {
  699. int i, n;
  700. connection_t *conn;
  701. connection_t **carray;
  702. or_options_t *options = get_options();
  703. /* refill the global buckets */
  704. if (global_read_bucket < (int)options->BandwidthBurst) {
  705. global_read_bucket += (int)options->BandwidthRate;
  706. log_fn(LOG_DEBUG,"global_read_bucket now %d.", global_read_bucket);
  707. }
  708. if (global_write_bucket < (int)options->BandwidthBurst) {
  709. global_write_bucket += (int)options->BandwidthRate;
  710. log_fn(LOG_DEBUG,"global_write_bucket now %d.", global_write_bucket);
  711. }
  712. /* refill the per-connection buckets */
  713. get_connection_array(&carray,&n);
  714. for (i=0;i<n;i++) {
  715. conn = carray[i];
  716. if (connection_receiver_bucket_should_increase(conn)) {
  717. conn->receiver_bucket += conn->bandwidth;
  718. //log_fn(LOG_DEBUG,"Receiver bucket %d now %d.", i, conn->receiver_bucket);
  719. }
  720. if (conn->wants_to_read == 1 /* it's marked to turn reading back on now */
  721. && global_read_bucket > 0 /* and we're allowed to read */
  722. && global_write_bucket > 0 /* and we're allowed to write (XXXX,
  723. * not the best place to check this.) */
  724. && (!connection_speaks_cells(conn) ||
  725. conn->state != OR_CONN_STATE_OPEN ||
  726. conn->receiver_bucket > 0)) {
  727. /* and either a non-cell conn or a cell conn with non-empty bucket */
  728. log_fn(LOG_DEBUG,"waking up conn (fd %d)",conn->s);
  729. conn->wants_to_read = 0;
  730. connection_start_reading(conn);
  731. if (conn->wants_to_write == 1) {
  732. conn->wants_to_write = 0;
  733. connection_start_writing(conn);
  734. }
  735. }
  736. }
  737. }
  738. /** Is the receiver bucket for connection <b>conn</b> low enough that we
  739. * should add another pile of tokens to it?
  740. */
  741. static int connection_receiver_bucket_should_increase(connection_t *conn) {
  742. tor_assert(conn);
  743. if (!connection_speaks_cells(conn))
  744. return 0; /* edge connections don't use receiver_buckets */
  745. if (conn->state != OR_CONN_STATE_OPEN)
  746. return 0; /* only open connections play the rate limiting game */
  747. tor_assert(conn->bandwidth > 0);
  748. if (conn->receiver_bucket > 9*conn->bandwidth)
  749. return 0;
  750. return 1;
  751. }
  752. /** Read bytes from conn->\s and process them.
  753. *
  754. * This function gets called from conn_read() in main.c, either
  755. * when poll() has declared that conn wants to read, or (for OR conns)
  756. * when there are pending TLS bytes.
  757. *
  758. * It calls connection_read_to_buf() to bring in any new bytes,
  759. * and then calls connection_process_inbuf() to process them.
  760. *
  761. * Mark the connection and return -1 if you want to close it, else
  762. * return 0.
  763. */
  764. int connection_handle_read(connection_t *conn) {
  765. int max_to_read=-1, try_to_read;
  766. conn->timestamp_lastread = time(NULL);
  767. switch (conn->type) {
  768. case CONN_TYPE_OR_LISTENER:
  769. return connection_handle_listener_read(conn, CONN_TYPE_OR);
  770. case CONN_TYPE_AP_LISTENER:
  771. return connection_handle_listener_read(conn, CONN_TYPE_AP);
  772. case CONN_TYPE_DIR_LISTENER:
  773. return connection_handle_listener_read(conn, CONN_TYPE_DIR);
  774. case CONN_TYPE_CONTROL_LISTENER:
  775. return connection_handle_listener_read(conn, CONN_TYPE_CONTROL);
  776. }
  777. loop_again:
  778. try_to_read = max_to_read;
  779. tor_assert(!conn->marked_for_close);
  780. if (connection_read_to_buf(conn, &max_to_read) < 0) {
  781. /* There's a read error; kill the connection.*/
  782. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  783. if (conn->type == CONN_TYPE_AP || conn->type == CONN_TYPE_EXIT) {
  784. connection_edge_end(conn, (char)(connection_state_is_open(conn) ?
  785. END_STREAM_REASON_MISC : END_STREAM_REASON_CONNECTFAILED),
  786. conn->cpath_layer);
  787. }
  788. connection_mark_for_close(conn);
  789. return -1;
  790. }
  791. if (CONN_IS_EDGE(conn) &&
  792. try_to_read != max_to_read) {
  793. /* instruct it not to try to package partial cells. */
  794. if (connection_process_inbuf(conn, 0) < 0) {
  795. return -1;
  796. }
  797. if (!conn->marked_for_close &&
  798. connection_is_reading(conn) &&
  799. !conn->inbuf_reached_eof &&
  800. max_to_read > 0)
  801. goto loop_again; /* try reading again, in case more is here now */
  802. }
  803. /* one last try, packaging partial cells and all. */
  804. if (!conn->marked_for_close &&
  805. connection_process_inbuf(conn, 1) < 0) {
  806. return -1;
  807. }
  808. if (!conn->marked_for_close &&
  809. conn->inbuf_reached_eof &&
  810. connection_reached_eof(conn) < 0) {
  811. return -1;
  812. }
  813. return 0;
  814. }
  815. /** Pull in new bytes from conn-\>s onto conn-\>inbuf, either
  816. * directly or via TLS. Reduce the token buckets by the number of
  817. * bytes read.
  818. *
  819. * If *max_to_read is -1, then decide it ourselves, else go with the
  820. * value passed to us. When returning, if it's changed, subtract the
  821. * number of bytes we read from *max_to_read.
  822. *
  823. * Return -1 if we want to break conn, else return 0.
  824. */
  825. static int connection_read_to_buf(connection_t *conn, int *max_to_read) {
  826. int result, at_most = *max_to_read;
  827. if (at_most == -1) { /* we need to initialize it */
  828. /* how many bytes are we allowed to read? */
  829. at_most = connection_bucket_read_limit(conn);
  830. }
  831. if (connection_speaks_cells(conn) && conn->state != OR_CONN_STATE_CONNECTING) {
  832. int pending;
  833. if (conn->state == OR_CONN_STATE_HANDSHAKING) {
  834. /* continue handshaking even if global token bucket is empty */
  835. return connection_tls_continue_handshake(conn);
  836. }
  837. log_fn(LOG_DEBUG,"%d: starting, inbuf_datalen %d (%d pending in tls object). at_most %d.",
  838. conn->s,(int)buf_datalen(conn->inbuf),tor_tls_get_pending_bytes(conn->tls), at_most);
  839. /* else open, or closing */
  840. result = read_to_buf_tls(conn->tls, at_most, conn->inbuf);
  841. switch (result) {
  842. case TOR_TLS_CLOSE:
  843. log_fn(LOG_INFO,"TLS connection closed on read. Closing. (Nickname %s, address %s",
  844. conn->nickname ? conn->nickname : "not set", conn->address);
  845. return -1;
  846. case TOR_TLS_ERROR:
  847. log_fn(LOG_INFO,"tls error. breaking (nickname %s, address %s).",
  848. conn->nickname ? conn->nickname : "not set", conn->address);
  849. return -1;
  850. case TOR_TLS_WANTWRITE:
  851. connection_start_writing(conn);
  852. return 0;
  853. case TOR_TLS_WANTREAD: /* we're already reading */
  854. case TOR_TLS_DONE: /* no data read, so nothing to process */
  855. result = 0;
  856. break; /* so we call bucket_decrement below */
  857. default:
  858. break;
  859. }
  860. pending = tor_tls_get_pending_bytes(conn->tls);
  861. if (pending) {
  862. /* XXXX If we have any pending bytes, read them now. This *can*
  863. * take us over our read alotment, but really we shouldn't be
  864. * believing that SSL bytes are the same as TCP bytes anyway. */
  865. int r2 = read_to_buf_tls(conn->tls, pending, conn->inbuf);
  866. if (r2<0) {
  867. log_fn(LOG_WARN, "Bug: apparently, reading pending bytes can fail.");
  868. return -1;
  869. } else {
  870. result += r2;
  871. }
  872. }
  873. } else {
  874. result = read_to_buf(conn->s, at_most, conn->inbuf,
  875. &conn->inbuf_reached_eof);
  876. // log_fn(LOG_DEBUG,"read_to_buf returned %d.",read_result);
  877. if (result < 0)
  878. return -1;
  879. }
  880. if (result > 0) { /* change *max_to_read */
  881. *max_to_read = at_most - result;
  882. }
  883. if (result > 0 && !is_local_IP(conn->addr)) { /* remember it */
  884. rep_hist_note_bytes_read(result, time(NULL));
  885. connection_read_bucket_decrement(conn, result);
  886. }
  887. /* Call even if result is 0, since the global read bucket may
  888. * have reached 0 on a different conn, and this guy needs to
  889. * know to stop reading. */
  890. connection_consider_empty_buckets(conn);
  891. return 0;
  892. }
  893. /** A pass-through to fetch_from_buf. */
  894. int connection_fetch_from_buf(char *string, size_t len, connection_t *conn) {
  895. return fetch_from_buf(string, len, conn->inbuf);
  896. }
  897. /** Return conn-\>outbuf_flushlen: how many bytes conn wants to flush
  898. * from its outbuf. */
  899. int connection_wants_to_flush(connection_t *conn) {
  900. return conn->outbuf_flushlen;
  901. }
  902. /** Are there too many bytes on edge connection <b>conn</b>'s outbuf to
  903. * send back a relay-level sendme yet? Return 1 if so, 0 if not. Used by
  904. * connection_edge_consider_sending_sendme().
  905. */
  906. int connection_outbuf_too_full(connection_t *conn) {
  907. return (conn->outbuf_flushlen > 10*CELL_PAYLOAD_SIZE);
  908. }
  909. /** Try to flush more bytes onto conn-\>s.
  910. *
  911. * This function gets called either from conn_write() in main.c
  912. * when poll() has declared that conn wants to write, or below
  913. * from connection_write_to_buf() when an entire TLS record is ready.
  914. *
  915. * Update conn-\>timestamp_lastwritten to now, and call flush_buf
  916. * or flush_buf_tls appropriately. If it succeeds and there no more
  917. * more bytes on conn->outbuf, then call connection_finished_flushing
  918. * on it too.
  919. *
  920. * Mark the connection and return -1 if you want to close it, else
  921. * return 0.
  922. */
  923. int connection_handle_write(connection_t *conn) {
  924. int e, len=sizeof(e);
  925. int result;
  926. time_t now = time(NULL);
  927. tor_assert(!connection_is_listener(conn));
  928. conn->timestamp_lastwritten = now;
  929. /* Sometimes, "writable" means "connected". */
  930. if (connection_state_is_connecting(conn)) {
  931. if (getsockopt(conn->s, SOL_SOCKET, SO_ERROR, (void*)&e, &len) < 0) {
  932. log_fn(LOG_WARN,"getsockopt() syscall failed?! Please report to tor-ops.");
  933. connection_close_immediate(conn);
  934. connection_mark_for_close(conn);
  935. return -1;
  936. }
  937. if (e) {
  938. /* some sort of error, but maybe just inprogress still */
  939. if (!ERRNO_IS_CONN_EINPROGRESS(e)) {
  940. log_fn(LOG_INFO,"in-progress connect failed. Removing.");
  941. connection_close_immediate(conn);
  942. connection_mark_for_close(conn);
  943. /* it's safe to pass OPs to router_mark_as_down(), since it just
  944. * ignores unrecognized routers
  945. */
  946. if (conn->type == CONN_TYPE_OR)
  947. router_mark_as_down(conn->identity_digest);
  948. return -1;
  949. } else {
  950. return 0; /* no change, see if next time is better */
  951. }
  952. }
  953. /* The connection is successful. */
  954. return connection_finished_connecting(conn);
  955. }
  956. if (connection_speaks_cells(conn)) {
  957. if (conn->state == OR_CONN_STATE_HANDSHAKING) {
  958. connection_stop_writing(conn);
  959. if (connection_tls_continue_handshake(conn) < 0) {
  960. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  961. connection_mark_for_close(conn);
  962. return -1;
  963. }
  964. return 0;
  965. }
  966. /* else open, or closing */
  967. result = flush_buf_tls(conn->tls, conn->outbuf, &conn->outbuf_flushlen);
  968. switch (result) {
  969. case TOR_TLS_ERROR:
  970. case TOR_TLS_CLOSE:
  971. log_fn(LOG_INFO,result==TOR_TLS_ERROR?
  972. "tls error. breaking.":"TLS connection closed on flush");
  973. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  974. connection_mark_for_close(conn);
  975. return -1;
  976. case TOR_TLS_WANTWRITE:
  977. log_fn(LOG_DEBUG,"wanted write.");
  978. /* we're already writing */
  979. return 0;
  980. case TOR_TLS_WANTREAD:
  981. /* Make sure to avoid a loop if the receive buckets are empty. */
  982. log_fn(LOG_DEBUG,"wanted read.");
  983. if (!connection_is_reading(conn)) {
  984. connection_stop_writing(conn);
  985. conn->wants_to_write = 1;
  986. /* we'll start reading again when the next second arrives,
  987. * and then also start writing again.
  988. */
  989. }
  990. /* else no problem, we're already reading */
  991. return 0;
  992. /* case TOR_TLS_DONE:
  993. * for TOR_TLS_DONE, fall through to check if the flushlen
  994. * is empty, so we can stop writing.
  995. */
  996. }
  997. } else {
  998. result = flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen);
  999. if (result < 0) {
  1000. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  1001. conn->has_sent_end = 1;
  1002. connection_mark_for_close(conn);
  1003. return -1;
  1004. }
  1005. }
  1006. if (result > 0 && !is_local_IP(conn->addr)) { /* remember it */
  1007. rep_hist_note_bytes_written(result, now);
  1008. global_write_bucket -= result;
  1009. }
  1010. if (!connection_wants_to_flush(conn)) { /* it's done flushing */
  1011. if (connection_finished_flushing(conn) < 0) {
  1012. /* already marked */
  1013. return -1;
  1014. }
  1015. }
  1016. return 0;
  1017. }
  1018. /** Append <b>len</b> bytes of <b>string</b> onto <b>conn</b>'s
  1019. * outbuf, and ask it to start writing.
  1020. */
  1021. void connection_write_to_buf(const char *string, size_t len, connection_t *conn) {
  1022. if (!len)
  1023. return;
  1024. /* if it's marked for close, only allow write if we mean to flush it */
  1025. if (conn->marked_for_close && !conn->hold_open_until_flushed)
  1026. return;
  1027. if (write_to_buf(string, len, conn->outbuf) < 0) {
  1028. if (conn->type == CONN_TYPE_AP || conn->type == CONN_TYPE_EXIT) {
  1029. /* if it failed, it means we have our package/delivery windows set
  1030. wrong compared to our max outbuf size. close the whole circuit. */
  1031. log_fn(LOG_WARN,"write_to_buf failed. Closing circuit (fd %d).", conn->s);
  1032. circuit_mark_for_close(circuit_get_by_conn(conn));
  1033. } else {
  1034. log_fn(LOG_WARN,"write_to_buf failed. Closing connection (fd %d).", conn->s);
  1035. connection_mark_for_close(conn);
  1036. }
  1037. return;
  1038. }
  1039. connection_start_writing(conn);
  1040. conn->outbuf_flushlen += len;
  1041. }
  1042. /** Return the conn to addr/port that has the most recent
  1043. * timestamp_created, or NULL if no such conn exists. */
  1044. connection_t *connection_exact_get_by_addr_port(uint32_t addr, uint16_t port) {
  1045. int i, n;
  1046. connection_t *conn, *best=NULL;
  1047. connection_t **carray;
  1048. get_connection_array(&carray,&n);
  1049. for (i=0;i<n;i++) {
  1050. conn = carray[i];
  1051. if (conn->addr == addr && conn->port == port && !conn->marked_for_close &&
  1052. (!best || best->timestamp_created < conn->timestamp_created))
  1053. best = conn;
  1054. }
  1055. return best;
  1056. }
  1057. connection_t *connection_get_by_identity_digest(const char *digest, int type)
  1058. {
  1059. int i, n;
  1060. connection_t *conn, *best=NULL;
  1061. connection_t **carray;
  1062. get_connection_array(&carray,&n);
  1063. for (i=0;i<n;i++) {
  1064. conn = carray[i];
  1065. if (conn->type != type)
  1066. continue;
  1067. if (!memcmp(conn->identity_digest, digest, DIGEST_LEN) &&
  1068. !conn->marked_for_close &&
  1069. (!best || best->timestamp_created < conn->timestamp_created))
  1070. best = conn;
  1071. }
  1072. return best;
  1073. }
  1074. /** Return a connection of type <b>type</b> that is not marked for
  1075. * close.
  1076. */
  1077. connection_t *connection_get_by_type(int type) {
  1078. int i, n;
  1079. connection_t *conn;
  1080. connection_t **carray;
  1081. get_connection_array(&carray,&n);
  1082. for (i=0;i<n;i++) {
  1083. conn = carray[i];
  1084. if (conn->type == type && !conn->marked_for_close)
  1085. return conn;
  1086. }
  1087. return NULL;
  1088. }
  1089. /** Return a connection of type <b>type</b> that is in state <b>state</b>,
  1090. * and that is not marked for close.
  1091. */
  1092. connection_t *connection_get_by_type_state(int type, int state) {
  1093. int i, n;
  1094. connection_t *conn;
  1095. connection_t **carray;
  1096. get_connection_array(&carray,&n);
  1097. for (i=0;i<n;i++) {
  1098. conn = carray[i];
  1099. if (conn->type == type && conn->state == state && !conn->marked_for_close)
  1100. return conn;
  1101. }
  1102. return NULL;
  1103. }
  1104. /** Return the connection of type <b>type</b> that is in state
  1105. * <b>state</b>, that was written to least recently, and that is not
  1106. * marked for close.
  1107. */
  1108. connection_t *connection_get_by_type_state_lastwritten(int type, int state) {
  1109. int i, n;
  1110. connection_t *conn, *best=NULL;
  1111. connection_t **carray;
  1112. get_connection_array(&carray,&n);
  1113. for (i=0;i<n;i++) {
  1114. conn = carray[i];
  1115. if (conn->type == type && conn->state == state && !conn->marked_for_close)
  1116. if (!best || conn->timestamp_lastwritten < best->timestamp_lastwritten)
  1117. best = conn;
  1118. }
  1119. return best;
  1120. }
  1121. /** Return a connection of type <b>type</b> that has rendquery equal
  1122. * to <b>rendquery</b>, and that is not marked for close. If state
  1123. * is non-zero, conn must be of that state too.
  1124. */
  1125. connection_t *
  1126. connection_get_by_type_state_rendquery(int type, int state, const char *rendquery) {
  1127. int i, n;
  1128. connection_t *conn;
  1129. connection_t **carray;
  1130. get_connection_array(&carray,&n);
  1131. for (i=0;i<n;i++) {
  1132. conn = carray[i];
  1133. if (conn->type == type &&
  1134. !conn->marked_for_close &&
  1135. (!state || state == conn->state) &&
  1136. !rend_cmp_service_ids(rendquery, conn->rend_query))
  1137. return conn;
  1138. }
  1139. return NULL;
  1140. }
  1141. /** Return 1 if <b>conn</b> is a listener conn, else return 0. */
  1142. int connection_is_listener(connection_t *conn) {
  1143. if (conn->type == CONN_TYPE_OR_LISTENER ||
  1144. conn->type == CONN_TYPE_AP_LISTENER ||
  1145. conn->type == CONN_TYPE_DIR_LISTENER ||
  1146. conn->type == CONN_TYPE_CONTROL_LISTENER)
  1147. return 1;
  1148. return 0;
  1149. }
  1150. /** Return 1 if <b>conn</b> is in state "open" and is not marked
  1151. * for close, else return 0.
  1152. */
  1153. int connection_state_is_open(connection_t *conn) {
  1154. tor_assert(conn);
  1155. if (conn->marked_for_close)
  1156. return 0;
  1157. if ((conn->type == CONN_TYPE_OR && conn->state == OR_CONN_STATE_OPEN) ||
  1158. (conn->type == CONN_TYPE_AP && conn->state == AP_CONN_STATE_OPEN) ||
  1159. (conn->type == CONN_TYPE_EXIT && conn->state == EXIT_CONN_STATE_OPEN) ||
  1160. (conn->type == CONN_TYPE_CONTROL && conn->state ==CONTROL_CONN_STATE_OPEN))
  1161. return 1;
  1162. return 0;
  1163. }
  1164. /** Return 1 if conn is in 'connecting' state, else return 0. */
  1165. int connection_state_is_connecting(connection_t *conn) {
  1166. tor_assert(conn);
  1167. if (conn->marked_for_close)
  1168. return 0;
  1169. switch (conn->type)
  1170. {
  1171. case CONN_TYPE_OR:
  1172. return conn->state == OR_CONN_STATE_CONNECTING;
  1173. case CONN_TYPE_EXIT:
  1174. return conn->state == EXIT_CONN_STATE_CONNECTING;
  1175. case CONN_TYPE_DIR:
  1176. return conn->state == DIR_CONN_STATE_CONNECTING;
  1177. }
  1178. return 0;
  1179. }
  1180. /** Write a destroy cell with circ ID <b>circ_id</b> onto OR connection
  1181. * <b>conn</b>.
  1182. *
  1183. * Return 0.
  1184. */
  1185. int connection_send_destroy(uint16_t circ_id, connection_t *conn) {
  1186. cell_t cell;
  1187. tor_assert(conn);
  1188. tor_assert(connection_speaks_cells(conn));
  1189. memset(&cell, 0, sizeof(cell_t));
  1190. cell.circ_id = circ_id;
  1191. cell.command = CELL_DESTROY;
  1192. log_fn(LOG_INFO,"Sending destroy (circID %d).", circ_id);
  1193. connection_or_write_cell_to_buf(&cell, conn);
  1194. return 0;
  1195. }
  1196. /** Process new bytes that have arrived on conn-\>inbuf.
  1197. *
  1198. * This function just passes conn to the connection-specific
  1199. * connection_*_process_inbuf() function. It also passes in
  1200. * package_partial if wanted.
  1201. */
  1202. static int connection_process_inbuf(connection_t *conn, int package_partial) {
  1203. tor_assert(conn);
  1204. switch (conn->type) {
  1205. case CONN_TYPE_OR:
  1206. return connection_or_process_inbuf(conn);
  1207. case CONN_TYPE_EXIT:
  1208. case CONN_TYPE_AP:
  1209. return connection_edge_process_inbuf(conn, package_partial);
  1210. case CONN_TYPE_DIR:
  1211. return connection_dir_process_inbuf(conn);
  1212. case CONN_TYPE_DNSWORKER:
  1213. return connection_dns_process_inbuf(conn);
  1214. case CONN_TYPE_CPUWORKER:
  1215. return connection_cpu_process_inbuf(conn);
  1216. case CONN_TYPE_CONTROL:
  1217. return connection_control_process_inbuf(conn);
  1218. default:
  1219. log_fn(LOG_WARN,"Bug: got unexpected conn type %d.", conn->type);
  1220. return -1;
  1221. }
  1222. }
  1223. /** We just finished flushing bytes from conn-\>outbuf, and there
  1224. * are no more bytes remaining.
  1225. *
  1226. * This function just passes conn to the connection-specific
  1227. * connection_*_finished_flushing() function.
  1228. */
  1229. static int connection_finished_flushing(connection_t *conn) {
  1230. tor_assert(conn);
  1231. // log_fn(LOG_DEBUG,"entered. Socket %u.", conn->s);
  1232. switch (conn->type) {
  1233. case CONN_TYPE_OR:
  1234. return connection_or_finished_flushing(conn);
  1235. case CONN_TYPE_AP:
  1236. case CONN_TYPE_EXIT:
  1237. return connection_edge_finished_flushing(conn);
  1238. case CONN_TYPE_DIR:
  1239. return connection_dir_finished_flushing(conn);
  1240. case CONN_TYPE_DNSWORKER:
  1241. return connection_dns_finished_flushing(conn);
  1242. case CONN_TYPE_CPUWORKER:
  1243. return connection_cpu_finished_flushing(conn);
  1244. case CONN_TYPE_CONTROL:
  1245. return connection_control_finished_flushing(conn);
  1246. default:
  1247. log_fn(LOG_WARN,"Bug: got unexpected conn type %d.", conn->type);
  1248. return -1;
  1249. }
  1250. }
  1251. /** Called when our attempt to connect() to another server has just
  1252. * succeeded.
  1253. *
  1254. * This function just passes conn to the connection-specific
  1255. * connection_*_finished_connecting() function.
  1256. */
  1257. static int connection_finished_connecting(connection_t *conn)
  1258. {
  1259. tor_assert(conn);
  1260. switch (conn->type)
  1261. {
  1262. case CONN_TYPE_OR:
  1263. return connection_or_finished_connecting(conn);
  1264. case CONN_TYPE_EXIT:
  1265. return connection_edge_finished_connecting(conn);
  1266. case CONN_TYPE_DIR:
  1267. return connection_dir_finished_connecting(conn);
  1268. default:
  1269. log_fn(LOG_WARN,"Bug: got unexpected conn type %d.", conn->type);
  1270. return -1;
  1271. }
  1272. }
  1273. static int connection_reached_eof(connection_t *conn)
  1274. {
  1275. switch (conn->type) {
  1276. case CONN_TYPE_OR:
  1277. return connection_or_reached_eof(conn);
  1278. case CONN_TYPE_AP:
  1279. case CONN_TYPE_EXIT:
  1280. return connection_edge_reached_eof(conn);
  1281. case CONN_TYPE_DIR:
  1282. return connection_dir_reached_eof(conn);
  1283. case CONN_TYPE_DNSWORKER:
  1284. return connection_dns_reached_eof(conn);
  1285. case CONN_TYPE_CPUWORKER:
  1286. return connection_cpu_reached_eof(conn);
  1287. case CONN_TYPE_CONTROL:
  1288. return connection_control_reached_eof(conn);
  1289. default:
  1290. log_fn(LOG_WARN,"Bug: got unexpected conn type %d.", conn->type);
  1291. return -1;
  1292. }
  1293. }
  1294. /** Verify that connection <b>conn</b> has all of its invariants
  1295. * correct. Trigger an assert if anything is invalid.
  1296. */
  1297. void assert_connection_ok(connection_t *conn, time_t now)
  1298. {
  1299. tor_assert(conn);
  1300. tor_assert(conn->magic == CONNECTION_MAGIC);
  1301. tor_assert(conn->type >= _CONN_TYPE_MIN);
  1302. tor_assert(conn->type <= _CONN_TYPE_MAX);
  1303. if (conn->outbuf_flushlen > 0) {
  1304. tor_assert(connection_is_writing(conn) || conn->wants_to_write);
  1305. }
  1306. if (conn->hold_open_until_flushed)
  1307. tor_assert(conn->marked_for_close);
  1308. /* XXX check: wants_to_read, wants_to_write, s, poll_index,
  1309. * marked_for_close. */
  1310. /* buffers */
  1311. if (!connection_is_listener(conn)) {
  1312. assert_buf_ok(conn->inbuf);
  1313. assert_buf_ok(conn->outbuf);
  1314. }
  1315. #if 0 /* computers often go back in time; no way to know */
  1316. tor_assert(!now || conn->timestamp_lastread <= now);
  1317. tor_assert(!now || conn->timestamp_lastwritten <= now);
  1318. tor_assert(conn->timestamp_created <= conn->timestamp_lastread);
  1319. tor_assert(conn->timestamp_created <= conn->timestamp_lastwritten);
  1320. #endif
  1321. /* XXX Fix this; no longer so.*/
  1322. #if 0
  1323. if (conn->type != CONN_TYPE_OR && conn->type != CONN_TYPE_DIR)
  1324. tor_assert(!conn->pkey);
  1325. /* pkey is set if we're a dir client, or if we're an OR in state OPEN
  1326. * connected to another OR.
  1327. */
  1328. #endif
  1329. if (conn->type != CONN_TYPE_OR) {
  1330. tor_assert(!conn->tls);
  1331. } else {
  1332. if (conn->state == OR_CONN_STATE_OPEN) {
  1333. /* tor_assert(conn->bandwidth > 0); */
  1334. /* the above isn't necessarily true: if we just did a TLS
  1335. * handshake but we didn't recognize the other peer, or it
  1336. * gave a bad cert/etc, then we won't have assigned bandwidth,
  1337. * yet it will be open. -RD
  1338. */
  1339. // tor_assert(conn->receiver_bucket >= 0);
  1340. }
  1341. tor_assert(conn->addr && conn->port);
  1342. tor_assert(conn->address);
  1343. if (conn->state != OR_CONN_STATE_CONNECTING)
  1344. tor_assert(conn->tls);
  1345. }
  1346. if (conn->type != CONN_TYPE_EXIT && conn->type != CONN_TYPE_AP) {
  1347. tor_assert(!conn->stream_id);
  1348. tor_assert(!conn->next_stream);
  1349. tor_assert(!conn->cpath_layer);
  1350. tor_assert(!conn->package_window);
  1351. tor_assert(!conn->deliver_window);
  1352. tor_assert(!conn->done_sending);
  1353. tor_assert(!conn->done_receiving);
  1354. } else {
  1355. /* XXX unchecked: package window, deliver window. */
  1356. }
  1357. if (conn->type == CONN_TYPE_AP) {
  1358. tor_assert(conn->socks_request);
  1359. if (conn->state == AP_CONN_STATE_OPEN) {
  1360. tor_assert(conn->socks_request->has_finished);
  1361. tor_assert(conn->cpath_layer);
  1362. assert_cpath_layer_ok(conn->cpath_layer);
  1363. }
  1364. } else {
  1365. tor_assert(!conn->socks_request);
  1366. }
  1367. if (conn->type == CONN_TYPE_EXIT) {
  1368. tor_assert(conn->purpose == EXIT_PURPOSE_CONNECT ||
  1369. conn->purpose == EXIT_PURPOSE_RESOLVE);
  1370. } else if (conn->type != CONN_TYPE_DIR) {
  1371. tor_assert(!conn->purpose); /* only used for dir types currently */
  1372. }
  1373. switch (conn->type)
  1374. {
  1375. case CONN_TYPE_OR_LISTENER:
  1376. case CONN_TYPE_AP_LISTENER:
  1377. case CONN_TYPE_DIR_LISTENER:
  1378. case CONN_TYPE_CONTROL_LISTENER:
  1379. tor_assert(conn->state == LISTENER_STATE_READY);
  1380. break;
  1381. case CONN_TYPE_OR:
  1382. tor_assert(conn->state >= _OR_CONN_STATE_MIN);
  1383. tor_assert(conn->state <= _OR_CONN_STATE_MAX);
  1384. break;
  1385. case CONN_TYPE_EXIT:
  1386. tor_assert(conn->state >= _EXIT_CONN_STATE_MIN);
  1387. tor_assert(conn->state <= _EXIT_CONN_STATE_MAX);
  1388. break;
  1389. case CONN_TYPE_AP:
  1390. tor_assert(conn->state >= _AP_CONN_STATE_MIN);
  1391. tor_assert(conn->state <= _AP_CONN_STATE_MAX);
  1392. tor_assert(conn->socks_request);
  1393. break;
  1394. case CONN_TYPE_DIR:
  1395. tor_assert(conn->state >= _DIR_CONN_STATE_MIN);
  1396. tor_assert(conn->state <= _DIR_CONN_STATE_MAX);
  1397. tor_assert(conn->purpose >= _DIR_PURPOSE_MIN);
  1398. tor_assert(conn->purpose <= _DIR_PURPOSE_MAX);
  1399. break;
  1400. case CONN_TYPE_DNSWORKER:
  1401. tor_assert(conn->state == DNSWORKER_STATE_IDLE ||
  1402. conn->state == DNSWORKER_STATE_BUSY);
  1403. break;
  1404. case CONN_TYPE_CPUWORKER:
  1405. tor_assert(conn->state >= _CPUWORKER_STATE_MIN);
  1406. tor_assert(conn->state <= _CPUWORKER_STATE_MAX);
  1407. break;
  1408. case CONN_TYPE_CONTROL:
  1409. tor_assert(conn->state >= _CONTROL_CONN_STATE_MIN);
  1410. tor_assert(conn->state <= _CONTROL_CONN_STATE_MAX);
  1411. break;
  1412. default:
  1413. tor_assert(0);
  1414. }
  1415. }