connection.c 43 KB

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