socket.c 26 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121
  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. void
  380. socket_connect( conn_t *sock, void (*cb)( int ok, void *aux ) )
  381. {
  382. const server_conf_t *conf = sock->conf;
  383. sock->callbacks.connect = cb;
  384. /* open connection to server */
  385. if (conf->tunnel) {
  386. int a[2];
  387. nfasprintf( &sock->name, "tunnel '%s'", conf->tunnel );
  388. infon( "Starting %s... ", sock->name );
  389. if (socketpair( PF_UNIX, SOCK_STREAM, 0, a )) {
  390. perror( "socketpair" );
  391. exit( 1 );
  392. }
  393. if (fork() == 0) {
  394. if (dup2( a[0], 0 ) == -1 || dup2( a[0], 1 ) == -1)
  395. _exit( 127 );
  396. close( a[0] );
  397. close( a[1] );
  398. execl( "/bin/sh", "sh", "-c", conf->tunnel, (char *)0 );
  399. _exit( 127 );
  400. }
  401. close( a[0] );
  402. socket_open_internal( sock, a[1] );
  403. info( "\vok\n" );
  404. socket_connected( sock );
  405. } else {
  406. #ifdef HAVE_IPV6
  407. int gaierr;
  408. struct addrinfo hints;
  409. memset( &hints, 0, sizeof(hints) );
  410. hints.ai_family = AF_UNSPEC;
  411. hints.ai_socktype = SOCK_STREAM;
  412. hints.ai_flags = AI_ADDRCONFIG;
  413. infon( "Resolving %s... ", conf->host );
  414. if ((gaierr = getaddrinfo( conf->host, NULL, &hints, &sock->addrs ))) {
  415. error( "Error: Cannot resolve server '%s': %s\n", conf->host, gai_strerror( gaierr ) );
  416. socket_connect_bail( sock );
  417. return;
  418. }
  419. info( "\vok\n" );
  420. sock->curr_addr = sock->addrs;
  421. #else
  422. struct hostent *he;
  423. infon( "Resolving %s... ", conf->host );
  424. he = gethostbyname( conf->host );
  425. if (!he) {
  426. error( "Error: Cannot resolve server '%s': %s\n", conf->host, hstrerror( h_errno ) );
  427. socket_connect_bail( sock );
  428. return;
  429. }
  430. info( "\vok\n" );
  431. sock->curr_addr = he->h_addr_list;
  432. #endif
  433. socket_connect_one( sock );
  434. }
  435. }
  436. static void
  437. socket_connect_one( conn_t *sock )
  438. {
  439. int s;
  440. #ifdef HAVE_IPV6
  441. struct addrinfo *ai;
  442. #else
  443. struct {
  444. struct sockaddr_in ai_addr[1];
  445. } ai[1];
  446. #endif
  447. #ifdef HAVE_IPV6
  448. if (!(ai = sock->curr_addr)) {
  449. #else
  450. if (!*sock->curr_addr) {
  451. #endif
  452. error( "No working address found for %s\n", sock->conf->host );
  453. socket_connect_bail( sock );
  454. return;
  455. }
  456. #ifdef HAVE_IPV6
  457. if (ai->ai_family == AF_INET6) {
  458. struct sockaddr_in6 *in6 = ((struct sockaddr_in6 *)ai->ai_addr);
  459. char sockname[64];
  460. in6->sin6_port = htons( sock->conf->port );
  461. nfasprintf( &sock->name, "%s ([%s]:%hu)",
  462. sock->conf->host, inet_ntop( AF_INET6, &in6->sin6_addr, sockname, sizeof(sockname) ), sock->conf->port );
  463. } else
  464. #endif
  465. {
  466. struct sockaddr_in *in = ((struct sockaddr_in *)ai->ai_addr);
  467. #ifndef HAVE_IPV6
  468. memset( in, 0, sizeof(*in) );
  469. in->sin_family = AF_INET;
  470. in->sin_addr.s_addr = *((int *)*sock->curr_addr);
  471. #endif
  472. in->sin_port = htons( sock->conf->port );
  473. nfasprintf( &sock->name, "%s (%s:%hu)",
  474. sock->conf->host, inet_ntoa( in->sin_addr ), sock->conf->port );
  475. }
  476. #ifdef HAVE_IPV6
  477. s = socket( ai->ai_family, SOCK_STREAM, 0 );
  478. #else
  479. s = socket( PF_INET, SOCK_STREAM, 0 );
  480. #endif
  481. if (s < 0) {
  482. socket_connect_next( sock );
  483. return;
  484. }
  485. socket_open_internal( sock, s );
  486. infon( "Connecting to %s... ", sock->name );
  487. #ifdef HAVE_IPV6
  488. if (connect( s, ai->ai_addr, ai->ai_addrlen )) {
  489. #else
  490. if (connect( s, ai->ai_addr, sizeof(*ai->ai_addr) )) {
  491. #endif
  492. if (errno != EINPROGRESS) {
  493. socket_connect_failed( sock );
  494. return;
  495. }
  496. conf_notifier( &sock->notify, 0, POLLOUT );
  497. socket_expect_read( sock, 1 );
  498. sock->state = SCK_CONNECTING;
  499. info( "\v\n" );
  500. return;
  501. }
  502. info( "\vok\n" );
  503. socket_connected( sock );
  504. }
  505. static void
  506. socket_connect_next( conn_t *conn )
  507. {
  508. sys_error( "Cannot connect to %s", conn->name );
  509. free( conn->name );
  510. conn->name = 0;
  511. #ifdef HAVE_IPV6
  512. conn->curr_addr = conn->curr_addr->ai_next;
  513. #else
  514. conn->curr_addr++;
  515. #endif
  516. socket_connect_one( conn );
  517. }
  518. static void
  519. socket_connect_failed( conn_t *conn )
  520. {
  521. socket_close_internal( conn );
  522. socket_connect_next( conn );
  523. }
  524. static void
  525. socket_connected( conn_t *conn )
  526. {
  527. #ifdef HAVE_IPV6
  528. if (conn->addrs) {
  529. freeaddrinfo( conn->addrs );
  530. conn->addrs = 0;
  531. }
  532. #endif
  533. conf_notifier( &conn->notify, 0, POLLIN );
  534. socket_expect_read( conn, 0 );
  535. conn->state = SCK_READY;
  536. conn->callbacks.connect( 1, conn->callback_aux );
  537. }
  538. static void
  539. socket_cleanup_names( conn_t *conn )
  540. {
  541. #ifdef HAVE_IPV6
  542. if (conn->addrs) {
  543. freeaddrinfo( conn->addrs );
  544. conn->addrs = 0;
  545. }
  546. #endif
  547. free( conn->name );
  548. conn->name = 0;
  549. }
  550. static void
  551. socket_connect_bail( conn_t *conn )
  552. {
  553. socket_cleanup_names( conn );
  554. conn->callbacks.connect( 0, conn->callback_aux );
  555. }
  556. static void dispose_chunk( conn_t *conn );
  557. void
  558. socket_close( conn_t *sock )
  559. {
  560. if (sock->fd >= 0)
  561. socket_close_internal( sock );
  562. socket_cleanup_names( sock );
  563. #ifdef HAVE_LIBSSL
  564. if (sock->ssl) {
  565. SSL_free( sock->ssl );
  566. sock->ssl = 0;
  567. wipe_wakeup( &sock->ssl_fake );
  568. }
  569. #endif
  570. #ifdef HAVE_LIBZ
  571. if (sock->in_z) {
  572. inflateEnd( sock->in_z );
  573. free( sock->in_z );
  574. sock->in_z = 0;
  575. deflateEnd( sock->out_z );
  576. free( sock->out_z );
  577. sock->out_z = 0;
  578. wipe_wakeup( &sock->z_fake );
  579. }
  580. #endif
  581. while (sock->write_buf)
  582. dispose_chunk( sock );
  583. free( sock->append_buf );
  584. sock->append_buf = 0;
  585. }
  586. static int
  587. prepare_read( conn_t *sock, char **buf, int *len )
  588. {
  589. int n = sock->offset + sock->bytes;
  590. if (!(*len = sizeof(sock->buf) - n)) {
  591. error( "Socket error: receive buffer full. Probably protocol error.\n" );
  592. socket_fail( sock );
  593. return -1;
  594. }
  595. *buf = sock->buf + n;
  596. return 0;
  597. }
  598. static int
  599. do_read( conn_t *sock, char *buf, int len )
  600. {
  601. int n;
  602. assert( sock->fd >= 0 );
  603. if (pending_wakeup( &sock->fd_timeout ))
  604. conf_wakeup( &sock->fd_timeout, sock->conf->timeout );
  605. #ifdef HAVE_LIBSSL
  606. if (sock->ssl) {
  607. if ((n = ssl_return( "read from", sock, SSL_read( sock->ssl, buf, len ) )) <= 0)
  608. return n;
  609. if (n == len && SSL_pending( sock->ssl ))
  610. conf_wakeup( &sock->ssl_fake, 0 );
  611. } else
  612. #endif
  613. {
  614. if ((n = read( sock->fd, buf, len )) < 0) {
  615. sys_error( "Socket error: read from %s", sock->name );
  616. socket_fail( sock );
  617. } else if (!n) {
  618. /* EOF. Callers take the short path out, so signal higher layers from here. */
  619. sock->state = SCK_EOF;
  620. sock->read_callback( sock->callback_aux );
  621. }
  622. }
  623. return n;
  624. }
  625. #ifdef HAVE_LIBZ
  626. static void
  627. socket_fill_z( conn_t *sock )
  628. {
  629. char *buf;
  630. int len, ret;
  631. if (prepare_read( sock, &buf, &len ) < 0)
  632. return;
  633. sock->in_z->avail_out = len;
  634. sock->in_z->next_out = (unsigned char *)buf;
  635. ret = inflate( sock->in_z, Z_SYNC_FLUSH );
  636. /* Z_BUF_ERROR happens here when the previous call both consumed
  637. * all input and exactly filled up the output buffer. */
  638. if (ret != Z_OK && ret != Z_BUF_ERROR && ret != Z_STREAM_END) {
  639. error( "Error decompressing data from %s: %s\n", sock->name, z_err_msg( ret, sock->in_z ) );
  640. socket_fail( sock );
  641. return;
  642. }
  643. if (!sock->in_z->avail_out)
  644. conf_wakeup( &sock->z_fake, 0 );
  645. if ((len = (char *)sock->in_z->next_out - buf)) {
  646. sock->bytes += len;
  647. sock->read_callback( sock->callback_aux );
  648. }
  649. }
  650. #endif
  651. static void
  652. socket_fill( conn_t *sock )
  653. {
  654. #ifdef HAVE_LIBZ
  655. if (sock->in_z) {
  656. int ret;
  657. /* The timer will preempt reads until the buffer is empty. */
  658. assert( !sock->in_z->avail_in );
  659. sock->in_z->next_in = (uchar *)sock->z_buf;
  660. if ((ret = do_read( sock, sock->z_buf, sizeof(sock->z_buf) )) <= 0)
  661. return;
  662. sock->in_z->avail_in = ret;
  663. socket_fill_z( sock );
  664. } else
  665. #endif
  666. {
  667. char *buf;
  668. int len;
  669. if (prepare_read( sock, &buf, &len ) < 0)
  670. return;
  671. if ((len = do_read( sock, buf, len )) <= 0)
  672. return;
  673. sock->bytes += len;
  674. sock->read_callback( sock->callback_aux );
  675. }
  676. }
  677. void
  678. socket_expect_read( conn_t *conn, int expect )
  679. {
  680. if (conn->conf->timeout > 0 && expect != pending_wakeup( &conn->fd_timeout ))
  681. conf_wakeup( &conn->fd_timeout, expect ? conn->conf->timeout : -1 );
  682. }
  683. int
  684. socket_read( conn_t *conn, char *buf, int len )
  685. {
  686. int n = conn->bytes;
  687. if (!n && conn->state == SCK_EOF)
  688. return -1;
  689. if (n > len)
  690. n = len;
  691. memcpy( buf, conn->buf + conn->offset, n );
  692. if (!(conn->bytes -= n))
  693. conn->offset = 0;
  694. else
  695. conn->offset += n;
  696. return n;
  697. }
  698. char *
  699. socket_read_line( conn_t *b )
  700. {
  701. char *p, *s;
  702. int n;
  703. s = b->buf + b->offset;
  704. p = memchr( s + b->scanoff, '\n', b->bytes - b->scanoff );
  705. if (!p) {
  706. b->scanoff = b->bytes;
  707. if (b->offset + b->bytes == sizeof(b->buf)) {
  708. memmove( b->buf, b->buf + b->offset, b->bytes );
  709. b->offset = 0;
  710. }
  711. if (b->state == SCK_EOF)
  712. return (void *)~0;
  713. return 0;
  714. }
  715. n = p + 1 - s;
  716. b->offset += n;
  717. b->bytes -= n;
  718. b->scanoff = 0;
  719. if (p != s && p[-1] == '\r')
  720. p--;
  721. *p = 0;
  722. return s;
  723. }
  724. static int
  725. do_write( conn_t *sock, char *buf, int len )
  726. {
  727. int n;
  728. assert( sock->fd >= 0 );
  729. #ifdef HAVE_LIBSSL
  730. if (sock->ssl)
  731. return ssl_return( "write to", sock, SSL_write( sock->ssl, buf, len ) );
  732. #endif
  733. n = write( sock->fd, buf, len );
  734. if (n < 0) {
  735. if (errno != EAGAIN && errno != EWOULDBLOCK) {
  736. sys_error( "Socket error: write to %s", sock->name );
  737. socket_fail( sock );
  738. } else {
  739. n = 0;
  740. conf_notifier( &sock->notify, POLLIN, POLLOUT );
  741. }
  742. } else if (n != len) {
  743. conf_notifier( &sock->notify, POLLIN, POLLOUT );
  744. }
  745. return n;
  746. }
  747. static void
  748. dispose_chunk( conn_t *conn )
  749. {
  750. buff_chunk_t *bc = conn->write_buf;
  751. if (!(conn->write_buf = bc->next))
  752. conn->write_buf_append = &conn->write_buf;
  753. conn->buffer_mem -= bc->len;
  754. free( bc );
  755. }
  756. static int
  757. do_queued_write( conn_t *conn )
  758. {
  759. buff_chunk_t *bc;
  760. if (!conn->write_buf)
  761. return 0;
  762. while ((bc = conn->write_buf)) {
  763. int n, len = bc->len - conn->write_offset;
  764. if ((n = do_write( conn, bc->data + conn->write_offset, len )) < 0)
  765. return -1;
  766. if (n != len) {
  767. conn->write_offset += n;
  768. conn->writing = 1;
  769. return 0;
  770. }
  771. conn->write_offset = 0;
  772. dispose_chunk( conn );
  773. }
  774. #ifdef HAVE_LIBSSL
  775. if (conn->ssl && SSL_pending( conn->ssl ))
  776. conf_wakeup( &conn->ssl_fake, 0 );
  777. #endif
  778. conn->writing = 0;
  779. conn->write_callback( conn->callback_aux );
  780. return -1;
  781. }
  782. static void
  783. do_append( conn_t *conn, buff_chunk_t *bc )
  784. {
  785. bc->next = 0;
  786. conn->buffer_mem += bc->len;
  787. *conn->write_buf_append = bc;
  788. conn->write_buf_append = &bc->next;
  789. }
  790. /* This is big enough to avoid excessive chunking, but is
  791. * sufficiently small to keep SSL latency low with a slow uplink. */
  792. #define WRITE_CHUNK_SIZE 1024
  793. static void
  794. do_flush( conn_t *conn )
  795. {
  796. buff_chunk_t *bc = conn->append_buf;
  797. #ifdef HAVE_LIBZ
  798. if (conn->out_z) {
  799. int buf_avail = conn->append_avail;
  800. if (!conn->z_written)
  801. return;
  802. do {
  803. int ret;
  804. if (!bc) {
  805. buf_avail = WRITE_CHUNK_SIZE;
  806. bc = nfmalloc( offsetof(buff_chunk_t, data) + buf_avail );
  807. bc->len = 0;
  808. }
  809. conn->out_z->next_in = Z_NULL;
  810. conn->out_z->avail_in = 0;
  811. conn->out_z->next_out = (uchar *)bc->data + bc->len;
  812. conn->out_z->avail_out = buf_avail;
  813. /* Z_BUF_ERROR cannot happen here, as zlib suppresses the error
  814. * both upon increasing the flush level (1st iteration) and upon
  815. * a no-op after the output buffer was full (later iterations). */
  816. if ((ret = deflate( conn->out_z, Z_PARTIAL_FLUSH )) != Z_OK) {
  817. error( "Fatal: Compression error: %s\n", z_err_msg( ret, conn->out_z ) );
  818. abort();
  819. }
  820. bc->len = (char *)conn->out_z->next_out - bc->data;
  821. if (bc->len) {
  822. do_append( conn, bc );
  823. bc = 0;
  824. buf_avail = 0;
  825. } else {
  826. buf_avail = conn->out_z->avail_out;
  827. }
  828. } while (!conn->out_z->avail_out);
  829. conn->append_buf = bc;
  830. conn->append_avail = buf_avail;
  831. conn->z_written = 0;
  832. } else
  833. #endif
  834. if (bc) {
  835. do_append( conn, bc );
  836. conn->append_buf = 0;
  837. #ifdef HAVE_LIBZ
  838. conn->append_avail = 0;
  839. #endif
  840. }
  841. }
  842. void
  843. socket_write( conn_t *conn, conn_iovec_t *iov, int iovcnt )
  844. {
  845. int i, buf_avail, len, offset = 0, total = 0;
  846. buff_chunk_t *bc;
  847. for (i = 0; i < iovcnt; i++)
  848. total += iov[i].len;
  849. if (total >= WRITE_CHUNK_SIZE) {
  850. /* If the new data is too big, queue the pending buffer to avoid latency. */
  851. do_flush( conn );
  852. }
  853. bc = conn->append_buf;
  854. #ifdef HAVE_LIBZ
  855. buf_avail = conn->append_avail;
  856. #endif
  857. while (total) {
  858. if (!bc) {
  859. /* We don't do anything special when compressing, as there is no way to
  860. * predict a reasonable output buffer size anyway - deflatePending() does
  861. * not account for consumed but not yet compressed input, and adding up
  862. * the deflateBound()s would be a tad *too* pessimistic. */
  863. buf_avail = total > WRITE_CHUNK_SIZE ? total : WRITE_CHUNK_SIZE;
  864. bc = nfmalloc( offsetof(buff_chunk_t, data) + buf_avail );
  865. bc->len = 0;
  866. #ifndef HAVE_LIBZ
  867. } else {
  868. /* A pending buffer will always be of standard size - over-sized
  869. * buffers are immediately filled and queued. */
  870. buf_avail = WRITE_CHUNK_SIZE - bc->len;
  871. #endif
  872. }
  873. while (total) {
  874. len = iov->len - offset;
  875. #ifdef HAVE_LIBZ
  876. if (conn->out_z) {
  877. int ret;
  878. conn->out_z->next_in = (uchar *)iov->buf + offset;
  879. conn->out_z->avail_in = len;
  880. conn->out_z->next_out = (uchar *)bc->data + bc->len;
  881. conn->out_z->avail_out = buf_avail;
  882. /* Z_BUF_ERROR is impossible here, as the input buffer always has data,
  883. * and the output buffer always has space. */
  884. if ((ret = deflate( conn->out_z, Z_NO_FLUSH )) != Z_OK) {
  885. error( "Fatal: Compression error: %s\n", z_err_msg( ret, conn->out_z ) );
  886. abort();
  887. }
  888. bc->len = (char *)conn->out_z->next_out - bc->data;
  889. buf_avail = conn->out_z->avail_out;
  890. len -= conn->out_z->avail_in;
  891. conn->z_written = 1;
  892. } else
  893. #endif
  894. {
  895. if (len > buf_avail)
  896. len = buf_avail;
  897. memcpy( bc->data + bc->len, iov->buf + offset, len );
  898. bc->len += len;
  899. buf_avail -= len;
  900. }
  901. offset += len;
  902. total -= len;
  903. if (offset == iov->len) {
  904. if (iov->takeOwn == GiveOwn)
  905. free( iov->buf );
  906. iov++;
  907. offset = 0;
  908. }
  909. if (!buf_avail) {
  910. do_append( conn, bc );
  911. bc = 0;
  912. break;
  913. }
  914. }
  915. }
  916. conn->append_buf = bc;
  917. #ifdef HAVE_LIBZ
  918. conn->append_avail = buf_avail;
  919. #endif
  920. conf_wakeup( &conn->fd_fake, 0 );
  921. }
  922. static void
  923. socket_fd_cb( int events, void *aux )
  924. {
  925. conn_t *conn = (conn_t *)aux;
  926. if ((events & POLLERR) || conn->state == SCK_CONNECTING) {
  927. int soerr;
  928. socklen_t selen = sizeof(soerr);
  929. if (getsockopt( conn->fd, SOL_SOCKET, SO_ERROR, &soerr, &selen )) {
  930. perror( "getsockopt" );
  931. exit( 1 );
  932. }
  933. errno = soerr;
  934. if (conn->state == SCK_CONNECTING) {
  935. if (errno)
  936. socket_connect_failed( conn );
  937. else
  938. socket_connected( conn );
  939. return;
  940. }
  941. sys_error( "Socket error from %s", conn->name );
  942. socket_fail( conn );
  943. return;
  944. }
  945. if (events & POLLOUT)
  946. conf_notifier( &conn->notify, POLLIN, 0 );
  947. #ifdef HAVE_LIBSSL
  948. if (conn->state == SCK_STARTTLS) {
  949. start_tls_p2( conn );
  950. return;
  951. }
  952. if (conn->ssl) {
  953. if (do_queued_write( conn ) < 0)
  954. return;
  955. socket_fill( conn );
  956. return;
  957. }
  958. #endif
  959. if ((events & POLLOUT) && do_queued_write( conn ) < 0)
  960. return;
  961. if (events & POLLIN)
  962. socket_fill( conn );
  963. }
  964. static void
  965. socket_fake_cb( void *aux )
  966. {
  967. conn_t *conn = (conn_t *)aux;
  968. /* Ensure that a pending write gets queued. */
  969. do_flush( conn );
  970. /* If no writes are ongoing, start writing now. */
  971. if (!conn->writing)
  972. do_queued_write( conn );
  973. }
  974. static void
  975. socket_timeout_cb( void *aux )
  976. {
  977. conn_t *conn = (conn_t *)aux;
  978. if (conn->state == SCK_CONNECTING) {
  979. errno = ETIMEDOUT;
  980. socket_connect_failed( conn );
  981. } else {
  982. error( "Socket error on %s: timeout.\n", conn->name );
  983. socket_fail( conn );
  984. }
  985. }
  986. #ifdef HAVE_LIBZ
  987. static void
  988. z_fake_cb( void *aux )
  989. {
  990. conn_t *conn = (conn_t *)aux;
  991. socket_fill_z( conn );
  992. }
  993. #endif
  994. #ifdef HAVE_LIBSSL
  995. static void
  996. ssl_fake_cb( void *aux )
  997. {
  998. conn_t *conn = (conn_t *)aux;
  999. socket_fill( conn );
  1000. }
  1001. #endif