connection.c 42 KB

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