socket.c 22 KB

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