socket.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
  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. /* This must come before isync.h to avoid our #define S messing up
  24. * blowfish.h on MacOS X. */
  25. #include <config.h>
  26. #ifdef HAVE_LIBSSL
  27. # include <openssl/ssl.h>
  28. # include <openssl/err.h>
  29. # include <openssl/hmac.h>
  30. # include <openssl/x509v3.h>
  31. #endif
  32. #include "isync.h"
  33. #include <assert.h>
  34. #include <unistd.h>
  35. #include <stdlib.h>
  36. #include <stddef.h>
  37. #include <errno.h>
  38. #include <string.h>
  39. #include <fcntl.h>
  40. #include <sys/socket.h>
  41. #include <sys/ioctl.h>
  42. #include <netinet/in.h>
  43. #include <netinet/tcp.h>
  44. #include <arpa/inet.h>
  45. #include <netdb.h>
  46. enum {
  47. SCK_CONNECTING,
  48. #ifdef HAVE_LIBSSL
  49. SCK_STARTTLS,
  50. #endif
  51. SCK_READY
  52. };
  53. static void
  54. socket_fail( conn_t *conn )
  55. {
  56. conn->bad_callback( conn->callback_aux );
  57. }
  58. #ifdef HAVE_LIBSSL
  59. static int ssl_data_idx;
  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_fd( conn->fd, 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. error( "Socket error: secure %s %s: unexpected EOF\n", func, conn->name );
  77. else
  78. sys_error( "Socket error: secure %s %s", func, conn->name );
  79. } else {
  80. error( "Socket error: secure %s %s: %s\n", func, conn->name, ERR_error_string( err, 0 ) );
  81. }
  82. break;
  83. default:
  84. error( "Socket error: secure %s %s: unhandled SSL error %d\n", func, conn->name, err );
  85. break;
  86. }
  87. if (conn->state == SCK_STARTTLS)
  88. conn->callbacks.starttls( 0, conn->callback_aux );
  89. else
  90. socket_fail( conn );
  91. return -1;
  92. }
  93. /* Some of this code is inspired by / lifted from mutt. */
  94. static int
  95. host_matches( const char *host, const char *pattern )
  96. {
  97. if (pattern[0] == '*' && pattern[1] == '.') {
  98. pattern += 2;
  99. if (!(host = strchr( host, '.' )))
  100. return 0;
  101. host++;
  102. }
  103. return *host && *pattern && !strcasecmp( host, pattern );
  104. }
  105. static int
  106. verify_hostname( X509 *cert, const char *hostname )
  107. {
  108. int i, len, found;
  109. X509_NAME *subj;
  110. STACK_OF(GENERAL_NAME) *subj_alt_names;
  111. char cname[1000];
  112. /* try the DNS subjectAltNames */
  113. found = 0;
  114. if ((subj_alt_names = X509_get_ext_d2i( cert, NID_subject_alt_name, NULL, NULL ))) {
  115. int num_subj_alt_names = sk_GENERAL_NAME_num( subj_alt_names );
  116. for (i = 0; i < num_subj_alt_names; i++) {
  117. GENERAL_NAME *subj_alt_name = sk_GENERAL_NAME_value( subj_alt_names, i );
  118. if (subj_alt_name->type == GEN_DNS &&
  119. strlen( (const char *)subj_alt_name->d.ia5->data ) == (size_t)subj_alt_name->d.ia5->length &&
  120. host_matches( hostname, (const char *)(subj_alt_name->d.ia5->data) ))
  121. {
  122. found = 1;
  123. break;
  124. }
  125. }
  126. sk_GENERAL_NAME_pop_free( subj_alt_names, GENERAL_NAME_free );
  127. }
  128. if (found)
  129. return 0;
  130. /* try the common name */
  131. if (!(subj = X509_get_subject_name( cert ))) {
  132. error( "Error, cannot get certificate subject\n" );
  133. return -1;
  134. }
  135. if ((len = X509_NAME_get_text_by_NID( subj, NID_commonName, cname, sizeof(cname) )) < 0) {
  136. error( "Error, cannot get certificate common name\n" );
  137. return -1;
  138. }
  139. if (strlen( cname ) == (size_t)len && host_matches( hostname, cname ))
  140. return 0;
  141. error( "Error, certificate owner does not match hostname %s\n", hostname );
  142. return -1;
  143. }
  144. static int
  145. verify_cert_host( const server_conf_t *conf, conn_t *sock )
  146. {
  147. X509 *cert;
  148. if (!conf->host || sock->force_trusted > 0)
  149. return 0;
  150. cert = SSL_get_peer_certificate( sock->ssl );
  151. if (!cert) {
  152. error( "Error, no server certificate\n" );
  153. return -1;
  154. }
  155. return verify_hostname( cert, conf->host );
  156. }
  157. static int
  158. ssl_verify_callback( int ok, X509_STORE_CTX *ctx )
  159. {
  160. SSL *ssl = X509_STORE_CTX_get_ex_data( ctx, SSL_get_ex_data_X509_STORE_CTX_idx() );
  161. conn_t *conn = SSL_get_ex_data( ssl, ssl_data_idx );
  162. if (!conn->force_trusted) {
  163. X509 *cert = sk_X509_value( ctx->chain, 0 );
  164. STACK_OF(X509_OBJECT) *trusted = ctx->ctx->objs;
  165. unsigned i;
  166. conn->force_trusted = -1;
  167. for (i = 0; i < conn->conf->num_trusted; i++) {
  168. if (!X509_cmp( cert, sk_X509_OBJECT_value( trusted, i )->data.x509 )) {
  169. conn->force_trusted = 1;
  170. break;
  171. }
  172. }
  173. }
  174. if (conn->force_trusted > 0)
  175. ok = 1;
  176. return ok;
  177. }
  178. static int
  179. init_ssl_ctx( const server_conf_t *conf )
  180. {
  181. server_conf_t *mconf = (server_conf_t *)conf;
  182. int options = 0;
  183. if (conf->SSLContext)
  184. return conf->ssl_ctx_valid;
  185. mconf->SSLContext = SSL_CTX_new( SSLv23_client_method() );
  186. if (!conf->use_sslv2)
  187. options |= SSL_OP_NO_SSLv2;
  188. if (!conf->use_sslv3)
  189. options |= SSL_OP_NO_SSLv3;
  190. if (!conf->use_tlsv1)
  191. options |= SSL_OP_NO_TLSv1;
  192. #ifdef SSL_OP_NO_TLSv1_1
  193. if (!conf->use_tlsv11)
  194. options |= SSL_OP_NO_TLSv1_1;
  195. #endif
  196. #ifdef SSL_OP_NO_TLSv1_2
  197. if (!conf->use_tlsv12)
  198. options |= SSL_OP_NO_TLSv1_2;
  199. #endif
  200. SSL_CTX_set_options( mconf->SSLContext, options );
  201. if (conf->cert_file && !SSL_CTX_load_verify_locations( mconf->SSLContext, conf->cert_file, 0 )) {
  202. error( "Error while loading certificate file '%s': %s\n",
  203. conf->cert_file, ERR_error_string( ERR_get_error(), 0 ) );
  204. return 0;
  205. }
  206. mconf->num_trusted = sk_X509_OBJECT_num( SSL_CTX_get_cert_store( mconf->SSLContext )->objs );
  207. if (!SSL_CTX_set_default_verify_paths( mconf->SSLContext ))
  208. warn( "Warning: Unable to load default certificate files: %s\n",
  209. ERR_error_string( ERR_get_error(), 0 ) );
  210. SSL_CTX_set_verify( mconf->SSLContext, SSL_VERIFY_PEER, ssl_verify_callback );
  211. mconf->ssl_ctx_valid = 1;
  212. return 1;
  213. }
  214. static void start_tls_p2( conn_t * );
  215. static void start_tls_p3( conn_t *, int );
  216. void
  217. socket_start_tls( conn_t *conn, void (*cb)( int ok, void *aux ) )
  218. {
  219. static int ssl_inited;
  220. conn->callbacks.starttls = cb;
  221. if (!ssl_inited) {
  222. SSL_library_init();
  223. SSL_load_error_strings();
  224. ssl_data_idx = SSL_get_ex_new_index( 0, NULL, NULL, NULL, NULL );
  225. ssl_inited = 1;
  226. }
  227. if (!init_ssl_ctx( conn->conf )) {
  228. start_tls_p3( conn, 0 );
  229. return;
  230. }
  231. conn->ssl = SSL_new( ((server_conf_t *)conn->conf)->SSLContext );
  232. SSL_set_fd( conn->ssl, conn->fd );
  233. SSL_set_mode( conn->ssl, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER );
  234. SSL_set_ex_data( conn->ssl, ssl_data_idx, conn );
  235. conn->state = SCK_STARTTLS;
  236. start_tls_p2( conn );
  237. }
  238. static void
  239. start_tls_p2( conn_t *conn )
  240. {
  241. if (ssl_return( "connect to", conn, SSL_connect( conn->ssl ) ) > 0) {
  242. /* verify whether the server hostname matches the certificate */
  243. if (verify_cert_host( conn->conf, conn )) {
  244. start_tls_p3( conn, 0 );
  245. } else {
  246. info( "Connection is now encrypted\n" );
  247. start_tls_p3( conn, 1 );
  248. }
  249. }
  250. }
  251. static void start_tls_p3( conn_t *conn, int ok )
  252. {
  253. conn->state = SCK_READY;
  254. conn->callbacks.starttls( ok, conn->callback_aux );
  255. }
  256. #endif /* HAVE_LIBSSL */
  257. static void socket_fd_cb( int, void * );
  258. static void socket_connect_one( conn_t * );
  259. static void socket_connect_failed( conn_t * );
  260. static void socket_connected( conn_t * );
  261. static void socket_connect_bail( conn_t * );
  262. static void
  263. socket_close_internal( conn_t *sock )
  264. {
  265. del_fd( sock->fd );
  266. close( sock->fd );
  267. sock->fd = -1;
  268. }
  269. void
  270. socket_connect( conn_t *sock, void (*cb)( int ok, void *aux ) )
  271. {
  272. const server_conf_t *conf = sock->conf;
  273. sock->callbacks.connect = cb;
  274. /* open connection to IMAP server */
  275. if (conf->tunnel) {
  276. int a[2];
  277. nfasprintf( &sock->name, "tunnel '%s'", conf->tunnel );
  278. infon( "Starting %s... ", sock->name );
  279. if (socketpair( PF_UNIX, SOCK_STREAM, 0, a )) {
  280. perror( "socketpair" );
  281. exit( 1 );
  282. }
  283. if (fork() == 0) {
  284. if (dup2( a[0], 0 ) == -1 || dup2( a[0], 1 ) == -1)
  285. _exit( 127 );
  286. close( a[0] );
  287. close( a[1] );
  288. execl( "/bin/sh", "sh", "-c", conf->tunnel, (char *)0 );
  289. _exit( 127 );
  290. }
  291. close( a[0] );
  292. sock->fd = a[1];
  293. fcntl( a[1], F_SETFL, O_NONBLOCK );
  294. add_fd( a[1], socket_fd_cb, sock );
  295. info( "\vok\n" );
  296. socket_connected( sock );
  297. } else {
  298. #ifdef HAVE_IPV6
  299. int gaierr;
  300. struct addrinfo hints;
  301. memset( &hints, 0, sizeof(hints) );
  302. hints.ai_family = AF_UNSPEC;
  303. hints.ai_socktype = SOCK_STREAM;
  304. hints.ai_flags = AI_V4MAPPED | AI_ADDRCONFIG;
  305. infon( "Resolving %s... ", conf->host );
  306. if ((gaierr = getaddrinfo( conf->host, NULL, &hints, &sock->addrs ))) {
  307. error( "IMAP error: Cannot resolve server '%s': %s\n", conf->host, gai_strerror( gaierr ) );
  308. socket_connect_bail( sock );
  309. return;
  310. }
  311. info( "\vok\n" );
  312. sock->curr_addr = sock->addrs;
  313. #else
  314. struct hostent *he;
  315. infon( "Resolving %s... ", conf->host );
  316. he = gethostbyname( conf->host );
  317. if (!he) {
  318. error( "IMAP error: Cannot resolve server '%s': %s\n", conf->host, hstrerror( h_errno ) );
  319. socket_connect_bail( sock );
  320. return;
  321. }
  322. info( "\vok\n" );
  323. sock->curr_addr = he->h_addr_list;
  324. #endif
  325. socket_connect_one( sock );
  326. }
  327. }
  328. static void
  329. socket_connect_one( conn_t *sock )
  330. {
  331. int s;
  332. ushort port;
  333. #ifdef HAVE_IPV6
  334. struct addrinfo *ai;
  335. #else
  336. struct {
  337. struct sockaddr_in ai_addr[1];
  338. } ai[1];
  339. #endif
  340. #ifdef HAVE_IPV6
  341. if (!(ai = sock->curr_addr)) {
  342. #else
  343. if (!*sock->curr_addr) {
  344. #endif
  345. error( "No working address found for %s\n", sock->conf->host );
  346. socket_connect_bail( sock );
  347. return;
  348. }
  349. port = sock->conf->port ? sock->conf->port :
  350. #ifdef HAVE_LIBSSL
  351. sock->conf->use_imaps ? 993 :
  352. #endif
  353. 143;
  354. #ifdef HAVE_IPV6
  355. if (ai->ai_family == AF_INET6) {
  356. struct sockaddr_in6 *in6 = ((struct sockaddr_in6 *)ai->ai_addr);
  357. char sockname[64];
  358. in6->sin6_port = htons( port );
  359. nfasprintf( &sock->name, "%s ([%s]:%hu)",
  360. sock->conf->host, inet_ntop( AF_INET6, &in6->sin6_addr, sockname, sizeof(sockname) ), port );
  361. } else
  362. #endif
  363. {
  364. struct sockaddr_in *in = ((struct sockaddr_in *)ai->ai_addr);
  365. #ifndef HAVE_IPV6
  366. memset( in, 0, sizeof(*in) );
  367. in->sin_family = AF_INET;
  368. in->sin_addr.s_addr = *((int *)*sock->curr_addr);
  369. #endif
  370. in->sin_port = htons( port );
  371. nfasprintf( &sock->name, "%s (%s:%hu)",
  372. sock->conf->host, inet_ntoa( in->sin_addr ), port );
  373. }
  374. #ifdef HAVE_IPV6
  375. s = socket( ai->ai_family, SOCK_STREAM, 0 );
  376. #else
  377. s = socket( PF_INET, SOCK_STREAM, 0 );
  378. #endif
  379. if (s < 0) {
  380. perror( "socket" );
  381. exit( 1 );
  382. }
  383. sock->fd = s;
  384. fcntl( s, F_SETFL, O_NONBLOCK );
  385. add_fd( s, socket_fd_cb, sock );
  386. infon( "Connecting to %s... ", sock->name );
  387. #ifdef HAVE_IPV6
  388. if (connect( s, ai->ai_addr, ai->ai_addrlen )) {
  389. #else
  390. if (connect( s, ai->ai_addr, sizeof(*ai->ai_addr) )) {
  391. #endif
  392. if (errno != EINPROGRESS) {
  393. socket_connect_failed( sock );
  394. return;
  395. }
  396. conf_fd( s, 0, POLLOUT );
  397. sock->state = SCK_CONNECTING;
  398. info( "\v\n" );
  399. return;
  400. }
  401. info( "\vok\n" );
  402. socket_connected( sock );
  403. }
  404. static void
  405. socket_connect_failed( conn_t *conn )
  406. {
  407. sys_error( "Cannot connect to %s", conn->name );
  408. socket_close_internal( conn );
  409. free( conn->name );
  410. conn->name = 0;
  411. #ifdef HAVE_IPV6
  412. conn->curr_addr = conn->curr_addr->ai_next;
  413. #else
  414. conn->curr_addr++;
  415. #endif
  416. socket_connect_one( conn );
  417. }
  418. static void
  419. socket_connected( conn_t *conn )
  420. {
  421. #ifdef HAVE_IPV6
  422. freeaddrinfo( conn->addrs );
  423. #endif
  424. conf_fd( conn->fd, 0, POLLIN );
  425. conn->state = SCK_READY;
  426. conn->callbacks.connect( 1, conn->callback_aux );
  427. }
  428. static void
  429. socket_connect_bail( conn_t *conn )
  430. {
  431. #ifdef HAVE_IPV6
  432. freeaddrinfo( conn->addrs );
  433. #endif
  434. free( conn->name );
  435. conn->name = 0;
  436. conn->callbacks.connect( 0, conn->callback_aux );
  437. }
  438. static void dispose_chunk( conn_t *conn );
  439. void
  440. socket_close( conn_t *sock )
  441. {
  442. if (sock->fd >= 0)
  443. socket_close_internal( sock );
  444. free( sock->name );
  445. sock->name = 0;
  446. #ifdef HAVE_LIBSSL
  447. if (sock->ssl) {
  448. SSL_free( sock->ssl );
  449. sock->ssl = 0;
  450. }
  451. #endif
  452. while (sock->write_buf)
  453. dispose_chunk( sock );
  454. }
  455. static void
  456. socket_fill( conn_t *sock )
  457. {
  458. char *buf;
  459. int n = sock->offset + sock->bytes;
  460. int len = sizeof(sock->buf) - n;
  461. if (!len) {
  462. error( "Socket error: receive buffer full. Probably protocol error.\n" );
  463. socket_fail( sock );
  464. return;
  465. }
  466. assert( sock->fd >= 0 );
  467. buf = sock->buf + n;
  468. #ifdef HAVE_LIBSSL
  469. if (sock->ssl) {
  470. if ((n = ssl_return( "read from", sock, SSL_read( sock->ssl, buf, len ) )) <= 0)
  471. return;
  472. if (n == len && SSL_pending( sock->ssl ))
  473. fake_fd( sock->fd, POLLIN );
  474. } else
  475. #endif
  476. {
  477. if ((n = read( sock->fd, buf, len )) < 0) {
  478. sys_error( "Socket error: read from %s", sock->name );
  479. socket_fail( sock );
  480. return;
  481. } else if (!n) {
  482. error( "Socket error: read from %s: unexpected EOF\n", sock->name );
  483. socket_fail( sock );
  484. return;
  485. }
  486. }
  487. sock->bytes += n;
  488. sock->read_callback( sock->callback_aux );
  489. }
  490. int
  491. socket_read( conn_t *conn, char *buf, int len )
  492. {
  493. int n = conn->bytes;
  494. if (n > len)
  495. n = len;
  496. memcpy( buf, conn->buf + conn->offset, n );
  497. if (!(conn->bytes -= n))
  498. conn->offset = 0;
  499. else
  500. conn->offset += n;
  501. return n;
  502. }
  503. char *
  504. socket_read_line( conn_t *b )
  505. {
  506. char *p, *s;
  507. int n;
  508. s = b->buf + b->offset;
  509. p = memchr( s + b->scanoff, '\n', b->bytes - b->scanoff );
  510. if (!p) {
  511. b->scanoff = b->bytes;
  512. if (b->offset + b->bytes == sizeof(b->buf)) {
  513. memmove( b->buf, b->buf + b->offset, b->bytes );
  514. b->offset = 0;
  515. }
  516. return 0;
  517. }
  518. n = p + 1 - s;
  519. b->offset += n;
  520. b->bytes -= n;
  521. b->scanoff = 0;
  522. if (p != s && p[-1] == '\r')
  523. p--;
  524. *p = 0;
  525. if (DFlags & VERBOSE) {
  526. puts( s );
  527. fflush( stdout );
  528. }
  529. return s;
  530. }
  531. static int
  532. do_write( conn_t *sock, char *buf, int len )
  533. {
  534. int n;
  535. assert( sock->fd >= 0 );
  536. #ifdef HAVE_LIBSSL
  537. if (sock->ssl)
  538. return ssl_return( "write to", sock, SSL_write( sock->ssl, buf, len ) );
  539. #endif
  540. n = write( sock->fd, buf, len );
  541. if (n < 0) {
  542. if (errno != EAGAIN && errno != EWOULDBLOCK) {
  543. sys_error( "Socket error: write to %s", sock->name );
  544. socket_fail( sock );
  545. } else {
  546. n = 0;
  547. conf_fd( sock->fd, POLLIN, POLLOUT );
  548. }
  549. } else if (n != len) {
  550. conf_fd( sock->fd, POLLIN, POLLOUT );
  551. }
  552. return n;
  553. }
  554. static void
  555. dispose_chunk( conn_t *conn )
  556. {
  557. buff_chunk_t *bc = conn->write_buf;
  558. if (!(conn->write_buf = bc->next))
  559. conn->write_buf_append = &conn->write_buf;
  560. if (bc->data != bc->buf)
  561. free( bc->data );
  562. free( bc );
  563. }
  564. static int
  565. do_queued_write( conn_t *conn )
  566. {
  567. buff_chunk_t *bc;
  568. if (!conn->write_buf)
  569. return 0;
  570. while ((bc = conn->write_buf)) {
  571. int n, len = bc->len - conn->write_offset;
  572. if ((n = do_write( conn, bc->data + conn->write_offset, len )) < 0)
  573. return -1;
  574. if (n != len) {
  575. conn->write_offset += n;
  576. return 0;
  577. }
  578. conn->write_offset = 0;
  579. dispose_chunk( conn );
  580. }
  581. #ifdef HAVE_LIBSSL
  582. if (conn->ssl && SSL_pending( conn->ssl ))
  583. fake_fd( conn->fd, POLLIN );
  584. #endif
  585. return conn->write_callback( conn->callback_aux );
  586. }
  587. static void
  588. do_append( conn_t *conn, char *buf, int len, ownership_t takeOwn )
  589. {
  590. buff_chunk_t *bc;
  591. if (takeOwn == GiveOwn) {
  592. bc = nfmalloc( offsetof(buff_chunk_t, buf) );
  593. bc->data = buf;
  594. } else {
  595. bc = nfmalloc( offsetof(buff_chunk_t, buf) + len );
  596. bc->data = bc->buf;
  597. memcpy( bc->data, buf, len );
  598. }
  599. bc->len = len;
  600. bc->next = 0;
  601. *conn->write_buf_append = bc;
  602. conn->write_buf_append = &bc->next;
  603. }
  604. int
  605. socket_write( conn_t *conn, char *buf, int len, ownership_t takeOwn )
  606. {
  607. if (conn->write_buf) {
  608. do_append( conn, buf, len, takeOwn );
  609. return len;
  610. } else {
  611. int n = do_write( conn, buf, len );
  612. if (n != len && n >= 0) {
  613. conn->write_offset = n;
  614. do_append( conn, buf, len, takeOwn );
  615. } else if (takeOwn) {
  616. free( buf );
  617. }
  618. return n;
  619. }
  620. }
  621. static void
  622. socket_fd_cb( int events, void *aux )
  623. {
  624. conn_t *conn = (conn_t *)aux;
  625. if ((events & POLLERR) || conn->state == SCK_CONNECTING) {
  626. int soerr;
  627. socklen_t selen = sizeof(soerr);
  628. if (getsockopt( conn->fd, SOL_SOCKET, SO_ERROR, &soerr, &selen )) {
  629. perror( "getsockopt" );
  630. exit( 1 );
  631. }
  632. errno = soerr;
  633. if (conn->state == SCK_CONNECTING) {
  634. if (errno)
  635. socket_connect_failed( conn );
  636. else
  637. socket_connected( conn );
  638. return;
  639. }
  640. sys_error( "Socket error from %s", conn->name );
  641. socket_fail( conn );
  642. return;
  643. }
  644. if (events & POLLOUT)
  645. conf_fd( conn->fd, POLLIN, 0 );
  646. #ifdef HAVE_LIBSSL
  647. if (conn->state == SCK_STARTTLS) {
  648. start_tls_p2( conn );
  649. return;
  650. }
  651. if (conn->ssl) {
  652. if (do_queued_write( conn ) < 0)
  653. return;
  654. socket_fill( conn );
  655. return;
  656. }
  657. #endif
  658. if ((events & POLLOUT) && do_queued_write( conn ) < 0)
  659. return;
  660. if (events & POLLIN)
  661. socket_fill( conn );
  662. }
  663. #ifdef HAVE_LIBSSL
  664. /* this isn't strictly socket code, but let's have all OpenSSL use in one file. */
  665. #define ENCODED_SIZE(n) (4*((n+2)/3))
  666. static char
  667. hexchar( unsigned int b )
  668. {
  669. if (b < 10)
  670. return '0' + b;
  671. return 'a' + (b - 10);
  672. }
  673. void
  674. cram( const char *challenge, const char *user, const char *pass, char **_final, int *_finallen )
  675. {
  676. char *response, *final;
  677. unsigned hashlen;
  678. int i, clen, blen, flen, olen;
  679. unsigned char hash[16];
  680. char buf[256], hex[33];
  681. HMAC_CTX hmac;
  682. HMAC_Init( &hmac, (unsigned char *)pass, strlen( pass ), EVP_md5() );
  683. clen = strlen( challenge );
  684. /* response will always be smaller than challenge because we are decoding. */
  685. response = nfcalloc( 1 + clen );
  686. EVP_DecodeBlock( (unsigned char *)response, (unsigned char *)challenge, clen );
  687. HMAC_Update( &hmac, (unsigned char *)response, strlen( response ) );
  688. free( response );
  689. hashlen = sizeof(hash);
  690. HMAC_Final( &hmac, hash, &hashlen );
  691. assert( hashlen == sizeof(hash) );
  692. hex[32] = 0;
  693. for (i = 0; i < 16; i++) {
  694. hex[2 * i] = hexchar( (hash[i] >> 4) & 0xf );
  695. hex[2 * i + 1] = hexchar( hash[i] & 0xf );
  696. }
  697. blen = nfsnprintf( buf, sizeof(buf), "%s %s", user, hex );
  698. flen = ENCODED_SIZE( blen );
  699. final = nfmalloc( flen + 1 );
  700. final[flen] = 0;
  701. olen = EVP_EncodeBlock( (unsigned char *)final, (unsigned char *)buf, blen );
  702. assert( olen == flen );
  703. *_final = final;
  704. *_finallen = flen;
  705. }
  706. #endif