connection.c 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369
  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. if(conn->state == OR_CONN_STATE_OPEN)
  128. directory_set_dirty();
  129. if (conn->tls)
  130. tor_tls_free(conn->tls);
  131. }
  132. if (conn->identity_pkey)
  133. crypto_free_pk_env(conn->identity_pkey);
  134. tor_free(conn->nickname);
  135. tor_free(conn->socks_request);
  136. if(conn->s >= 0) {
  137. log_fn(LOG_INFO,"closing fd %d.",conn->s);
  138. tor_close_socket(conn->s);
  139. }
  140. memset(conn, 0xAA, sizeof(connection_t)); /* poison memory */
  141. tor_free(conn);
  142. }
  143. /** Call connection_free() on every connection in our array.
  144. * This is used by cpuworkers and dnsworkers when they fork,
  145. * so they don't keep resources held open (especially sockets).
  146. */
  147. void connection_free_all(void) {
  148. int i, n;
  149. connection_t **carray;
  150. get_connection_array(&carray,&n);
  151. for(i=0;i<n;i++)
  152. connection_free(carray[i]);
  153. }
  154. void connection_about_to_close_connection(connection_t *conn)
  155. {
  156. assert(conn->marked_for_close);
  157. if(conn->type == CONN_TYPE_AP || conn->type == CONN_TYPE_EXIT) {
  158. if(!conn->has_sent_end)
  159. log_fn(LOG_WARN,"Edge connection hasn't sent end yet? Bug.");
  160. }
  161. switch(conn->type) {
  162. case CONN_TYPE_DIR:
  163. if(conn->purpose == DIR_PURPOSE_FETCH_RENDDESC)
  164. rend_client_desc_fetched(conn->rend_query, 0);
  165. break;
  166. case CONN_TYPE_OR:
  167. /* Remember why we're closing this connection. */
  168. if (conn->state != OR_CONN_STATE_OPEN) {
  169. /* XXX Nick: this still isn't right, because it might be
  170. * dying even though we didn't initiate the connect. Can
  171. * you look at this more? -RD XXXX008 -NM*/
  172. /* XXX We only set conn->nickname when we initiate the connection, or
  173. * when the handshake is complete; so conn->nickname is a good test
  174. * for "we initiated the connection", right? -NM */
  175. */
  176. if(conn->nickname)
  177. rep_hist_note_connect_failed(conn->identity_digest, time(NULL));
  178. } else if (0) { // XXX reason == CLOSE_REASON_UNUSED_OR_CONN) {
  179. rep_hist_note_disconnect(conn->identity_digest, time(NULL));
  180. } else if(conn->identity_digest) {
  181. rep_hist_note_connection_died(conn->identity_digest, time(NULL));
  182. }
  183. break;
  184. case CONN_TYPE_AP:
  185. if (conn->socks_request->has_finished == 0) {
  186. log_fn(LOG_INFO,"Cleaning up AP -- sending socks reject.");
  187. connection_ap_handshake_socks_reply(conn, NULL, 0, 0);
  188. conn->socks_request->has_finished = 1;
  189. conn->hold_open_until_flushed = 1;
  190. }
  191. break;
  192. case CONN_TYPE_EXIT:
  193. if (conn->state == EXIT_CONN_STATE_RESOLVING) {
  194. circuit_detach_stream(circuit_get_by_conn(conn), conn);
  195. connection_dns_remove(conn);
  196. }
  197. break;
  198. case CONN_TYPE_DNSWORKER:
  199. if (conn->state == DNSWORKER_STATE_BUSY) {
  200. dns_cancel_pending_resolve(conn->address);
  201. }
  202. break;
  203. }
  204. }
  205. /** Close the underlying socket for <b>conn</b>, so we don't try to
  206. * flush it. Must be used in conjunction with (right before)
  207. * connection_mark_for_close().
  208. */
  209. void connection_close_immediate(connection_t *conn)
  210. {
  211. assert_connection_ok(conn,0);
  212. if (conn->s < 0) {
  213. log_fn(LOG_WARN,"Attempt to close already-closed connection.");
  214. return;
  215. }
  216. if (conn->outbuf_flushlen) {
  217. log_fn(LOG_INFO,"fd %d, type %s, state %d, %d bytes on outbuf.",
  218. conn->s, CONN_TYPE_TO_STRING(conn->type),
  219. conn->state, conn->outbuf_flushlen);
  220. }
  221. tor_close_socket(conn->s);
  222. conn->s = -1;
  223. if(!connection_is_listener(conn)) {
  224. buf_clear(conn->outbuf);
  225. conn->outbuf_flushlen = 0;
  226. }
  227. }
  228. /** Mark <b>conn</b> to be closed next time we loop through
  229. * conn_close_if_marked() in main.c. Do any cleanup needed:
  230. * - Directory conns that fail to fetch a rendezvous descriptor need
  231. * to inform pending rendezvous streams.
  232. * - OR conns need to call rep_hist_note_*() to record status.
  233. * - AP conns need to send a socks reject if necessary.
  234. * - Exit conns need to call connection_dns_remove() if necessary.
  235. * - AP and Exit conns need to send an end cell if they can.
  236. * - DNS conns need to fail any resolves that are pending on them.
  237. */
  238. int
  239. _connection_mark_for_close(connection_t *conn)
  240. {
  241. assert_connection_ok(conn,0);
  242. if (conn->marked_for_close) {
  243. log(LOG_WARN, "Double mark-for-close on connection.");
  244. return -1;
  245. }
  246. conn->marked_for_close = 1;
  247. /* in case we're going to be held-open-til-flushed, reset
  248. * the number of seconds since last successful write, so
  249. * we get our whole 15 seconds */
  250. conn->timestamp_lastwritten = time(NULL);
  251. return 0;
  252. }
  253. /** Find each connection that has hold_open_until_flushed set to
  254. * 1 but hasn't written in the past 15 seconds, and set
  255. * hold_open_until_flushed to 0. This means it will get cleaned
  256. * up in the next loop through close_if_marked() in main.c.
  257. */
  258. void connection_expire_held_open(void)
  259. {
  260. connection_t **carray, *conn;
  261. int n, i;
  262. time_t now;
  263. now = time(NULL);
  264. get_connection_array(&carray, &n);
  265. for (i = 0; i < n; ++i) {
  266. conn = carray[i];
  267. /* If we've been holding the connection open, but we haven't written
  268. * for 15 seconds...
  269. */
  270. if (conn->hold_open_until_flushed) {
  271. tor_assert(conn->marked_for_close);
  272. if (now - conn->timestamp_lastwritten >= 15) {
  273. log_fn(LOG_WARN,"Giving up on marked_for_close conn that's been flushing for 15s (fd %d, type %s, state %d).",
  274. conn->s, CONN_TYPE_TO_STRING(conn->type), conn->state);
  275. conn->hold_open_until_flushed = 0;
  276. }
  277. }
  278. }
  279. }
  280. /** Bind a new non-blocking socket listening to
  281. * <b>bindaddress</b>:<b>bindport</b>, and add this new connection
  282. * (of type <b>type</b>) to the connection array.
  283. *
  284. * If <b>bindaddress</b> includes a port, we bind on that port; otherwise, we
  285. * use bindport.
  286. */
  287. static int connection_create_listener(const char *bindaddress, uint16_t bindport, int type) {
  288. struct sockaddr_in bindaddr; /* where to bind */
  289. connection_t *conn;
  290. uint16_t usePort;
  291. int s; /* the socket we're going to make */
  292. int one=1;
  293. memset(&bindaddr,0,sizeof(struct sockaddr_in));
  294. if (parse_addr_port(bindaddress, NULL, &(bindaddr.sin_addr.s_addr),
  295. &usePort)<0) {
  296. log_fn(LOG_WARN, "Error parsing/resolving BindAddress %s",bindaddress);
  297. return -1;
  298. }
  299. if (usePort==0)
  300. usePort = bindport;
  301. bindaddr.sin_family = AF_INET;
  302. bindaddr.sin_port = htons((uint16_t) usePort);
  303. s = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
  304. if (s < 0) {
  305. log_fn(LOG_WARN,"Socket creation failed.");
  306. return -1;
  307. }
  308. setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void*) &one, sizeof(one));
  309. if(bind(s,(struct sockaddr *)&bindaddr,sizeof(bindaddr)) < 0) {
  310. log_fn(LOG_WARN,"Could not bind to port %u: %s",usePort,
  311. tor_socket_strerror(tor_socket_errno(s)));
  312. return -1;
  313. }
  314. if(listen(s,SOMAXCONN) < 0) {
  315. log_fn(LOG_WARN,"Could not listen on port %u: %s",usePort,
  316. tor_socket_strerror(tor_socket_errno(s)));
  317. return -1;
  318. }
  319. set_socket_nonblocking(s);
  320. conn = connection_new(type);
  321. conn->s = s;
  322. if(connection_add(conn) < 0) { /* no space, forget it */
  323. log_fn(LOG_WARN,"connection_add failed. Giving up.");
  324. connection_free(conn);
  325. return -1;
  326. }
  327. log_fn(LOG_DEBUG,"%s listening on port %u.",conn_type_to_string[type], usePort);
  328. conn->state = LISTENER_STATE_READY;
  329. connection_start_reading(conn);
  330. return 0;
  331. }
  332. /** The listener connection <b>conn</b> told poll() it wanted to read.
  333. * Call accept() on conn-\>s, and add the new connection if necessary.
  334. */
  335. static int connection_handle_listener_read(connection_t *conn, int new_type) {
  336. int news; /* the new socket */
  337. connection_t *newconn;
  338. struct sockaddr_in remote; /* information about the remote peer when connecting to other routers */
  339. int remotelen = sizeof(struct sockaddr_in); /* length of the remote address */
  340. news = accept(conn->s,(struct sockaddr *)&remote,&remotelen);
  341. if (news == -1) { /* accept() error */
  342. if(ERRNO_IS_EAGAIN(tor_socket_errno(conn->s))) {
  343. return 0; /* he hung up before we could accept(). that's fine. */
  344. }
  345. /* else there was a real error. */
  346. log_fn(LOG_WARN,"accept() failed. Closing listener.");
  347. connection_mark_for_close(conn);
  348. return -1;
  349. }
  350. log(LOG_INFO,"Connection accepted on socket %d (child of fd %d).",news, conn->s);
  351. if(shutting_down && new_type != CONN_TYPE_DIR) {
  352. /* allow directory connections even while we're shutting down */
  353. log(LOG_INFO,"But we're shutting down, so closing (type %d).", new_type);
  354. tor_close_socket(news);
  355. return 0;
  356. }
  357. set_socket_nonblocking(news);
  358. /* process entrance policies here, before we even create the connection */
  359. if(new_type == CONN_TYPE_AP) {
  360. /* check sockspolicy to see if we should accept it */
  361. if(socks_policy_permits_address(ntohl(remote.sin_addr.s_addr)) == 0) {
  362. log_fn(LOG_WARN,"Denying socks connection from untrusted address %s.",
  363. inet_ntoa(remote.sin_addr));
  364. tor_close_socket(news);
  365. return 0;
  366. }
  367. }
  368. newconn = connection_new(new_type);
  369. newconn->s = news;
  370. newconn->address = tor_strdup(inet_ntoa(remote.sin_addr)); /* remember the remote address */
  371. newconn->addr = ntohl(remote.sin_addr.s_addr);
  372. newconn->port = ntohs(remote.sin_port);
  373. if(connection_add(newconn) < 0) { /* no space, forget it */
  374. connection_free(newconn);
  375. return 0; /* no need to tear down the parent */
  376. }
  377. if(connection_init_accepted_conn(newconn) < 0) {
  378. connection_mark_for_close(newconn);
  379. return 0;
  380. }
  381. return 0;
  382. }
  383. /** Initialize states for newly accepted connection <b>conn</b>.
  384. * If conn is an OR, start the tls handshake.
  385. */
  386. static int connection_init_accepted_conn(connection_t *conn) {
  387. connection_start_reading(conn);
  388. switch(conn->type) {
  389. case CONN_TYPE_OR:
  390. return connection_tls_start_handshake(conn, 1);
  391. case CONN_TYPE_AP:
  392. conn->state = AP_CONN_STATE_SOCKS_WAIT;
  393. break;
  394. case CONN_TYPE_DIR:
  395. conn->purpose = DIR_PURPOSE_SERVER;
  396. conn->state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
  397. break;
  398. }
  399. return 0;
  400. }
  401. /** Take conn, make a nonblocking socket; try to connect to
  402. * addr:port (they arrive in *host order*). If fail, return -1. Else
  403. * assign s to conn->\s: if connected return 1, if EAGAIN return 0.
  404. *
  405. * address is used to make the logs useful.
  406. *
  407. * On success, add conn to the list of polled connections.
  408. */
  409. int connection_connect(connection_t *conn, char *address, uint32_t addr, uint16_t port) {
  410. int s;
  411. struct sockaddr_in dest_addr;
  412. s=socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
  413. if (s < 0) {
  414. log_fn(LOG_WARN,"Error creating network socket: %s",
  415. tor_socket_strerror(tor_socket_errno(-1)));
  416. return -1;
  417. }
  418. if (options.OutboundBindAddress) {
  419. struct sockaddr_in ext_addr;
  420. memset(&ext_addr, 0, sizeof(ext_addr));
  421. ext_addr.sin_family = AF_INET;
  422. ext_addr.sin_port = 0;
  423. if (!tor_inet_aton(options.OutboundBindAddress, &ext_addr.sin_addr)) {
  424. log_fn(LOG_WARN,"Outbound bind address '%s' didn't parse. Ignoring.",
  425. options.OutboundBindAddress);
  426. } else {
  427. if(bind(s, (struct sockaddr*)&ext_addr, sizeof(ext_addr)) < 0) {
  428. log_fn(LOG_WARN,"Error binding network socket: %s",
  429. tor_socket_strerror(tor_socket_errno(s)));
  430. return -1;
  431. }
  432. }
  433. }
  434. set_socket_nonblocking(s);
  435. memset(&dest_addr,0,sizeof(dest_addr));
  436. dest_addr.sin_family = AF_INET;
  437. dest_addr.sin_port = htons(port);
  438. dest_addr.sin_addr.s_addr = htonl(addr);
  439. log_fn(LOG_DEBUG,"Connecting to %s:%u.",address,port);
  440. if(connect(s,(struct sockaddr *)&dest_addr,sizeof(dest_addr)) < 0) {
  441. if(!ERRNO_IS_CONN_EINPROGRESS(tor_socket_errno(s))) {
  442. /* yuck. kill it. */
  443. log_fn(LOG_INFO,"Connect() to %s:%u failed: %s",address,port,
  444. tor_socket_strerror(tor_socket_errno(s)));
  445. tor_close_socket(s);
  446. return -1;
  447. } else {
  448. /* it's in progress. set state appropriately and return. */
  449. conn->s = s;
  450. if(connection_add(conn) < 0) /* no space, forget it */
  451. return -1;
  452. log_fn(LOG_DEBUG,"connect in progress, socket %d.",s);
  453. return 0;
  454. }
  455. }
  456. /* it succeeded. we're connected. */
  457. log_fn(LOG_INFO,"Connection to %s:%u established.",address,port);
  458. conn->s = s;
  459. if(connection_add(conn) < 0) /* no space, forget it */
  460. return -1;
  461. return 1;
  462. }
  463. /** If there exist any listeners of type <b>type</b> in the connection
  464. * array, mark them for close.
  465. */
  466. static void listener_close_if_present(int type) {
  467. connection_t *conn;
  468. connection_t **carray;
  469. int i,n;
  470. tor_assert(type == CONN_TYPE_OR_LISTENER ||
  471. type == CONN_TYPE_AP_LISTENER ||
  472. type == CONN_TYPE_DIR_LISTENER);
  473. get_connection_array(&carray,&n);
  474. for(i=0;i<n;i++) {
  475. conn = carray[i];
  476. if (conn->type == type && !conn->marked_for_close) {
  477. connection_close_immediate(conn);
  478. connection_mark_for_close(conn);
  479. }
  480. }
  481. }
  482. static int retry_listeners(int type, struct config_line_t *cfg,
  483. int port_option, const char *default_addr)
  484. {
  485. listener_close_if_present(type);
  486. if (port_option) {
  487. if (!cfg) {
  488. if (connection_create_listener(default_addr, (uint16_t) port_option,
  489. type)<0)
  490. return -1;
  491. } else {
  492. for ( ; cfg; cfg = cfg->next) {
  493. if (connection_create_listener(cfg->value, (uint16_t) port_option,
  494. type)<0)
  495. return -1;
  496. }
  497. }
  498. }
  499. return 0;
  500. }
  501. /** (Re)launch listeners for each port you should have open.
  502. */
  503. int retry_all_listeners(void) {
  504. if (retry_listeners(CONN_TYPE_OR_LISTENER, options.ORBindAddress,
  505. options.ORPort, "0.0.0.0")<0)
  506. return -1;
  507. if (retry_listeners(CONN_TYPE_DIR_LISTENER, options.DirBindAddress,
  508. options.DirPort, "0.0.0.0")<0)
  509. return -1;
  510. if (retry_listeners(CONN_TYPE_AP_LISTENER, options.SocksBindAddress,
  511. options.SocksPort, "127.0.0.1")<0)
  512. return -1;
  513. return 0;
  514. }
  515. extern int global_read_bucket, global_write_bucket;
  516. /** How many bytes at most can we read onto this connection? */
  517. int connection_bucket_read_limit(connection_t *conn) {
  518. int at_most;
  519. /* do a rudimentary round-robin so one circuit can't hog a connection */
  520. if(connection_speaks_cells(conn)) {
  521. at_most = 32*(CELL_NETWORK_SIZE);
  522. } else {
  523. at_most = 32*(RELAY_PAYLOAD_SIZE);
  524. }
  525. if(at_most > global_read_bucket)
  526. at_most = global_read_bucket;
  527. if(connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN)
  528. if(at_most > conn->receiver_bucket)
  529. at_most = conn->receiver_bucket;
  530. return at_most;
  531. }
  532. /** We just read num_read onto conn. Decrement buckets appropriately. */
  533. static void connection_read_bucket_decrement(connection_t *conn, int num_read) {
  534. global_read_bucket -= num_read; tor_assert(global_read_bucket >= 0);
  535. if(connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN) {
  536. conn->receiver_bucket -= num_read; tor_assert(conn->receiver_bucket >= 0);
  537. }
  538. if(global_read_bucket == 0) {
  539. log_fn(LOG_DEBUG,"global bucket exhausted. Pausing.");
  540. conn->wants_to_read = 1;
  541. connection_stop_reading(conn);
  542. return;
  543. }
  544. if(connection_speaks_cells(conn) &&
  545. conn->state == OR_CONN_STATE_OPEN &&
  546. conn->receiver_bucket == 0) {
  547. log_fn(LOG_DEBUG,"receiver bucket exhausted. Pausing.");
  548. conn->wants_to_read = 1;
  549. connection_stop_reading(conn);
  550. }
  551. }
  552. /** Keep a timeval to know when time has passed enough to refill buckets */
  553. static struct timeval current_time;
  554. /** Initiatialize the global read bucket to options.BandwidthBurst,
  555. * and current_time to the current time. */
  556. void connection_bucket_init(void) {
  557. tor_gettimeofday(&current_time);
  558. global_read_bucket = options.BandwidthBurst; /* start it at max traffic */
  559. global_write_bucket = options.BandwidthBurst; /* start it at max traffic */
  560. }
  561. /** Some time has passed; increment buckets appropriately. */
  562. void connection_bucket_refill(struct timeval *now) {
  563. int i, n;
  564. connection_t *conn;
  565. connection_t **carray;
  566. if(now->tv_sec <= current_time.tv_sec)
  567. return; /* wait until the second has rolled over */
  568. current_time.tv_sec = now->tv_sec; /* update current_time */
  569. /* (ignore usecs for now) */
  570. /* refill the global buckets */
  571. if(global_read_bucket < options.BandwidthBurst) {
  572. global_read_bucket += options.BandwidthRate;
  573. log_fn(LOG_DEBUG,"global_read_bucket now %d.", global_read_bucket);
  574. }
  575. if(global_write_bucket < options.BandwidthBurst) {
  576. global_write_bucket += options.BandwidthRate;
  577. log_fn(LOG_DEBUG,"global_write_bucket now %d.", global_write_bucket);
  578. }
  579. /* refill the per-connection buckets */
  580. get_connection_array(&carray,&n);
  581. for(i=0;i<n;i++) {
  582. conn = carray[i];
  583. if(connection_receiver_bucket_should_increase(conn)) {
  584. conn->receiver_bucket += conn->bandwidth;
  585. //log_fn(LOG_DEBUG,"Receiver bucket %d now %d.", i, conn->receiver_bucket);
  586. }
  587. if(conn->wants_to_read == 1 /* it's marked to turn reading back on now */
  588. && global_read_bucket > 0 /* and we're allowed to read */
  589. && global_write_bucket > 0 /* and we're allowed to write (XXXX,
  590. * not the best place to check this.) */
  591. && (!connection_speaks_cells(conn) ||
  592. conn->state != OR_CONN_STATE_OPEN ||
  593. conn->receiver_bucket > 0)) {
  594. /* and either a non-cell conn or a cell conn with non-empty bucket */
  595. log_fn(LOG_DEBUG,"waking up conn (fd %d)",conn->s);
  596. conn->wants_to_read = 0;
  597. connection_start_reading(conn);
  598. if(conn->wants_to_write == 1) {
  599. conn->wants_to_write = 0;
  600. connection_start_writing(conn);
  601. }
  602. }
  603. }
  604. }
  605. /** Is the receiver bucket for connection <b>conn</b> low enough that we
  606. * should add another pile of tokens to it?
  607. */
  608. static int connection_receiver_bucket_should_increase(connection_t *conn) {
  609. tor_assert(conn);
  610. if(!connection_speaks_cells(conn))
  611. return 0; /* edge connections don't use receiver_buckets */
  612. if(conn->state != OR_CONN_STATE_OPEN)
  613. return 0; /* only open connections play the rate limiting game */
  614. tor_assert(conn->bandwidth > 0);
  615. if(conn->receiver_bucket > 9*conn->bandwidth)
  616. return 0;
  617. return 1;
  618. }
  619. /** Read bytes from conn->\s and process them.
  620. *
  621. * This function gets called from conn_read() in main.c, either
  622. * when poll() has declared that conn wants to read, or (for OR conns)
  623. * when there are pending TLS bytes.
  624. *
  625. * It calls connection_read_to_buf() to bring in any new bytes,
  626. * and then calls connection_process_inbuf() to process them.
  627. *
  628. * Mark the connection and return -1 if you want to close it, else
  629. * return 0.
  630. */
  631. int connection_handle_read(connection_t *conn) {
  632. conn->timestamp_lastread = time(NULL);
  633. switch(conn->type) {
  634. case CONN_TYPE_OR_LISTENER:
  635. return connection_handle_listener_read(conn, CONN_TYPE_OR);
  636. case CONN_TYPE_AP_LISTENER:
  637. return connection_handle_listener_read(conn, CONN_TYPE_AP);
  638. case CONN_TYPE_DIR_LISTENER:
  639. return connection_handle_listener_read(conn, CONN_TYPE_DIR);
  640. }
  641. if(connection_read_to_buf(conn) < 0) {
  642. /* There's a read error; kill the connection.*/
  643. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  644. conn->has_sent_end = 1; /* XXX have we already sent the end? really? */
  645. connection_mark_for_close(conn);
  646. if(conn->type == CONN_TYPE_DIR &&
  647. conn->state == DIR_CONN_STATE_CONNECTING) {
  648. /* it's a directory server and connecting failed: forget about this router */
  649. /* XXX I suspect pollerr may make Windows not get to this point. :( */
  650. router_mark_as_down(conn->identity_digest);
  651. if(conn->purpose == DIR_PURPOSE_FETCH_DIR && !all_directory_servers_down()) {
  652. log_fn(LOG_INFO,"Giving up on dirserver %s; trying another.", conn->nickname);
  653. directory_get_from_dirserver(DIR_PURPOSE_FETCH_DIR, NULL, 0);
  654. }
  655. }
  656. return -1;
  657. }
  658. if(connection_process_inbuf(conn) < 0) {
  659. // log_fn(LOG_DEBUG,"connection_process_inbuf returned -1.");
  660. return -1;
  661. }
  662. return 0;
  663. }
  664. /** Pull in new bytes from conn-\>s onto conn-\>inbuf, either
  665. * directly or via TLS. Reduce the token buckets by the number of
  666. * bytes read.
  667. *
  668. * Return -1 if we want to break conn, else return 0.
  669. */
  670. static int connection_read_to_buf(connection_t *conn) {
  671. int result;
  672. int at_most;
  673. /* how many bytes are we allowed to read? */
  674. at_most = connection_bucket_read_limit(conn);
  675. if(connection_speaks_cells(conn) && conn->state != OR_CONN_STATE_CONNECTING) {
  676. if(conn->state == OR_CONN_STATE_HANDSHAKING) {
  677. /* continue handshaking even if global token bucket is empty */
  678. return connection_tls_continue_handshake(conn);
  679. }
  680. log_fn(LOG_DEBUG,"%d: starting, inbuf_datalen %d (%d pending in tls object). at_most %d.",
  681. conn->s,(int)buf_datalen(conn->inbuf),tor_tls_get_pending_bytes(conn->tls), at_most);
  682. /* else open, or closing */
  683. result = read_to_buf_tls(conn->tls, at_most, conn->inbuf);
  684. switch(result) {
  685. case TOR_TLS_ERROR:
  686. case TOR_TLS_CLOSE:
  687. log_fn(LOG_INFO,"tls error. breaking (nickname %s, address %s).",
  688. conn->nickname ? conn->nickname : "not set", conn->address);
  689. return -1; /* XXX deal with close better */
  690. case TOR_TLS_WANTWRITE:
  691. connection_start_writing(conn);
  692. return 0;
  693. case TOR_TLS_WANTREAD: /* we're already reading */
  694. case TOR_TLS_DONE: /* no data read, so nothing to process */
  695. result = 0;
  696. break; /* so we call bucket_decrement below */
  697. }
  698. } else {
  699. result = read_to_buf(conn->s, at_most, conn->inbuf,
  700. &conn->inbuf_reached_eof);
  701. // log(LOG_DEBUG,"connection_read_to_buf(): read_to_buf returned %d.",read_result);
  702. if(result < 0)
  703. return -1;
  704. }
  705. if(result > 0 && !is_local_IP(conn->addr)) { /* remember it */
  706. rep_hist_note_bytes_read(result, time(NULL));
  707. }
  708. connection_read_bucket_decrement(conn, result);
  709. return 0;
  710. }
  711. /** A pass-through to fetch_from_buf. */
  712. int connection_fetch_from_buf(char *string, int len, connection_t *conn) {
  713. return fetch_from_buf(string, len, conn->inbuf);
  714. }
  715. /** Return conn-\>outbuf_flushlen: how many bytes conn wants to flush
  716. * from its outbuf. */
  717. int connection_wants_to_flush(connection_t *conn) {
  718. return conn->outbuf_flushlen;
  719. }
  720. /** Are there too many bytes on edge connection <b>conn</b>'s outbuf to
  721. * send back a relay-level sendme yet? Return 1 if so, 0 if not. Used by
  722. * connection_edge_consider_sending_sendme().
  723. */
  724. int connection_outbuf_too_full(connection_t *conn) {
  725. return (conn->outbuf_flushlen > 10*CELL_PAYLOAD_SIZE);
  726. }
  727. /** Try to flush more bytes onto conn-\>s.
  728. *
  729. * This function gets called either from conn_write() in main.c
  730. * when poll() has declared that conn wants to write, or below
  731. * from connection_write_to_buf() when an entire TLS record is ready.
  732. *
  733. * Update conn-\>timestamp_lastwritten to now, and call flush_buf
  734. * or flush_buf_tls appropriately. If it succeeds and there no more
  735. * more bytes on conn->outbuf, then call connection_finished_flushing
  736. * on it too.
  737. *
  738. * Mark the connection and return -1 if you want to close it, else
  739. * return 0.
  740. */
  741. int connection_handle_write(connection_t *conn) {
  742. int e, len=sizeof(e);
  743. int result;
  744. time_t now = time(NULL);
  745. tor_assert(!connection_is_listener(conn));
  746. conn->timestamp_lastwritten = now;
  747. /* Sometimes, "writeable" means "connected". */
  748. if (connection_state_is_connecting(conn)) {
  749. if (getsockopt(conn->s, SOL_SOCKET, SO_ERROR, (void*)&e, &len) < 0) {
  750. log_fn(LOG_WARN,"getsockopt() syscall failed?! Please report to tor-ops.");
  751. connection_close_immediate(conn);
  752. connection_mark_for_close(conn);
  753. return -1;
  754. }
  755. if(e) {
  756. /* some sort of error, but maybe just inprogress still */
  757. errno = e; /* XXX008 this is a kludge. maybe we should rearrange
  758. our error-hunting functions? E.g. pass errno to
  759. tor_socket_errno(). */
  760. if(!ERRNO_IS_CONN_EINPROGRESS(tor_socket_errno(conn->s))) {
  761. log_fn(LOG_INFO,"in-progress connect failed. Removing.");
  762. connection_close_immediate(conn);
  763. connection_mark_for_close(conn);
  764. /* it's safe to pass OPs to router_mark_as_down(), since it just
  765. * ignores unrecognized routers
  766. */
  767. if (conn->type == CONN_TYPE_OR)
  768. router_mark_as_down(conn->identity_digest);
  769. return -1;
  770. } else {
  771. return 0; /* no change, see if next time is better */
  772. }
  773. }
  774. /* The connection is successful. */
  775. return connection_finished_connecting(conn);
  776. }
  777. if (connection_speaks_cells(conn)) {
  778. if (conn->state == OR_CONN_STATE_HANDSHAKING) {
  779. connection_stop_writing(conn);
  780. if(connection_tls_continue_handshake(conn) < 0) {
  781. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  782. connection_mark_for_close(conn);
  783. return -1;
  784. }
  785. return 0;
  786. }
  787. /* else open, or closing */
  788. result = flush_buf_tls(conn->tls, conn->outbuf, &conn->outbuf_flushlen);
  789. switch(result) {
  790. case TOR_TLS_ERROR:
  791. case TOR_TLS_CLOSE:
  792. log_fn(LOG_INFO,"tls error. breaking.");
  793. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  794. connection_mark_for_close(conn);
  795. return -1; /* XXX deal with close better */
  796. case TOR_TLS_WANTWRITE:
  797. log_fn(LOG_DEBUG,"wanted write.");
  798. /* we're already writing */
  799. return 0;
  800. case TOR_TLS_WANTREAD:
  801. /* Make sure to avoid a loop if the receive buckets are empty. */
  802. log_fn(LOG_DEBUG,"wanted read.");
  803. if(!connection_is_reading(conn)) {
  804. connection_stop_writing(conn);
  805. conn->wants_to_write = 1;
  806. /* we'll start reading again when the next second arrives,
  807. * and then also start writing again.
  808. */
  809. }
  810. /* else no problem, we're already reading */
  811. return 0;
  812. /* case TOR_TLS_DONE:
  813. * for TOR_TLS_DONE, fall through to check if the flushlen
  814. * is empty, so we can stop writing.
  815. */
  816. }
  817. } else {
  818. result = flush_buf(conn->s, conn->outbuf, &conn->outbuf_flushlen);
  819. if (result < 0) {
  820. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  821. conn->has_sent_end = 1;
  822. connection_mark_for_close(conn);
  823. return -1;
  824. }
  825. }
  826. if(result > 0 && !is_local_IP(conn->addr)) { /* remember it */
  827. rep_hist_note_bytes_written(result, now);
  828. }
  829. global_write_bucket -= result;
  830. if(!connection_wants_to_flush(conn)) { /* it's done flushing */
  831. if(connection_finished_flushing(conn) < 0) {
  832. /* already marked */
  833. return -1;
  834. }
  835. }
  836. return 0;
  837. }
  838. /** Append <b>len</b> bytes of <b>string</b> onto <b>conn</b>'s
  839. * outbuf, and ask it to start writing.
  840. */
  841. void connection_write_to_buf(const char *string, int len, connection_t *conn) {
  842. if(!len || conn->marked_for_close)
  843. return;
  844. if(write_to_buf(string, len, conn->outbuf) < 0) {
  845. if(conn->type == CONN_TYPE_AP || conn->type == CONN_TYPE_EXIT) {
  846. /* if it failed, it means we have our package/delivery windows set
  847. wrong compared to our max outbuf size. close the whole circuit. */
  848. log_fn(LOG_WARN,"write_to_buf failed. Closing circuit (fd %d).", conn->s);
  849. circuit_mark_for_close(circuit_get_by_conn(conn));
  850. } else {
  851. log_fn(LOG_WARN,"write_to_buf failed. Closing connection (fd %d).", conn->s);
  852. connection_mark_for_close(conn);
  853. }
  854. return;
  855. }
  856. connection_start_writing(conn);
  857. conn->outbuf_flushlen += len;
  858. }
  859. /** Return the conn to addr/port that has the most recent
  860. * timestamp_created, or NULL if no such conn exists. */
  861. connection_t *connection_exact_get_by_addr_port(uint32_t addr, uint16_t port) {
  862. int i, n;
  863. connection_t *conn, *best=NULL;
  864. connection_t **carray;
  865. get_connection_array(&carray,&n);
  866. for(i=0;i<n;i++) {
  867. conn = carray[i];
  868. if(conn->addr == addr && conn->port == port && !conn->marked_for_close &&
  869. (!best || best->timestamp_created < conn->timestamp_created))
  870. best = conn;
  871. }
  872. return best;
  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. */