socket.c 24 KB

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