connection.c 46 KB

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