connection.c 43 KB

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