socket.c 22 KB

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