socket.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972
  1. /*
  2. * mbsync - mailbox synchronizer
  3. * Copyright (C) 2000-2002 Michael R. Elkins <me@mutt.org>
  4. * Copyright (C) 2002-2006,2008,2010,2011, 2013 Oswald Buddenhagen <ossi@users.sf.net>
  5. * Copyright (C) 2004 Theodore Y. Ts'o <tytso@mit.edu>
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. *
  20. * As a special exception, mbsync may be linked with the OpenSSL library,
  21. * despite that library's more restrictive license.
  22. */
  23. #include "socket.h"
  24. #include <assert.h>
  25. #include <unistd.h>
  26. #include <stdlib.h>
  27. #include <stddef.h>
  28. #include <errno.h>
  29. #include <string.h>
  30. #include <fcntl.h>
  31. #include <sys/socket.h>
  32. #include <sys/ioctl.h>
  33. #include <netinet/in.h>
  34. #include <netinet/tcp.h>
  35. #include <arpa/inet.h>
  36. #include <netdb.h>
  37. #ifdef HAVE_LIBSSL
  38. # include <openssl/ssl.h>
  39. # include <openssl/err.h>
  40. # include <openssl/hmac.h>
  41. # include <openssl/x509v3.h>
  42. #endif
  43. static void
  44. socket_fail( conn_t *conn )
  45. {
  46. conn->bad_callback( conn->callback_aux );
  47. }
  48. #ifdef HAVE_LIBSSL
  49. static int
  50. ssl_return( const char *func, conn_t *conn, int ret )
  51. {
  52. int err;
  53. switch ((err = SSL_get_error( conn->ssl, ret ))) {
  54. case SSL_ERROR_NONE:
  55. return ret;
  56. case SSL_ERROR_WANT_WRITE:
  57. conf_notifier( &conn->notify, POLLIN, POLLOUT );
  58. /* fallthrough */
  59. case SSL_ERROR_WANT_READ:
  60. return 0;
  61. case SSL_ERROR_SYSCALL:
  62. case SSL_ERROR_SSL:
  63. if (!(err = ERR_get_error())) {
  64. if (ret == 0) {
  65. if (conn->state != SCK_CLOSING)
  66. error( "Socket error: secure %s %s: unexpected EOF\n", func, conn->name );
  67. } else {
  68. sys_error( "Socket error: secure %s %s", func, conn->name );
  69. }
  70. } else {
  71. error( "Socket error: secure %s %s: %s\n", func, conn->name, ERR_error_string( err, 0 ) );
  72. }
  73. break;
  74. default:
  75. error( "Socket error: secure %s %s: unhandled SSL error %d\n", func, conn->name, err );
  76. break;
  77. }
  78. if (conn->state == SCK_STARTTLS)
  79. conn->callbacks.starttls( 0, conn->callback_aux );
  80. else
  81. socket_fail( conn );
  82. return -1;
  83. }
  84. /* Some of this code is inspired by / lifted from mutt. */
  85. static int
  86. host_matches( const char *host, const char *pattern )
  87. {
  88. if (pattern[0] == '*' && pattern[1] == '.') {
  89. pattern += 2;
  90. if (!(host = strchr( host, '.' )))
  91. return 0;
  92. host++;
  93. }
  94. return *host && *pattern && !strcasecmp( host, pattern );
  95. }
  96. static int
  97. verify_hostname( X509 *cert, const char *hostname )
  98. {
  99. int i, len, found;
  100. X509_NAME *subj;
  101. STACK_OF(GENERAL_NAME) *subj_alt_names;
  102. char cname[1000];
  103. /* try the DNS subjectAltNames */
  104. found = 0;
  105. if ((subj_alt_names = X509_get_ext_d2i( cert, NID_subject_alt_name, NULL, NULL ))) {
  106. int num_subj_alt_names = sk_GENERAL_NAME_num( subj_alt_names );
  107. for (i = 0; i < num_subj_alt_names; i++) {
  108. GENERAL_NAME *subj_alt_name = sk_GENERAL_NAME_value( subj_alt_names, i );
  109. if (subj_alt_name->type == GEN_DNS &&
  110. strlen( (const char *)subj_alt_name->d.ia5->data ) == (size_t)subj_alt_name->d.ia5->length &&
  111. host_matches( hostname, (const char *)(subj_alt_name->d.ia5->data) ))
  112. {
  113. found = 1;
  114. break;
  115. }
  116. }
  117. sk_GENERAL_NAME_pop_free( subj_alt_names, GENERAL_NAME_free );
  118. }
  119. if (found)
  120. return 0;
  121. /* try the common name */
  122. if (!(subj = X509_get_subject_name( cert ))) {
  123. error( "Error, cannot get certificate subject\n" );
  124. return -1;
  125. }
  126. if ((len = X509_NAME_get_text_by_NID( subj, NID_commonName, cname, sizeof(cname) )) < 0) {
  127. error( "Error, cannot get certificate common name\n" );
  128. return -1;
  129. }
  130. if (strlen( cname ) == (size_t)len && host_matches( hostname, cname ))
  131. return 0;
  132. error( "Error, certificate owner does not match hostname %s\n", hostname );
  133. return -1;
  134. }
  135. static int
  136. verify_cert_host( const server_conf_t *conf, conn_t *sock )
  137. {
  138. int i;
  139. long err;
  140. X509 *cert;
  141. STACK_OF(X509_OBJECT) *trusted;
  142. cert = SSL_get_peer_certificate( sock->ssl );
  143. if (!cert) {
  144. error( "Error, no server certificate\n" );
  145. return -1;
  146. }
  147. trusted = (STACK_OF(X509_OBJECT) *)sock->conf->trusted_certs;
  148. for (i = 0; i < sk_X509_OBJECT_num( trusted ); i++) {
  149. if (!X509_cmp( cert, sk_X509_OBJECT_value( trusted, i )->data.x509 ))
  150. return 0;
  151. }
  152. err = SSL_get_verify_result( sock->ssl );
  153. if (err != X509_V_OK) {
  154. error( "SSL error connecting %s: %s\n", sock->name, ERR_error_string( err, NULL ) );
  155. return -1;
  156. }
  157. if (!conf->host) {
  158. error( "SSL error connecting %s: Neither host nor matching certificate specified\n", sock->name );
  159. return -1;
  160. }
  161. return verify_hostname( cert, conf->host );
  162. }
  163. static int
  164. init_ssl_ctx( const server_conf_t *conf )
  165. {
  166. server_conf_t *mconf = (server_conf_t *)conf;
  167. int options = 0;
  168. if (conf->SSLContext)
  169. return conf->ssl_ctx_valid;
  170. mconf->SSLContext = SSL_CTX_new( SSLv23_client_method() );
  171. if (!(conf->ssl_versions & SSLv2))
  172. options |= SSL_OP_NO_SSLv2;
  173. if (!(conf->ssl_versions & SSLv3))
  174. options |= SSL_OP_NO_SSLv3;
  175. if (!(conf->ssl_versions & TLSv1))
  176. options |= SSL_OP_NO_TLSv1;
  177. #ifdef SSL_OP_NO_TLSv1_1
  178. if (!(conf->ssl_versions & TLSv1_1))
  179. options |= SSL_OP_NO_TLSv1_1;
  180. #endif
  181. #ifdef SSL_OP_NO_TLSv1_2
  182. if (!(conf->ssl_versions & TLSv1_2))
  183. options |= SSL_OP_NO_TLSv1_2;
  184. #endif
  185. SSL_CTX_set_options( mconf->SSLContext, options );
  186. if (conf->cert_file && !SSL_CTX_load_verify_locations( mconf->SSLContext, conf->cert_file, 0 )) {
  187. error( "Error while loading certificate file '%s': %s\n",
  188. conf->cert_file, ERR_error_string( ERR_get_error(), 0 ) );
  189. return 0;
  190. }
  191. mconf->trusted_certs = (_STACK *)sk_X509_OBJECT_dup( SSL_CTX_get_cert_store( mconf->SSLContext )->objs );
  192. if (mconf->system_certs && !SSL_CTX_set_default_verify_paths( mconf->SSLContext ))
  193. warn( "Warning: Unable to load default certificate files: %s\n",
  194. ERR_error_string( ERR_get_error(), 0 ) );
  195. SSL_CTX_set_verify( mconf->SSLContext, SSL_VERIFY_NONE, NULL );
  196. mconf->ssl_ctx_valid = 1;
  197. return 1;
  198. }
  199. static void start_tls_p2( conn_t * );
  200. static void start_tls_p3( conn_t *, int );
  201. static void ssl_fake_cb( void * );
  202. void
  203. socket_start_tls( conn_t *conn, void (*cb)( int ok, void *aux ) )
  204. {
  205. static int ssl_inited;
  206. conn->callbacks.starttls = cb;
  207. if (!ssl_inited) {
  208. SSL_library_init();
  209. SSL_load_error_strings();
  210. ssl_inited = 1;
  211. }
  212. if (!init_ssl_ctx( conn->conf )) {
  213. start_tls_p3( conn, 0 );
  214. return;
  215. }
  216. init_wakeup( &conn->ssl_fake, ssl_fake_cb, conn );
  217. conn->ssl = SSL_new( ((server_conf_t *)conn->conf)->SSLContext );
  218. SSL_set_fd( conn->ssl, conn->fd );
  219. SSL_set_mode( conn->ssl, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER );
  220. conn->state = SCK_STARTTLS;
  221. start_tls_p2( conn );
  222. }
  223. static void
  224. start_tls_p2( conn_t *conn )
  225. {
  226. if (ssl_return( "connect to", conn, SSL_connect( conn->ssl ) ) > 0) {
  227. if (verify_cert_host( conn->conf, conn )) {
  228. start_tls_p3( conn, 0 );
  229. } else {
  230. info( "Connection is now encrypted\n" );
  231. start_tls_p3( conn, 1 );
  232. }
  233. }
  234. }
  235. static void start_tls_p3( conn_t *conn, int ok )
  236. {
  237. conn->state = SCK_READY;
  238. conn->callbacks.starttls( ok, conn->callback_aux );
  239. }
  240. #endif /* HAVE_LIBSSL */
  241. #ifdef HAVE_LIBZ
  242. static void z_fake_cb( void * );
  243. void
  244. socket_start_deflate( conn_t *conn )
  245. {
  246. int result;
  247. conn->in_z = nfcalloc( sizeof(*conn->in_z) );
  248. result = inflateInit2(
  249. conn->in_z,
  250. -15 /* Use raw deflate */
  251. );
  252. if (result != Z_OK) {
  253. error( "Fatal: Cannot initialize decompression: %s\n", conn->in_z->msg );
  254. abort();
  255. }
  256. conn->out_z = nfcalloc( sizeof(*conn->out_z) );
  257. result = deflateInit2(
  258. conn->out_z,
  259. Z_DEFAULT_COMPRESSION, /* Compression level */
  260. Z_DEFLATED, /* Only valid value */
  261. -15, /* Use raw deflate */
  262. 8, /* Default memory usage */
  263. Z_DEFAULT_STRATEGY /* Don't try to do anything fancy */
  264. );
  265. if (result != Z_OK) {
  266. error( "Fatal: Cannot initialize compression: %s\n", conn->out_z->msg );
  267. abort();
  268. }
  269. init_wakeup( &conn->z_fake, z_fake_cb, conn );
  270. }
  271. #endif /* HAVE_LIBZ */
  272. static void socket_fd_cb( int, void * );
  273. static void socket_fake_cb( void * );
  274. static void socket_connect_one( conn_t * );
  275. static void socket_connect_failed( conn_t * );
  276. static void socket_connected( conn_t * );
  277. static void socket_connect_bail( conn_t * );
  278. static void
  279. socket_open_internal( conn_t *sock, int fd )
  280. {
  281. sock->fd = fd;
  282. fcntl( fd, F_SETFL, O_NONBLOCK );
  283. init_notifier( &sock->notify, fd, socket_fd_cb, sock );
  284. init_wakeup( &sock->fd_fake, socket_fake_cb, sock );
  285. }
  286. static void
  287. socket_close_internal( conn_t *sock )
  288. {
  289. wipe_notifier( &sock->notify );
  290. wipe_wakeup( &sock->fd_fake );
  291. close( sock->fd );
  292. sock->fd = -1;
  293. }
  294. void
  295. socket_connect( conn_t *sock, void (*cb)( int ok, void *aux ) )
  296. {
  297. const server_conf_t *conf = sock->conf;
  298. sock->callbacks.connect = cb;
  299. /* open connection to server */
  300. if (conf->tunnel) {
  301. int a[2];
  302. nfasprintf( &sock->name, "tunnel '%s'", conf->tunnel );
  303. infon( "Starting %s... ", sock->name );
  304. if (socketpair( PF_UNIX, SOCK_STREAM, 0, a )) {
  305. perror( "socketpair" );
  306. exit( 1 );
  307. }
  308. if (fork() == 0) {
  309. if (dup2( a[0], 0 ) == -1 || dup2( a[0], 1 ) == -1)
  310. _exit( 127 );
  311. close( a[0] );
  312. close( a[1] );
  313. execl( "/bin/sh", "sh", "-c", conf->tunnel, (char *)0 );
  314. _exit( 127 );
  315. }
  316. close( a[0] );
  317. socket_open_internal( sock, a[1] );
  318. info( "\vok\n" );
  319. socket_connected( sock );
  320. } else {
  321. #ifdef HAVE_IPV6
  322. int gaierr;
  323. struct addrinfo hints;
  324. memset( &hints, 0, sizeof(hints) );
  325. hints.ai_family = AF_UNSPEC;
  326. hints.ai_socktype = SOCK_STREAM;
  327. hints.ai_flags = AI_ADDRCONFIG;
  328. infon( "Resolving %s... ", conf->host );
  329. if ((gaierr = getaddrinfo( conf->host, NULL, &hints, &sock->addrs ))) {
  330. error( "Error: Cannot resolve server '%s': %s\n", conf->host, gai_strerror( gaierr ) );
  331. socket_connect_bail( sock );
  332. return;
  333. }
  334. info( "\vok\n" );
  335. sock->curr_addr = sock->addrs;
  336. #else
  337. struct hostent *he;
  338. infon( "Resolving %s... ", conf->host );
  339. he = gethostbyname( conf->host );
  340. if (!he) {
  341. error( "Error: Cannot resolve server '%s': %s\n", conf->host, hstrerror( h_errno ) );
  342. socket_connect_bail( sock );
  343. return;
  344. }
  345. info( "\vok\n" );
  346. sock->curr_addr = he->h_addr_list;
  347. #endif
  348. socket_connect_one( sock );
  349. }
  350. }
  351. static void
  352. socket_connect_one( conn_t *sock )
  353. {
  354. int s;
  355. #ifdef HAVE_IPV6
  356. struct addrinfo *ai;
  357. #else
  358. struct {
  359. struct sockaddr_in ai_addr[1];
  360. } ai[1];
  361. #endif
  362. #ifdef HAVE_IPV6
  363. if (!(ai = sock->curr_addr)) {
  364. #else
  365. if (!*sock->curr_addr) {
  366. #endif
  367. error( "No working address found for %s\n", sock->conf->host );
  368. socket_connect_bail( sock );
  369. return;
  370. }
  371. #ifdef HAVE_IPV6
  372. if (ai->ai_family == AF_INET6) {
  373. struct sockaddr_in6 *in6 = ((struct sockaddr_in6 *)ai->ai_addr);
  374. char sockname[64];
  375. in6->sin6_port = htons( sock->conf->port );
  376. nfasprintf( &sock->name, "%s ([%s]:%hu)",
  377. sock->conf->host, inet_ntop( AF_INET6, &in6->sin6_addr, sockname, sizeof(sockname) ), sock->conf->port );
  378. } else
  379. #endif
  380. {
  381. struct sockaddr_in *in = ((struct sockaddr_in *)ai->ai_addr);
  382. #ifndef HAVE_IPV6
  383. memset( in, 0, sizeof(*in) );
  384. in->sin_family = AF_INET;
  385. in->sin_addr.s_addr = *((int *)*sock->curr_addr);
  386. #endif
  387. in->sin_port = htons( sock->conf->port );
  388. nfasprintf( &sock->name, "%s (%s:%hu)",
  389. sock->conf->host, inet_ntoa( in->sin_addr ), sock->conf->port );
  390. }
  391. #ifdef HAVE_IPV6
  392. s = socket( ai->ai_family, SOCK_STREAM, 0 );
  393. #else
  394. s = socket( PF_INET, SOCK_STREAM, 0 );
  395. #endif
  396. if (s < 0) {
  397. perror( "socket" );
  398. exit( 1 );
  399. }
  400. socket_open_internal( sock, s );
  401. infon( "Connecting to %s... ", sock->name );
  402. #ifdef HAVE_IPV6
  403. if (connect( s, ai->ai_addr, ai->ai_addrlen )) {
  404. #else
  405. if (connect( s, ai->ai_addr, sizeof(*ai->ai_addr) )) {
  406. #endif
  407. if (errno != EINPROGRESS) {
  408. socket_connect_failed( sock );
  409. return;
  410. }
  411. conf_notifier( &sock->notify, 0, POLLOUT );
  412. sock->state = SCK_CONNECTING;
  413. info( "\v\n" );
  414. return;
  415. }
  416. info( "\vok\n" );
  417. socket_connected( sock );
  418. }
  419. static void
  420. socket_connect_failed( conn_t *conn )
  421. {
  422. sys_error( "Cannot connect to %s", conn->name );
  423. socket_close_internal( conn );
  424. free( conn->name );
  425. conn->name = 0;
  426. #ifdef HAVE_IPV6
  427. conn->curr_addr = conn->curr_addr->ai_next;
  428. #else
  429. conn->curr_addr++;
  430. #endif
  431. socket_connect_one( conn );
  432. }
  433. static void
  434. socket_connected( conn_t *conn )
  435. {
  436. #ifdef HAVE_IPV6
  437. freeaddrinfo( conn->addrs );
  438. #endif
  439. conf_notifier( &conn->notify, 0, POLLIN );
  440. conn->state = SCK_READY;
  441. conn->callbacks.connect( 1, conn->callback_aux );
  442. }
  443. static void
  444. socket_connect_bail( conn_t *conn )
  445. {
  446. #ifdef HAVE_IPV6
  447. freeaddrinfo( conn->addrs );
  448. #endif
  449. free( conn->name );
  450. conn->name = 0;
  451. conn->callbacks.connect( 0, conn->callback_aux );
  452. }
  453. static void dispose_chunk( conn_t *conn );
  454. void
  455. socket_close( conn_t *sock )
  456. {
  457. if (sock->fd >= 0)
  458. socket_close_internal( sock );
  459. free( sock->name );
  460. sock->name = 0;
  461. #ifdef HAVE_LIBSSL
  462. if (sock->ssl) {
  463. SSL_free( sock->ssl );
  464. sock->ssl = 0;
  465. wipe_wakeup( &sock->ssl_fake );
  466. }
  467. #endif
  468. #ifdef HAVE_LIBZ
  469. if (sock->in_z) {
  470. inflateEnd( sock->in_z );
  471. free( sock->in_z );
  472. sock->in_z = 0;
  473. deflateEnd( sock->out_z );
  474. free( sock->out_z );
  475. sock->out_z = 0;
  476. wipe_wakeup( &sock->z_fake );
  477. }
  478. #endif
  479. while (sock->write_buf)
  480. dispose_chunk( sock );
  481. free( sock->append_buf );
  482. sock->append_buf = 0;
  483. }
  484. static int
  485. prepare_read( conn_t *sock, char **buf, int *len )
  486. {
  487. int n = sock->offset + sock->bytes;
  488. if (!(*len = sizeof(sock->buf) - n)) {
  489. error( "Socket error: receive buffer full. Probably protocol error.\n" );
  490. socket_fail( sock );
  491. return -1;
  492. }
  493. *buf = sock->buf + n;
  494. return 0;
  495. }
  496. static int
  497. do_read( conn_t *sock, char *buf, int len )
  498. {
  499. int n;
  500. assert( sock->fd >= 0 );
  501. #ifdef HAVE_LIBSSL
  502. if (sock->ssl) {
  503. if ((n = ssl_return( "read from", sock, SSL_read( sock->ssl, buf, len ) )) <= 0)
  504. return n;
  505. if (n == len && SSL_pending( sock->ssl ))
  506. conf_wakeup( &sock->ssl_fake, 0 );
  507. } else
  508. #endif
  509. {
  510. if ((n = read( sock->fd, buf, len )) < 0) {
  511. sys_error( "Socket error: read from %s", sock->name );
  512. socket_fail( sock );
  513. } else if (!n) {
  514. if (sock->state != SCK_CLOSING)
  515. error( "Socket error: read from %s: unexpected EOF\n", sock->name );
  516. socket_fail( sock );
  517. return -1;
  518. }
  519. }
  520. return n;
  521. }
  522. #ifdef HAVE_LIBZ
  523. static void
  524. socket_fill_z( conn_t *sock )
  525. {
  526. char *buf;
  527. int len;
  528. if (prepare_read( sock, &buf, &len ) < 0)
  529. return;
  530. sock->in_z->avail_out = len;
  531. sock->in_z->next_out = (unsigned char *)buf;
  532. if (inflate( sock->in_z, Z_SYNC_FLUSH ) != Z_OK) {
  533. error( "Error decompressing data from %s: %s\n", sock->name, sock->in_z->msg );
  534. socket_fail( sock );
  535. return;
  536. }
  537. if (!sock->in_z->avail_out)
  538. conf_wakeup( &sock->z_fake, 0 );
  539. if ((len = (char *)sock->in_z->next_out - buf)) {
  540. sock->bytes += len;
  541. sock->read_callback( sock->callback_aux );
  542. }
  543. }
  544. #endif
  545. static void
  546. socket_fill( conn_t *sock )
  547. {
  548. #ifdef HAVE_LIBZ
  549. if (sock->in_z) {
  550. /* The timer will preempt reads until the buffer is empty. */
  551. assert( !sock->in_z->avail_in );
  552. sock->in_z->next_in = (uchar *)sock->z_buf;
  553. if ((sock->in_z->avail_in = do_read( sock, sock->z_buf, sizeof(sock->z_buf) )) <= 0)
  554. return;
  555. socket_fill_z( sock );
  556. } else
  557. #endif
  558. {
  559. char *buf;
  560. int len;
  561. if (prepare_read( sock, &buf, &len ) < 0)
  562. return;
  563. if ((len = do_read( sock, buf, len )) <= 0)
  564. return;
  565. sock->bytes += len;
  566. sock->read_callback( sock->callback_aux );
  567. }
  568. }
  569. int
  570. socket_read( conn_t *conn, char *buf, int len )
  571. {
  572. int n = conn->bytes;
  573. if (n > len)
  574. n = len;
  575. memcpy( buf, conn->buf + conn->offset, n );
  576. if (!(conn->bytes -= n))
  577. conn->offset = 0;
  578. else
  579. conn->offset += n;
  580. return n;
  581. }
  582. char *
  583. socket_read_line( conn_t *b )
  584. {
  585. char *p, *s;
  586. int n;
  587. s = b->buf + b->offset;
  588. p = memchr( s + b->scanoff, '\n', b->bytes - b->scanoff );
  589. if (!p) {
  590. b->scanoff = b->bytes;
  591. if (b->offset + b->bytes == sizeof(b->buf)) {
  592. memmove( b->buf, b->buf + b->offset, b->bytes );
  593. b->offset = 0;
  594. }
  595. return 0;
  596. }
  597. n = p + 1 - s;
  598. b->offset += n;
  599. b->bytes -= n;
  600. b->scanoff = 0;
  601. if (p != s && p[-1] == '\r')
  602. p--;
  603. *p = 0;
  604. return s;
  605. }
  606. static int
  607. do_write( conn_t *sock, char *buf, int len )
  608. {
  609. int n;
  610. assert( sock->fd >= 0 );
  611. #ifdef HAVE_LIBSSL
  612. if (sock->ssl)
  613. return ssl_return( "write to", sock, SSL_write( sock->ssl, buf, len ) );
  614. #endif
  615. n = write( sock->fd, buf, len );
  616. if (n < 0) {
  617. if (errno != EAGAIN && errno != EWOULDBLOCK) {
  618. sys_error( "Socket error: write to %s", sock->name );
  619. socket_fail( sock );
  620. } else {
  621. n = 0;
  622. conf_notifier( &sock->notify, POLLIN, POLLOUT );
  623. }
  624. } else if (n != len) {
  625. conf_notifier( &sock->notify, POLLIN, POLLOUT );
  626. }
  627. return n;
  628. }
  629. static void
  630. dispose_chunk( conn_t *conn )
  631. {
  632. buff_chunk_t *bc = conn->write_buf;
  633. if (!(conn->write_buf = bc->next))
  634. conn->write_buf_append = &conn->write_buf;
  635. free( bc );
  636. }
  637. static int
  638. do_queued_write( conn_t *conn )
  639. {
  640. buff_chunk_t *bc;
  641. if (!conn->write_buf)
  642. return 0;
  643. while ((bc = conn->write_buf)) {
  644. int n, len = bc->len - conn->write_offset;
  645. if ((n = do_write( conn, bc->data + conn->write_offset, len )) < 0)
  646. return -1;
  647. if (n != len) {
  648. conn->write_offset += n;
  649. return 0;
  650. }
  651. conn->write_offset = 0;
  652. dispose_chunk( conn );
  653. }
  654. #ifdef HAVE_LIBSSL
  655. if (conn->ssl && SSL_pending( conn->ssl ))
  656. conf_wakeup( &conn->ssl_fake, 0 );
  657. #endif
  658. return conn->write_callback( conn->callback_aux );
  659. }
  660. static void
  661. do_append( conn_t *conn, buff_chunk_t *bc )
  662. {
  663. bc->next = 0;
  664. *conn->write_buf_append = bc;
  665. conn->write_buf_append = &bc->next;
  666. }
  667. /* This is big enough to avoid excessive chunking, but is
  668. * sufficiently small to keep SSL latency low with a slow uplink. */
  669. #define WRITE_CHUNK_SIZE 1024
  670. static void
  671. do_flush( conn_t *conn )
  672. {
  673. buff_chunk_t *bc = conn->append_buf;
  674. #ifdef HAVE_LIBZ
  675. if (conn->out_z) {
  676. int buf_avail = conn->append_avail;
  677. do {
  678. if (!bc) {
  679. buf_avail = WRITE_CHUNK_SIZE;
  680. bc = nfmalloc( offsetof(buff_chunk_t, data) + buf_avail );
  681. bc->len = 0;
  682. }
  683. conn->out_z->next_in = Z_NULL;
  684. conn->out_z->avail_in = 0;
  685. conn->out_z->next_out = (uchar *)bc->data + bc->len;
  686. conn->out_z->avail_out = buf_avail;
  687. if (deflate( conn->out_z, Z_PARTIAL_FLUSH ) != Z_OK) {
  688. error( "Fatal: Compression error: %s\n", conn->out_z->msg );
  689. abort();
  690. }
  691. bc->len = (char *)conn->out_z->next_out - bc->data;
  692. if (bc->len) {
  693. do_append( conn, bc );
  694. bc = 0;
  695. buf_avail = 0;
  696. } else {
  697. buf_avail = conn->out_z->avail_out;
  698. }
  699. } while (!conn->out_z->avail_out);
  700. conn->append_buf = bc;
  701. conn->append_avail = buf_avail;
  702. } else
  703. #endif
  704. if (bc) {
  705. do_append( conn, bc );
  706. conn->append_buf = 0;
  707. #ifdef HAVE_LIBZ
  708. conn->append_avail = 0;
  709. #endif
  710. }
  711. }
  712. int
  713. socket_write( conn_t *conn, conn_iovec_t *iov, int iovcnt )
  714. {
  715. int i, buf_avail, len, offset = 0, total = 0;
  716. buff_chunk_t *bc, *exwb = conn->write_buf;
  717. for (i = 0; i < iovcnt; i++)
  718. total += iov[i].len;
  719. if (total >= WRITE_CHUNK_SIZE && pending_wakeup( &conn->fd_fake )) {
  720. /* If the new data is too big, queue the pending buffer to avoid latency. */
  721. do_flush( conn );
  722. }
  723. bc = conn->append_buf;
  724. #ifdef HAVE_LIBZ
  725. buf_avail = conn->append_avail;
  726. #endif
  727. while (total) {
  728. if (!bc) {
  729. /* We don't do anything special when compressing, as there is no way to
  730. * predict a reasonable output buffer size anyway - deflatePending() does
  731. * not account for consumed but not yet compressed input, and adding up
  732. * the deflateBound()s would be a tad *too* pessimistic. */
  733. buf_avail = total > WRITE_CHUNK_SIZE ? total : WRITE_CHUNK_SIZE;
  734. bc = nfmalloc( offsetof(buff_chunk_t, data) + buf_avail );
  735. bc->len = 0;
  736. #ifndef HAVE_LIBZ
  737. } else {
  738. /* A pending buffer will always be of standard size - over-sized
  739. * buffers are immediately filled and queued. */
  740. buf_avail = WRITE_CHUNK_SIZE - bc->len;
  741. #endif
  742. }
  743. while (total) {
  744. len = iov->len - offset;
  745. #ifdef HAVE_LIBZ
  746. if (conn->out_z) {
  747. conn->out_z->next_in = (uchar *)iov->buf + offset;
  748. conn->out_z->avail_in = len;
  749. conn->out_z->next_out = (uchar *)bc->data + bc->len;
  750. conn->out_z->avail_out = buf_avail;
  751. if (deflate( conn->out_z, Z_NO_FLUSH ) != Z_OK) {
  752. error( "Fatal: Compression error: %s\n", conn->out_z->msg );
  753. abort();
  754. }
  755. bc->len = (char *)conn->out_z->next_out - bc->data;
  756. buf_avail = conn->out_z->avail_out;
  757. len -= conn->out_z->avail_in;
  758. } else
  759. #endif
  760. {
  761. if (len > buf_avail)
  762. len = buf_avail;
  763. memcpy( bc->data + bc->len, iov->buf + offset, len );
  764. bc->len += len;
  765. buf_avail -= len;
  766. }
  767. offset += len;
  768. total -= len;
  769. if (offset == iov->len) {
  770. if (iov->takeOwn == GiveOwn)
  771. free( iov->buf );
  772. iov++;
  773. offset = 0;
  774. }
  775. if (!buf_avail) {
  776. do_append( conn, bc );
  777. bc = 0;
  778. break;
  779. }
  780. }
  781. }
  782. conn->append_buf = bc;
  783. #ifdef HAVE_LIBZ
  784. conn->append_avail = buf_avail;
  785. #endif
  786. /* Queue the pending write once the main loop goes idle. */
  787. conf_wakeup( &conn->fd_fake,
  788. #ifdef HAVE_LIBZ
  789. /* Always give zlib a chance to flush its internal buffer. */
  790. conn->out_z ||
  791. #endif
  792. bc ? 0 : -1 );
  793. /* If no writes were queued before, ensure that flushing commences. */
  794. if (!exwb)
  795. return do_queued_write( conn );
  796. return 0;
  797. }
  798. static void
  799. socket_fd_cb( int events, void *aux )
  800. {
  801. conn_t *conn = (conn_t *)aux;
  802. if ((events & POLLERR) || conn->state == SCK_CONNECTING) {
  803. int soerr;
  804. socklen_t selen = sizeof(soerr);
  805. if (getsockopt( conn->fd, SOL_SOCKET, SO_ERROR, &soerr, &selen )) {
  806. perror( "getsockopt" );
  807. exit( 1 );
  808. }
  809. errno = soerr;
  810. if (conn->state == SCK_CONNECTING) {
  811. if (errno)
  812. socket_connect_failed( conn );
  813. else
  814. socket_connected( conn );
  815. return;
  816. }
  817. sys_error( "Socket error from %s", conn->name );
  818. socket_fail( conn );
  819. return;
  820. }
  821. if (events & POLLOUT)
  822. conf_notifier( &conn->notify, POLLIN, 0 );
  823. #ifdef HAVE_LIBSSL
  824. if (conn->state == SCK_STARTTLS) {
  825. start_tls_p2( conn );
  826. return;
  827. }
  828. if (conn->ssl) {
  829. if (do_queued_write( conn ) < 0)
  830. return;
  831. socket_fill( conn );
  832. return;
  833. }
  834. #endif
  835. if ((events & POLLOUT) && do_queued_write( conn ) < 0)
  836. return;
  837. if (events & POLLIN)
  838. socket_fill( conn );
  839. }
  840. static void
  841. socket_fake_cb( void *aux )
  842. {
  843. conn_t *conn = (conn_t *)aux;
  844. buff_chunk_t *exwb = conn->write_buf;
  845. do_flush( conn );
  846. /* If no writes were queued before, ensure that flushing commences. */
  847. if (!exwb)
  848. do_queued_write( conn );
  849. }
  850. #ifdef HAVE_LIBZ
  851. static void
  852. z_fake_cb( void *aux )
  853. {
  854. conn_t *conn = (conn_t *)aux;
  855. socket_fill_z( conn );
  856. }
  857. #endif
  858. #ifdef HAVE_LIBSSL
  859. static void
  860. ssl_fake_cb( void *aux )
  861. {
  862. conn_t *conn = (conn_t *)aux;
  863. socket_fill( conn );
  864. }
  865. #endif