socket.c 26 KB

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