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. if(connection_or_nonopen_was_started_here(conn))
  170. rep_hist_note_connect_failed(conn->identity_digest, time(NULL));
  171. } else if (0) { // XXX reason == CLOSE_REASON_UNUSED_OR_CONN) {
  172. rep_hist_note_disconnect(conn->identity_digest, time(NULL));
  173. } else if(conn->identity_digest) {
  174. rep_hist_note_connection_died(conn->identity_digest, time(NULL));
  175. }
  176. break;
  177. case CONN_TYPE_AP:
  178. if (conn->socks_request->has_finished == 0) {
  179. log_fn(LOG_INFO,"Cleaning up AP -- sending socks reject.");
  180. connection_ap_handshake_socks_reply(conn, NULL, 0, 0);
  181. conn->socks_request->has_finished = 1;
  182. conn->hold_open_until_flushed = 1;
  183. }
  184. break;
  185. case CONN_TYPE_EXIT:
  186. if (conn->state == EXIT_CONN_STATE_RESOLVING) {
  187. circuit_detach_stream(circuit_get_by_conn(conn), conn);
  188. connection_dns_remove(conn);
  189. }
  190. break;
  191. case CONN_TYPE_DNSWORKER:
  192. if (conn->state == DNSWORKER_STATE_BUSY) {
  193. dns_cancel_pending_resolve(conn->address);
  194. }
  195. break;
  196. }
  197. }
  198. /** Close the underlying socket for <b>conn</b>, so we don't try to
  199. * flush it. Must be used in conjunction with (right before)
  200. * connection_mark_for_close().
  201. */
  202. void connection_close_immediate(connection_t *conn)
  203. {
  204. assert_connection_ok(conn,0);
  205. if (conn->s < 0) {
  206. log_fn(LOG_WARN,"Attempt to close already-closed connection.");
  207. return;
  208. }
  209. if (conn->outbuf_flushlen) {
  210. log_fn(LOG_INFO,"fd %d, type %s, state %d, %d bytes on outbuf.",
  211. conn->s, CONN_TYPE_TO_STRING(conn->type),
  212. conn->state, (int)conn->outbuf_flushlen);
  213. }
  214. tor_close_socket(conn->s);
  215. conn->s = -1;
  216. if(!connection_is_listener(conn)) {
  217. buf_clear(conn->outbuf);
  218. conn->outbuf_flushlen = 0;
  219. }
  220. }
  221. /** Mark <b>conn</b> to be closed next time we loop through
  222. * conn_close_if_marked() in main.c. Do any cleanup needed:
  223. * - Directory conns that fail to fetch a rendezvous descriptor need
  224. * to inform pending rendezvous streams.
  225. * - OR conns need to call rep_hist_note_*() to record status.
  226. * - AP conns need to send a socks reject if necessary.
  227. * - Exit conns need to call connection_dns_remove() if necessary.
  228. * - AP and Exit conns need to send an end cell if they can.
  229. * - DNS conns need to fail any resolves that are pending on them.
  230. */
  231. int
  232. _connection_mark_for_close(connection_t *conn)
  233. {
  234. assert_connection_ok(conn,0);
  235. if (conn->marked_for_close) {
  236. log(LOG_WARN, "Double mark-for-close on connection.");
  237. return -1;
  238. }
  239. conn->marked_for_close = 1;
  240. /* in case we're going to be held-open-til-flushed, reset
  241. * the number of seconds since last successful write, so
  242. * we get our whole 15 seconds */
  243. conn->timestamp_lastwritten = time(NULL);
  244. return 0;
  245. }
  246. /** Find each connection that has hold_open_until_flushed set to
  247. * 1 but hasn't written in the past 15 seconds, and set
  248. * hold_open_until_flushed to 0. This means it will get cleaned
  249. * up in the next loop through close_if_marked() in main.c.
  250. */
  251. void connection_expire_held_open(void)
  252. {
  253. connection_t **carray, *conn;
  254. int n, i;
  255. time_t now;
  256. now = time(NULL);
  257. get_connection_array(&carray, &n);
  258. for (i = 0; i < n; ++i) {
  259. conn = carray[i];
  260. /* If we've been holding the connection open, but we haven't written
  261. * for 15 seconds...
  262. */
  263. if (conn->hold_open_until_flushed) {
  264. tor_assert(conn->marked_for_close);
  265. if (now - conn->timestamp_lastwritten >= 15) {
  266. log_fn(LOG_WARN,"Giving up on marked_for_close conn that's been flushing for 15s (fd %d, type %s, state %d).",
  267. conn->s, CONN_TYPE_TO_STRING(conn->type), conn->state);
  268. conn->hold_open_until_flushed = 0;
  269. }
  270. }
  271. }
  272. }
  273. /** Bind a new non-blocking socket listening to
  274. * <b>bindaddress</b>:<b>bindport</b>, and add this new connection
  275. * (of type <b>type</b>) to the connection array.
  276. *
  277. * If <b>bindaddress</b> includes a port, we bind on that port; otherwise, we
  278. * use bindport.
  279. */
  280. static int connection_create_listener(const char *bindaddress, uint16_t bindport, int type) {
  281. struct sockaddr_in bindaddr; /* where to bind */
  282. connection_t *conn;
  283. uint16_t usePort;
  284. int s; /* the socket we're going to make */
  285. int one=1;
  286. memset(&bindaddr,0,sizeof(struct sockaddr_in));
  287. if (parse_addr_port(bindaddress, NULL, &(bindaddr.sin_addr.s_addr),
  288. &usePort)<0) {
  289. log_fn(LOG_WARN, "Error parsing/resolving BindAddress %s",bindaddress);
  290. return -1;
  291. }
  292. if (usePort==0)
  293. usePort = bindport;
  294. bindaddr.sin_family = AF_INET;
  295. bindaddr.sin_port = htons((uint16_t) usePort);
  296. s = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
  297. if (s < 0) {
  298. log_fn(LOG_WARN,"Socket creation failed.");
  299. return -1;
  300. }
  301. setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (void*) &one, sizeof(one));
  302. if(bind(s,(struct sockaddr *)&bindaddr,sizeof(bindaddr)) < 0) {
  303. log_fn(LOG_WARN,"Could not bind to port %u: %s",usePort,
  304. tor_socket_strerror(tor_socket_errno(s)));
  305. return -1;
  306. }
  307. if(listen(s,SOMAXCONN) < 0) {
  308. log_fn(LOG_WARN,"Could not listen on port %u: %s",usePort,
  309. tor_socket_strerror(tor_socket_errno(s)));
  310. return -1;
  311. }
  312. set_socket_nonblocking(s);
  313. conn = connection_new(type);
  314. conn->s = s;
  315. if(connection_add(conn) < 0) { /* no space, forget it */
  316. log_fn(LOG_WARN,"connection_add failed. Giving up.");
  317. connection_free(conn);
  318. return -1;
  319. }
  320. log_fn(LOG_DEBUG,"%s listening on port %u.",conn_type_to_string[type], usePort);
  321. conn->state = LISTENER_STATE_READY;
  322. connection_start_reading(conn);
  323. return 0;
  324. }
  325. /** The listener connection <b>conn</b> told poll() it wanted to read.
  326. * Call accept() on conn-\>s, and add the new connection if necessary.
  327. */
  328. static int connection_handle_listener_read(connection_t *conn, int new_type) {
  329. int news; /* the new socket */
  330. connection_t *newconn;
  331. /* information about the remote peer when connecting to other routers */
  332. struct sockaddr_in remote;
  333. /* length of the remote address. Must be an int, since accept() needs that. */
  334. int remotelen = sizeof(struct sockaddr_in);
  335. news = accept(conn->s,(struct sockaddr *)&remote,&remotelen);
  336. if (news == -1) { /* accept() error */
  337. if(ERRNO_IS_EAGAIN(tor_socket_errno(conn->s))) {
  338. return 0; /* he hung up before we could accept(). that's fine. */
  339. }
  340. /* else there was a real error. */
  341. log_fn(LOG_WARN,"accept() failed. Closing listener.");
  342. connection_mark_for_close(conn);
  343. return -1;
  344. }
  345. log(LOG_INFO,"Connection accepted on socket %d (child of fd %d).",news, conn->s);
  346. if(shutting_down && new_type != CONN_TYPE_DIR) {
  347. /* allow directory connections even while we're shutting down */
  348. log(LOG_INFO,"But we're shutting down, so closing (type %d).", new_type);
  349. tor_close_socket(news);
  350. return 0;
  351. }
  352. set_socket_nonblocking(news);
  353. /* process entrance policies here, before we even create the connection */
  354. if(new_type == CONN_TYPE_AP) {
  355. /* check sockspolicy to see if we should accept it */
  356. if(socks_policy_permits_address(ntohl(remote.sin_addr.s_addr)) == 0) {
  357. log_fn(LOG_WARN,"Denying socks connection from untrusted address %s.",
  358. inet_ntoa(remote.sin_addr));
  359. tor_close_socket(news);
  360. return 0;
  361. }
  362. }
  363. newconn = connection_new(new_type);
  364. newconn->s = news;
  365. newconn->address = tor_strdup(inet_ntoa(remote.sin_addr)); /* remember the remote address */
  366. newconn->addr = ntohl(remote.sin_addr.s_addr);
  367. newconn->port = ntohs(remote.sin_port);
  368. if(connection_add(newconn) < 0) { /* no space, forget it */
  369. connection_free(newconn);
  370. return 0; /* no need to tear down the parent */
  371. }
  372. if(connection_init_accepted_conn(newconn) < 0) {
  373. connection_mark_for_close(newconn);
  374. return 0;
  375. }
  376. return 0;
  377. }
  378. /** Initialize states for newly accepted connection <b>conn</b>.
  379. * If conn is an OR, start the tls handshake.
  380. */
  381. static int connection_init_accepted_conn(connection_t *conn) {
  382. connection_start_reading(conn);
  383. switch(conn->type) {
  384. case CONN_TYPE_OR:
  385. return connection_tls_start_handshake(conn, 1);
  386. case CONN_TYPE_AP:
  387. conn->state = AP_CONN_STATE_SOCKS_WAIT;
  388. break;
  389. case CONN_TYPE_DIR:
  390. conn->purpose = DIR_PURPOSE_SERVER;
  391. conn->state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
  392. break;
  393. }
  394. return 0;
  395. }
  396. /** Take conn, make a nonblocking socket; try to connect to
  397. * addr:port (they arrive in *host order*). If fail, return -1. Else
  398. * assign s to conn->\s: if connected return 1, if EAGAIN return 0.
  399. *
  400. * address is used to make the logs useful.
  401. *
  402. * On success, add conn to the list of polled connections.
  403. */
  404. int connection_connect(connection_t *conn, char *address, uint32_t addr, uint16_t port) {
  405. int s;
  406. struct sockaddr_in dest_addr;
  407. s=socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
  408. if (s < 0) {
  409. log_fn(LOG_WARN,"Error creating network socket: %s",
  410. tor_socket_strerror(tor_socket_errno(-1)));
  411. return -1;
  412. }
  413. if (options.OutboundBindAddress) {
  414. struct sockaddr_in ext_addr;
  415. memset(&ext_addr, 0, sizeof(ext_addr));
  416. ext_addr.sin_family = AF_INET;
  417. ext_addr.sin_port = 0;
  418. if (!tor_inet_aton(options.OutboundBindAddress, &ext_addr.sin_addr)) {
  419. log_fn(LOG_WARN,"Outbound bind address '%s' didn't parse. Ignoring.",
  420. options.OutboundBindAddress);
  421. } else {
  422. if(bind(s, (struct sockaddr*)&ext_addr, sizeof(ext_addr)) < 0) {
  423. log_fn(LOG_WARN,"Error binding network socket: %s",
  424. tor_socket_strerror(tor_socket_errno(s)));
  425. return -1;
  426. }
  427. }
  428. }
  429. set_socket_nonblocking(s);
  430. memset(&dest_addr,0,sizeof(dest_addr));
  431. dest_addr.sin_family = AF_INET;
  432. dest_addr.sin_port = htons(port);
  433. dest_addr.sin_addr.s_addr = htonl(addr);
  434. log_fn(LOG_DEBUG,"Connecting to %s:%u.",address,port);
  435. if(connect(s,(struct sockaddr *)&dest_addr,sizeof(dest_addr)) < 0) {
  436. if(!ERRNO_IS_CONN_EINPROGRESS(tor_socket_errno(s))) {
  437. /* yuck. kill it. */
  438. log_fn(LOG_INFO,"Connect() to %s:%u failed: %s",address,port,
  439. tor_socket_strerror(tor_socket_errno(s)));
  440. tor_close_socket(s);
  441. return -1;
  442. } else {
  443. /* it's in progress. set state appropriately and return. */
  444. conn->s = s;
  445. if(connection_add(conn) < 0) /* no space, forget it */
  446. return -1;
  447. log_fn(LOG_DEBUG,"connect in progress, socket %d.",s);
  448. return 0;
  449. }
  450. }
  451. /* it succeeded. we're connected. */
  452. log_fn(LOG_INFO,"Connection to %s:%u established.",address,port);
  453. conn->s = s;
  454. if(connection_add(conn) < 0) /* no space, forget it */
  455. return -1;
  456. return 1;
  457. }
  458. /** If there exist any listeners of type <b>type</b> in the connection
  459. * array, mark them for close.
  460. */
  461. static void listener_close_if_present(int type) {
  462. connection_t *conn;
  463. connection_t **carray;
  464. int i,n;
  465. tor_assert(type == CONN_TYPE_OR_LISTENER ||
  466. type == CONN_TYPE_AP_LISTENER ||
  467. type == CONN_TYPE_DIR_LISTENER);
  468. get_connection_array(&carray,&n);
  469. for(i=0;i<n;i++) {
  470. conn = carray[i];
  471. if (conn->type == type && !conn->marked_for_close) {
  472. connection_close_immediate(conn);
  473. connection_mark_for_close(conn);
  474. }
  475. }
  476. }
  477. static int retry_listeners(int type, struct config_line_t *cfg,
  478. int port_option, const char *default_addr)
  479. {
  480. listener_close_if_present(type);
  481. if (port_option) {
  482. if (!cfg) {
  483. if (connection_create_listener(default_addr, (uint16_t) port_option,
  484. type)<0)
  485. return -1;
  486. } else {
  487. for ( ; cfg; cfg = cfg->next) {
  488. if (connection_create_listener(cfg->value, (uint16_t) port_option,
  489. type)<0)
  490. return -1;
  491. }
  492. }
  493. }
  494. return 0;
  495. }
  496. /** (Re)launch listeners for each port you should have open.
  497. */
  498. int retry_all_listeners(void) {
  499. if (retry_listeners(CONN_TYPE_OR_LISTENER, options.ORBindAddress,
  500. options.ORPort, "0.0.0.0")<0)
  501. return -1;
  502. if (retry_listeners(CONN_TYPE_DIR_LISTENER, options.DirBindAddress,
  503. options.DirPort, "0.0.0.0")<0)
  504. return -1;
  505. if (retry_listeners(CONN_TYPE_AP_LISTENER, options.SocksBindAddress,
  506. options.SocksPort, "127.0.0.1")<0)
  507. return -1;
  508. return 0;
  509. }
  510. extern int global_read_bucket, global_write_bucket;
  511. /** How many bytes at most can we read onto this connection? */
  512. int connection_bucket_read_limit(connection_t *conn) {
  513. int at_most;
  514. /* do a rudimentary round-robin so one circuit can't hog a connection */
  515. if(connection_speaks_cells(conn)) {
  516. at_most = 32*(CELL_NETWORK_SIZE);
  517. } else {
  518. at_most = 32*(RELAY_PAYLOAD_SIZE);
  519. }
  520. if(at_most > global_read_bucket)
  521. at_most = global_read_bucket;
  522. if(connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN)
  523. if(at_most > conn->receiver_bucket)
  524. at_most = conn->receiver_bucket;
  525. return at_most;
  526. }
  527. /** We just read num_read onto conn. Decrement buckets appropriately. */
  528. static void connection_read_bucket_decrement(connection_t *conn, int num_read) {
  529. global_read_bucket -= num_read; tor_assert(global_read_bucket >= 0);
  530. if(connection_speaks_cells(conn) && conn->state == OR_CONN_STATE_OPEN) {
  531. conn->receiver_bucket -= num_read; tor_assert(conn->receiver_bucket >= 0);
  532. }
  533. if(global_read_bucket == 0) {
  534. log_fn(LOG_DEBUG,"global bucket exhausted. Pausing.");
  535. conn->wants_to_read = 1;
  536. connection_stop_reading(conn);
  537. return;
  538. }
  539. if(connection_speaks_cells(conn) &&
  540. conn->state == OR_CONN_STATE_OPEN &&
  541. conn->receiver_bucket == 0) {
  542. log_fn(LOG_DEBUG,"receiver bucket exhausted. Pausing.");
  543. conn->wants_to_read = 1;
  544. connection_stop_reading(conn);
  545. }
  546. }
  547. /** Keep a timeval to know when time has passed enough to refill buckets */
  548. static struct timeval current_time;
  549. /** Initiatialize the global read bucket to options.BandwidthBurst,
  550. * and current_time to the current time. */
  551. void connection_bucket_init(void) {
  552. tor_gettimeofday(&current_time);
  553. global_read_bucket = options.BandwidthBurst; /* start it at max traffic */
  554. global_write_bucket = options.BandwidthBurst; /* start it at max traffic */
  555. }
  556. /** Some time has passed; increment buckets appropriately. */
  557. void connection_bucket_refill(struct timeval *now) {
  558. int i, n;
  559. connection_t *conn;
  560. connection_t **carray;
  561. if(now->tv_sec <= current_time.tv_sec)
  562. return; /* wait until the second has rolled over */
  563. current_time.tv_sec = now->tv_sec; /* update current_time */
  564. /* (ignore usecs for now) */
  565. /* refill the global buckets */
  566. if(global_read_bucket < options.BandwidthBurst) {
  567. global_read_bucket += options.BandwidthRate;
  568. log_fn(LOG_DEBUG,"global_read_bucket now %d.", global_read_bucket);
  569. }
  570. if(global_write_bucket < options.BandwidthBurst) {
  571. global_write_bucket += options.BandwidthRate;
  572. log_fn(LOG_DEBUG,"global_write_bucket now %d.", global_write_bucket);
  573. }
  574. /* refill the per-connection buckets */
  575. get_connection_array(&carray,&n);
  576. for(i=0;i<n;i++) {
  577. conn = carray[i];
  578. if(connection_receiver_bucket_should_increase(conn)) {
  579. conn->receiver_bucket += conn->bandwidth;
  580. //log_fn(LOG_DEBUG,"Receiver bucket %d now %d.", i, conn->receiver_bucket);
  581. }
  582. if(conn->wants_to_read == 1 /* it's marked to turn reading back on now */
  583. && global_read_bucket > 0 /* and we're allowed to read */
  584. && global_write_bucket > 0 /* and we're allowed to write (XXXX,
  585. * not the best place to check this.) */
  586. && (!connection_speaks_cells(conn) ||
  587. conn->state != OR_CONN_STATE_OPEN ||
  588. conn->receiver_bucket > 0)) {
  589. /* and either a non-cell conn or a cell conn with non-empty bucket */
  590. log_fn(LOG_DEBUG,"waking up conn (fd %d)",conn->s);
  591. conn->wants_to_read = 0;
  592. connection_start_reading(conn);
  593. if(conn->wants_to_write == 1) {
  594. conn->wants_to_write = 0;
  595. connection_start_writing(conn);
  596. }
  597. }
  598. }
  599. }
  600. /** Is the receiver bucket for connection <b>conn</b> low enough that we
  601. * should add another pile of tokens to it?
  602. */
  603. static int connection_receiver_bucket_should_increase(connection_t *conn) {
  604. tor_assert(conn);
  605. if(!connection_speaks_cells(conn))
  606. return 0; /* edge connections don't use receiver_buckets */
  607. if(conn->state != OR_CONN_STATE_OPEN)
  608. return 0; /* only open connections play the rate limiting game */
  609. tor_assert(conn->bandwidth > 0);
  610. if(conn->receiver_bucket > 9*conn->bandwidth)
  611. return 0;
  612. return 1;
  613. }
  614. /** Read bytes from conn->\s and process them.
  615. *
  616. * This function gets called from conn_read() in main.c, either
  617. * when poll() has declared that conn wants to read, or (for OR conns)
  618. * when there are pending TLS bytes.
  619. *
  620. * It calls connection_read_to_buf() to bring in any new bytes,
  621. * and then calls connection_process_inbuf() to process them.
  622. *
  623. * Mark the connection and return -1 if you want to close it, else
  624. * return 0.
  625. */
  626. int connection_handle_read(connection_t *conn) {
  627. conn->timestamp_lastread = time(NULL);
  628. switch(conn->type) {
  629. case CONN_TYPE_OR_LISTENER:
  630. return connection_handle_listener_read(conn, CONN_TYPE_OR);
  631. case CONN_TYPE_AP_LISTENER:
  632. return connection_handle_listener_read(conn, CONN_TYPE_AP);
  633. case CONN_TYPE_DIR_LISTENER:
  634. return connection_handle_listener_read(conn, CONN_TYPE_DIR);
  635. }
  636. if(connection_read_to_buf(conn) < 0) {
  637. /* There's a read error; kill the connection.*/
  638. connection_close_immediate(conn); /* Don't flush; connection is dead. */
  639. if(conn->type == CONN_TYPE_AP || conn->type == CONN_TYPE_EXIT) {
  640. connection_edge_end(conn, (char)(connection_state_is_open(conn) ?
  641. END_STREAM_REASON_MISC : END_STREAM_REASON_CONNECTFAILED),
  642. conn->cpath_layer);
  643. }
  644. connection_mark_for_close(conn);
  645. if(conn->type == CONN_TYPE_DIR &&
  646. conn->state == DIR_CONN_STATE_CONNECTING) {
  647. /* it's a directory server and connecting failed: forget about this router */
  648. /* XXX I suspect pollerr may make Windows not get to this point. :( */
  649. router_mark_as_down(conn->identity_digest);
  650. if(conn->purpose == DIR_PURPOSE_FETCH_DIR &&
  651. !all_trusted_directory_servers_down()) {
  652. log_fn(LOG_INFO,"Giving up on dirserver %s; trying another.", conn->address);
  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, size_t 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, size_t 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. */