Debian Codegraph @

src/Socket.cpp

raw
1 // Socket class - implements BaseSocket for INET domain sockets
2
3 // For all support, instructions and copyright go to:
4 // http://e2guardian.org/
5 // Released under the GPL v2, with the OpenSSL exception described in the README file.
6
7 // INCLUDES
8 #ifdef HAVE_CONFIG_H
9 #include "e2config.h"
10 #endif
11
12 #include "Socket.hpp"
13 #include "Logger.hpp"
14
15 #include <string.h>
16 #include <csignal>
17 #include <fcntl.h>
18 #include <sys/time.h>
19 #include <pwd.h>
20 #include <stdexcept>
21 #include <cerrno>
22 #include <unistd.h>
23 #include <netinet/tcp.h>
24
25 #include "openssl/x509v3.h"
26 #include "openssl/asn1.h"
27 #include "openssl/ssl.h"
28 #include "openssl/err.h"
29 #include "String.hpp"
30 #include "CertificateAuthority.hpp"
31
32 extern bool reloadconfig;
33
34 #ifndef X509_V_FLAG_TRUSTED_FIRST
35 #warning "openssl X509_V_FLAG_TRUSTED_FIRST not available, certificate chain creation will be unreliable and will fail on some sites"
36 #warning "To fix install a later version of openssl"
37 #define X509_V_FLAG_TRUSTED_FIRST 0
38 #endif
39
40
41 // IMPLEMENTATION
42 //
43 // destructor
44 Socket::~Socket() {
45 close();
46 }
47
48 // constructor - create an INET socket & clear address structures
49 Socket::Socket() {
50 sck = socket(AF_INET, SOCK_STREAM, 0);
51 if (sck < 0) {
52 s_errno = errno;
53 } else {
54 memset(&my_adr, 0, sizeof my_adr);
55 memset(&peer_adr, 0, sizeof peer_adr);
56 my_adr.sin_family = AF_INET;
57 peer_adr.sin_family = AF_INET;
58 peer_adr_length = sizeof(struct sockaddr_in);
59 int f = 1;
60
61 if (sck > 0)
62 setsockopt(sck, IPPROTO_TCP, TCP_NODELAY, &f, sizeof(int));
63
64 my_port = 0;
65 chunkError = false;
66
67 ssl = NULL;
68 ctx = NULL;
69 isssl = false;
70 issslserver = false;
71 }
72 }
73
74 // create socket from pre-existing FD (address structs will be invalid!)
75 Socket::Socket(int fd)
76 : BaseSocket(fd) {
77 memset(&my_adr, 0, sizeof my_adr);
78 memset(&peer_adr, 0, sizeof peer_adr);
79 my_adr.sin_family = AF_INET;
80 peer_adr.sin_family = AF_INET;
81 peer_adr_length = sizeof(struct sockaddr_in);
82 int f = 1;
83
84 int res = setsockopt(sck, IPPROTO_TCP, TCP_NODELAY, &f, sizeof(int));
85 if (res < 0) s_errno = errno;
86 my_port = 0;
87 chunkError = false;
88
89 ssl = NULL;
90 ctx = NULL;
91 isssl = false;
92 issslserver = false;
93 }
94
95 // create socket from pre-existing FD, storing local & remote IPs
96 Socket::Socket(int newfd, struct sockaddr_in myip, struct sockaddr_in peerip)
97 : BaseSocket(newfd) {
98 memset(&my_adr, 0, sizeof my_adr); // ***
99 memset(&peer_adr, 0, sizeof peer_adr); // ***
100 my_adr.sin_family = AF_INET; // *** Fix suggested by
101 peer_adr.sin_family = AF_INET; // *** Christopher Weimann
102 my_adr = myip;
103 peer_adr = peerip;
104 peer_adr_length = sizeof(struct sockaddr_in);
105 int f = 1;
106
107 int res = setsockopt(sck, IPPROTO_TCP, TCP_NODELAY, &f, sizeof(int));
108 if (res < 0) s_errno = errno;
109 my_port = 0;
110 chunkError = false;
111
112 ssl = NULL;
113 ctx = NULL;
114 isssl = false;
115 issslserver = false;
116 //fcntl(sck, F_SETFL, O_NONBLOCK);
117 }
118
119 // find the ip to which the client has connected
120 std::string Socket::getLocalIP() {
121 char res[INET_ADDRSTRLEN];
122 return inet_ntop(AF_INET,&my_adr.sin_addr, res, sizeof(res));
123 }
124
125 // find the ip of the client connecting to us
126 std::string Socket::getPeerIP() {
127 if (!client_addr.empty()) {
128 return client_addr;
129 } else {
130 char res[INET_ADDRSTRLEN];
131 return inet_ntop(AF_INET, &peer_adr.sin_addr, res, sizeof(res));
132 }
133 }
134
135 // find the port of the client connecting to us
136 int Socket::getPeerSourcePort() {
137 return ntohs(peer_adr.sin_port);
138 }
139
140 int Socket::getPort() {
141 return my_port;
142 }
143
144 void Socket::setPort(int port) {
145 my_port = port;
146 }
147
148 // return the address of the client connecting to us
149 unsigned long int Socket::getPeerSourceAddr() {
150 return (unsigned long int) ntohl(peer_adr.sin_addr.s_addr);
151 }
152
153 // close connection & wipe address structs
154 void Socket::reset() {
155 if (isssl) {
156 stopSsl();
157 }
158 this->baseReset();
159
160 sck = socket(AF_INET, SOCK_STREAM, 0);
161 if (sck < 0) {
162 s_errno = errno;
163 return;
164 }
165
166 memset(&my_adr, 0, sizeof my_adr);
167 memset(&peer_adr, 0, sizeof peer_adr);
168 my_adr.sin_family = AF_INET;
169 peer_adr.sin_family = AF_INET;
170 peer_adr_length = sizeof(struct sockaddr_in);
171 infds[0].fd = sck;
172 outfds[0].fd = sck;
173
174 chunkError = false;
175 chunk_to_read = 0;
176
177 }
178
179 // connect to given IP & port (following default constructor)
180 int Socket::connect(const std::string &ip, int port) {
181 reset(); // do it anyway as we need sck to be allocated
182
183 if (sck < 0) // socket creation error
184 {
185 return -1;
186 }
187
188 int len = sizeof my_adr;
189 peer_adr.sin_port = htons(port);
190 inet_aton(ip.c_str(), &peer_adr.sin_addr);
191 my_port = port;
192 int save_flags = fcntl(sck,F_GETFL);
193 fcntl(sck, F_SETFL, save_flags | O_NONBLOCK);
194 s_errno = 0;
195 errno = 0;
196 int ret = ::connect(sck, (struct sockaddr *) &peer_adr, len);
197 if (ret < 0 && errno == EINPROGRESS) ret = 0;
198 else s_errno = errno;
199 if (ret == 0) {
200 int rc = poll(outfds, 1, timeout);
201 if (rc == 0) {
202 timedout = true;
203 ret = -1;
204 } else if (rc < 0) {
205 s_errno = errno;
206 ret = -1;
207 } else {
208 int so_error;
209 socklen_t len = sizeof so_error;
210 getsockopt(sck, SOL_SOCKET, SO_ERROR, &so_error, &len);
211 if (so_error != 0) {
212 sockerr = true;
213 s_errno = so_error;
214 ret = -1;
215 } else {
216 ret = 0;
217 }
218 }
219 }
220 if (ret < 0) {
221 close();
222 } else {
223 save_flags = fcntl(sck,F_GETFL);
224 fcntl(sck, F_SETFL, save_flags & ~O_NONBLOCK);
225 }
226 return ret;
227 }
228
229 // bind socket to given port
230 int Socket::bind(int port) {
231 int len = sizeof my_adr;
232 int i = 1;
233
234 setsockopt(sck, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
235
236 my_adr.sin_port = htons(port);
237 my_port = port;
238
239 return ::bind(sck, (struct sockaddr *) &my_adr, len);
240 }
241
242 // bind socket to given port & IP
243 int Socket::bind(const std::string &ip, int port) {
244 int len = sizeof my_adr;
245 int i = 1;
246
247 setsockopt(sck, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
248
249 my_adr.sin_port = htons(port);
250 my_adr.sin_addr.s_addr = inet_addr(ip.c_str());
251 my_port = port;
252
253 return ::bind(sck, (struct sockaddr *) &my_adr, len);
254 }
255
256 // accept incoming connections & return new Socket
257 Socket *Socket::accept() {
258 peer_adr_length = sizeof(struct sockaddr_in);
259 s_errno = 0;
260 errno = 0;
261 int newfd = ::accept(sck, (struct sockaddr *) &peer_adr, &peer_adr_length);
262
263 if (newfd > 0) {
264 Socket *s = new Socket(newfd, my_adr, peer_adr);
265 s->setPort(my_port);
266 return s;
267 } else {
268 s_errno = errno;
269 return NULL;
270 }
271 }
272
273 //use this socket as an ssl client
274 int Socket::startSslClient(const std::string &certificate_path, String hostname)
275 {
276 if (isssl) {
277 stopSsl();
278 }
279
280 ERR_clear_error();
281 #if OPENSSL_VERSION_NUMBER < 0x10100000L
282 #error "openssl version 1.1 or greater is required"
283 #else
284 ctx = SSL_CTX_new(TLS_client_method());
285 #endif
286
287 if (ctx == NULL) {
288 log_ssl_errors("Error ssl context is null for ", hostname.c_str());
289 return -1;
290 }
291
292 //set the timeout for the ssl session
293 if (SSL_CTX_set_timeout(ctx, 130l) < 1) {
294 SSL_CTX_free(ctx);
295 ctx = NULL;
296 return -1;
297 }
298
299 //load certs
300 ERR_clear_error();
301 if (certificate_path.length()) {
302 if (!SSL_CTX_load_verify_locations(ctx, NULL, certificate_path.c_str())) {
303 log_ssl_errors("couldnt load certificates from ", certificate_path.c_str());
304 //tidy up
305 SSL_CTX_free(ctx);
306 ctx = NULL;
307 return -2;
308 }
309 } else if (!SSL_CTX_set_default_verify_paths(ctx)) //use default if no certPpath given
310 {
311 log_ssl_errors("couldnt load default certificates for ", hostname.c_str());
312 //tidy up
313 SSL_CTX_free(ctx);
314 ctx = NULL;
315 return -2;
316 }
317
318 // add validation params
319 ERR_clear_error();
320 X509_VERIFY_PARAM *x509_param = X509_VERIFY_PARAM_new();
321 if (!x509_param) {
322 log_ssl_errors("couldnt add validation params for %s", hostname.c_str());
323 SSL_CTX_free(ctx);
324 ctx = NULL;
325 return -2;
326 }
327
328 // X509_V_FLAG_TRUSTED_FIRST is set by default in ossl v1.1 and above - so no need for this check
329 //ERR_clear_error();
330 //if (!X509_VERIFY_PARAM_set_flags(x509_param, X509_V_FLAG_TRUSTED_FIRST)) {
331 //log_ssl_errors("couldnt add validation params for %s", hostname.c_str());
332 //X509_VERIFY_PARAM_free(x509_param);
333 //SSL_CTX_free(ctx);
334 //ctx = NULL;
335 //return -2;
336 //}
337
338 // ERR_clear_error();
339 // X509_VERIFY_PARAM *param = X509_VERIFY_PARAM_new();
340 // X509_VERIFY_PARAM_set_hostflags(param,X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS );
341
342 // moved from checkCertValid
343
344 // kulge to check theory in use of illegal char in dns name
345 //{
346 //String t = hostname;
347 //if (t.contains("_")) {
348 //t.swapChar('_','-');
349 //hostname = t;
350 //}
351 //}
352
353 DEBUG_debug("Adding hostname to check:",hostname,":");
354
355 // moved from checkCertValid
356 ERR_clear_error();
357 if (!X509_VERIFY_PARAM_set1_host(x509_param, hostname.c_str(), hostname.length())) {
358 log_ssl_errors("couldnt add validation params for %s", hostname.c_str());
359 X509_VERIFY_PARAM_free(x509_param);
360 SSL_CTX_free(ctx);
361 ctx = NULL;
362 return -2;
363 }
364
365 ERR_clear_error();
366 if (!SSL_CTX_set1_param(ctx, x509_param)) {
367 log_ssl_errors("couldnt add validation params for %s", hostname.c_str());
368 X509_VERIFY_PARAM_free(x509_param);
369 SSL_CTX_free(ctx);
370 ctx = NULL;
371 return -2;
372 }
373
374 X509_VERIFY_PARAM_free(x509_param); // try not freeing this as SSL_CTX_free seems to be trying to free it - PIP - 4/09/24 v5.5 seems OK now - valgrind complains if it is not freed.
375
376 //hand socket over to ssl lib
377 ERR_clear_error();
378 ssl = SSL_new(ctx);
379 SSL_set_options(ssl, SSL_OP_ALL);
380 SSL_set_connect_state(ssl);
381
382 SSL_set_fd(ssl, this->getFD());
383 SSL_set_tlsext_host_name(ssl, hostname.c_str());
384 X509_VERIFY_PARAM_set1_host(SSL_get0_param(ssl), hostname.c_str(),0);
385
386 int rc = 0;
387 while (rc != 1) {
388 ERR_clear_error();
389 rc = SSL_connect(ssl);
390 DEBUG_network("ssl_connect returned ", rc );
391
392 if (rc != 1) {
393 s_errno = SSL_get_error(ssl,rc);
394 DEBUG_network("ssl_connect s_error is ", s_errno);
395 switch (s_errno) {
396 case SSL_ERROR_WANT_READ:
397 case SSL_ERROR_WANT_WRITE:
398 if (ssl_poll_wait(s_errno, timeout)) continue;
399 timedout = true;
400 default:
401 log_ssl_errors("ssl_connect failed to %s", hostname.c_str());
402 DEBUG_network("ssl_connect failed with error ", SSL_get_error(ssl, rc));
403 // tidy up
404 SSL_free(ssl);
405 ssl = NULL;
406 SSL_CTX_free(ctx);
407 ctx = NULL;
408 return -3;
409 }
410 }
411 }
412
413 isssl = true;
414 issslserver = false;
415 return 0;
416 }
417
418 bool Socket::isSsl()
419 {
420 return isssl;
421 }
422
423 bool Socket::isSslServer()
424 {
425 return issslserver;
426 }
427
428 //shuts down the current ssl connection
429 void Socket::stopSsl()
430 {
431 DEBUG_network("ssl stopping");
432 if(!isssl) return;
433
434 isssl = false;
435
436 if (ssl != NULL) {
437 if (issslserver) {
438 #ifdef DEBUG_LOW
439 DEBUG_network("this is a server connection");
440 if (SSL_get_shutdown(ssl) & SSL_SENT_SHUTDOWN) {
441 DEBUG_network("SSL_SENT_SHUTDOWN IS SET");
442 }
443 if (SSL_get_shutdown(ssl) & SSL_RECEIVED_SHUTDOWN) {
444 DEBUG_network("SSL_RECEIVED_SHUTDOWN IS SET");
445 }
446 #endif
447 DEBUG_network("calling 1st ssl shutdown");
448
449 int rc = 0;
450 while (rc != 1) {
451 ERR_clear_error();
452 rc = SSL_shutdown(ssl);
453 DEBUG_network("SSL_shutdown returns ", rc);
454 //if (rc == 0) continue;
455 if (rc == 0) break;
456 if (rc != 1) {
457 s_errno = SSL_get_error(ssl,rc);
458 DEBUG_network("s_errno ", s_errno);
459 switch (s_errno) {
460 case SSL_ERROR_WANT_READ:
461 case SSL_ERROR_WANT_WRITE:
462 if (ssl_poll_wait(s_errno, timeout)) continue;
463 DEBUG_network("timed out ", timeout);
464 break;
465 default:
466 DEBUG_network("Error shutitng down SSL ", s_errno );
467 log_ssl_errors("ssl_shutdown failed ","");
468 break;
469 }
470 }
471 break;
472 }
473 if (rc == 0) {
474 DEBUG_network("Discarding extra data from client");
475
476 shutdown(SSL_get_fd(ssl), SHUT_WR);
477 char junk[1024];
478 readFromSocket(junk, sizeof(junk), 0, 5);
479 DEBUG_network("done");
480 }
481 } else {
482 #ifdef DEBUG_LOW
483 DEBUG_network("this is a client connection");
484 if (SSL_get_shutdown(ssl) & SSL_SENT_SHUTDOWN) {
485 DEBUG_network("SSL_SENT_SHUTDOWN IS SET");
486 }
487 if (SSL_get_shutdown(ssl) & SSL_RECEIVED_SHUTDOWN) {
488 DEBUG_network("SSL_RECEIVED_SHUTDOWN IS SET");
489 }
490 DEBUG_network("calling ssl shutdown");
491 #endif
492 int rc = 0;
493 while (rc != 1) {
494 ERR_clear_error();
495 rc = SSL_shutdown(ssl);
496 DEBUG_network("SSL_shutdown returns ", rc);
497 // if (rc == 0) continue;
498 if (rc == 0) break;
499 if (rc != 1) {
500 s_errno = SSL_get_error(ssl,rc);
501 DEBUG_network("s_errno ", s_errno);
502 switch (s_errno) {
503 case SSL_ERROR_WANT_READ:
504 case SSL_ERROR_WANT_WRITE:
505 if (ssl_poll_wait(s_errno, timeout)) continue;
506 break;
507 default:
508 DEBUG_network("Error shutitng down SSL", s_errno );
509 log_ssl_errors("ssl_shutdwon failed ","");
510 break;
511 }
512 }
513 break;
514 }
515 DEBUG_network("done");
516 }
517 }
518
519 cleanSsl();
520
521 }
522
523 void Socket::cleanSsl() { // called when failure in ssl set up functions and from stopSsl
524 if (ssl != NULL) {
525 SSL_free(ssl);
526 ssl = NULL;
527 }
528 if (ctx != NULL ) {
529 SSL_CTX_free(ctx);
530 ctx = NULL;
531 }
532 issslserver = false;
533 isssl = false;
534 }
535
536 //check that everything in this certificate is correct appart from the hostname
537 long Socket::checkCertValid(String &hostname)
538 {
539 //check we have a certificate
540 X509 *peerCert = SSL_get_peer_certificate(ssl);
541 if (peerCert == NULL) {
542 return -1;
543 }
544 X509_free(peerCert);
545
546 // Moved to startSslClient
547 // X509_VERIFY_PARAM *param;
548 //param = X509_VERIFY_PARAM_new() ;
549 //X509_VERIFY_PARAM_set1_host(param,hostname.c_str(), hostname.length());
550 //SSL_CTX_set1_param(ctx,param);
551 //X509_VERIFY_PARAM_free(param);
552 return SSL_get_verify_result(ssl);
553 }
554
555 //check the common name and altnames of a certificate against hostname
556 int Socket::checkCertHostname(const std::string &_hostname)
557 {
558 return 0; //TODO
559 }
560
561 void Socket::close()
562 {
563 if (isssl) {
564 stopSsl();
565 }
566 BaseSocket::close();
567 }
568
569 //use this socket as an ssl server
570 int Socket::startSslServer(X509 *x, EVP_PKEY *privKey, std::string &set_cipher_list)
571 {
572
573 if (isssl) {
574 stopSsl();
575 }
576
577 // set ssl to NULL
578 ssl = NULL;
579
580 //setup the ssl server ctx
581 ctx = SSL_CTX_new(TLS_server_method());
582
583 if (ctx == NULL) {
584 DEBUG_network("Error ssl context is null (check that openssl has been inited)");
585 return -1;
586 }
587
588 //set the timeout to match firefox
589 if (SSL_CTX_set_timeout(ctx, 130l) < 1) {
590 cleanSsl();
591 return -1;
592 }
593
594 //set the ctx to use the certificate
595 if (SSL_CTX_use_certificate(ctx, x) < 1) {
596 DEBUG_network("Error using certificate");
597 cleanSsl();
598 return -1;
599 }
600
601 if (set_cipher_list.length() > 0)
602 SSL_CTX_set_cipher_list(ctx, set_cipher_list.c_str());
603
604 //set the ctx to use the private key
605 if (SSL_CTX_use_PrivateKey(ctx, privKey) < 1) {
606 DEBUG_network("Error using private key");
607 cleanSsl();
608 return -1;
609 }
610
611 //setup the ssl session
612 ERR_clear_error();
613 ssl = SSL_new(ctx);
614 SSL_set_options(ssl, SSL_OP_ALL);
615 // SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY);
616 SSL_set_accept_state(ssl);
617
618 ERR_clear_error();
619 if(!SSL_set_fd(ssl, this->getFD())) {
620 log_ssl_errors("ssl_set_fd failed to client", "");
621 cleanSsl();
622 return -1;
623 };
624
625 int rc = 0;
626 while (rc != 1) {
627 ERR_clear_error();
628 rc = SSL_accept(ssl);
629 DEBUG_network("accepting returns ", rc);
630 if (rc != 1) {
631 s_errno = SSL_get_error(ssl,rc);
632 switch (s_errno) {
633 case SSL_ERROR_WANT_READ:
634 case SSL_ERROR_WANT_WRITE:
635 if (ssl_poll_wait(s_errno, timeout)) continue;
636 timedout = true;
637 return -1;
638 default:
639 DEBUG_network("Error accepting ssl connection error is ", s_errno );
640 log_ssl_errors("ssl_accept failed to client %s", "");
641 cleanSsl();
642 return -1;
643 }
644 }
645 }
646
647 ERR_clear_error();
648 if (SSL_do_handshake(ssl) < 0) {
649 log_ssl_errors("ssl_handshake failed to client ", "");
650 cleanSsl();
651 return -1;
652 }
653 SSL_clear_mode(ssl, SSL_MODE_AUTO_RETRY);
654 isssl = true;
655 issslserver = true;
656 return 0;
657 }
658
659 bool Socket::checkForInput(int timeout)
660 {
661 if (!isssl) {
662 return BaseSocket::checkForInput(timeout);
663 }
664
665 //if(timeout == 0)
666 // return false;
667
668 DEBUG_network("checking for input on ssl connection");
669 if ((bufflen - buffstart) > 0) {
670 DEBUG_network("found buffered input on ssl connection");
671 return true;
672 }
673
674 int rc = 0;
675 int rc2 = 0;
676
677 rc = s_checkPending();
678
679 if (rc < 1 ) {
680 if (timeout == 0) { // poll ios handled by calling function
681 DEBUG_network("no pending data on ssl connection pending ", rc);
682 timedout = true;
683 return false;
684 } else {
685 if ((rc2 = poll(infds, 1, timeout)) == 0) {
686 DEBUG_network("timed out on pending data on ssl connection SSL_pending ", rc);
687 timedout = true;
688 return false;
689 }
690 if (infds[0].revents & POLLIN) return true;
691 }
692 }
693
694 DEBUG_network("found data on ssl connection");
695
696 return true;
697 }
698
699
700 // read a line from the socket
701 int Socket::getLine(char *buff, int size, int timeout, bool *chopped, bool *truncated)
702 {
703 try {
704 if (!isssl) {
705 return BaseSocket::getLine(buff, size, timeout, chopped, truncated);
706 }
707
708 // first, return what's left from the previous buffer read, if anything
709 int i = 0;
710 if ((bufflen - buffstart) > 0) {
711 int tocopy = size - 1;
712 if ((bufflen - buffstart) < tocopy)
713 tocopy = bufflen - buffstart;
714 char *result = (char *)memccpy(buff, buffer + buffstart, '\n', tocopy);
715 if (result != NULL) {
716 // indicate that a newline was chopped off, if desired
717 if (chopped)
718 *chopped = true;
719 *(--result) = '\0';
720 buffstart += (result - buff) + 1;
721 return result - buff;
722 } else {
723 i += tocopy;
724 buffstart += tocopy;
725 }
726 }
727 while (i < (size - 1)) {
728 buffstart = 0;
729 bufflen = 0;
730 //int pend_ret = SSL_has_pending(ssl);
731 //DEBUG_network("pending ret ", pend_ret);
732 // may need checkForInput here !!
733 if (!checkForInput(timeout)) {
734 timedout = true;
735 return -1;
736 }
737 bufflen = SSL_read(ssl, buffer, SCK_READ_BUFF_SIZE);
738
739 DEBUG_network("read into buffer; bufflen: ", bufflen);
740 if (bufflen < 1) {
741 s_errno = SSL_get_error(ssl,bufflen);
742 DEBUG_network("read into buffer; s_errno: ", s_errno);
743
744 switch (s_errno) {
745 case SSL_ERROR_WANT_READ:
746 case SSL_ERROR_WANT_WRITE:
747 if (ssl_poll_wait(s_errno, timeout)) continue;
748 timedout = true;
749 return -1;
750 case SSL_ERROR_ZERO_RETURN: // eof
751 ishup = true;
752 buff[i] = '\0'; // ...terminate string & return what read
753 if (truncated)
754 *truncated = true;
755 return i;
756 case SSL_ERROR_SYSCALL: // happens if other end stops ssl - line may or may not be HUPed
757 ishup = true;
758 return -1;
759 default:
760 log_ssl_errors("ssl_read failed %s", "");
761 DEBUG_network("SSL_read failed with error ", SSL_get_error(ssl, bufflen));
762 ishup = true;
763 return -1;
764 }
765 }
766 int tocopy = bufflen;
767 if ((i + bufflen) > (size - 1))
768 tocopy = (size - 1) - i;
769 char *result = (char *)memccpy(buff + i, buffer, '\n', tocopy);
770 if (result != NULL) {
771 // indicate that a newline was chopped off, if desired
772 if (chopped)
773 *chopped = true;
774 *(--result) = '\0';
775 buffstart += (result - (buff + i)) + 1;
776 return i + (result - (buff + i));
777 }
778 i += tocopy;
779 }
780 // oh dear - buffer end reached before we found a newline
781 buff[i] = '\0';
782 if (truncated)
783 *truncated = true;
784 return i;
785 } catch (...) {
786 return -1; }
787 }
788
789 // write line to socket
790 bool Socket::writeString(const char *line)
791 {
792 int l = strlen(line);
793 return writeToSocket(line, l, 0, timeout);
794 }
795
796 // write line to socket
797 bool Socket::writeString(std::string line)
798 {
799 int l = line.length();
800 return writeToSocket(line.c_str(), l, 0, timeout);
801 }
802
803 // write data to socket
804 bool Socket::writeToSocket(const char *buff, int len, unsigned int flags, int timeout)
805 {
806 if (len == 0) // nothing to write
807 return true;
808 if (!isssl) {
809 return BaseSocket::writeToSocket(buff, len, flags, timeout);
810 }
811
812 int actuallysent = 0;
813 int sent;
814 while (actuallysent < len) {
815 DEBUG_network("Ready to write ", len - actuallysent, " bytes");
816 ERR_clear_error();
817 sent = SSL_write(ssl, buff + actuallysent, len - actuallysent);
818 if (sent < 1) {
819 s_errno = SSL_get_error(ssl,sent);
820 switch (s_errno) {
821 case SSL_ERROR_WANT_READ:
822 case SSL_ERROR_WANT_WRITE:
823 if (timeout > 0 && ssl_poll_wait(s_errno, timeout)) continue;
824 DEBUG_network("Poll timeed out or error");
825 timedout = true;
826 return false;
827 case SSL_ERROR_ZERO_RETURN: // eof
828 DEBUG_network("SSL returns eof on write???");
829 ishup = true;
830 return false;
831 default:
832 String serr(s_errno);
833 log_ssl_errors("ssl_write failed - error ",serr.c_str());
834 DEBUG_network("ssl_write failed ", s_errno, " failed to write");
835 ishup = true;
836 return false;
837 }
838
839 }
840 actuallysent += sent;
841 }
842 return true;
843 }
844
845 int Socket::readFromSocket(char *buff, int len, unsigned int flags, int timeout, bool ret_part )
846 {
847 if (len == 0) // nothing to read
848 return 0;
849 if (!isssl) {
850 return BaseSocket::readFromSocket(buff, len, flags, timeout, ret_part);
851 }
852
853 // first, return what's left from the previous buffer read, if anything
854 int cnt = len;
855 int tocopy = 0;
856 if ((bufflen - buffstart) > 0) {
857 DEBUG_network("Socket::readFromSocket: data already in buffer; bufflen: ", bufflen, " buffstart: ", buffstart );
858 tocopy = len;
859 if ((bufflen - buffstart) < len)
860 tocopy = bufflen - buffstart;
861 memcpy(buff, buffer + buffstart, tocopy);
862 cnt -= tocopy;
863 buffstart += tocopy;
864 buff += tocopy;
865 if(ret_part) return tocopy;
866 if (cnt == 0)
867 return len;
868 }
869
870 //#ifdef DEBUG_LOW
871 // int pend_stat = SSL_has_pending(ssl);
872 // DEBUG_network("has_pending returns ", pend_stat);
873 //#endif
874 bool has_buffer = checkForInput(timeout);
875
876 int rc;
877 while (cnt > 0) {
878 ERR_clear_error();
879
880 if(!has_buffer) {
881 if (timeout > 0) {
882 if (!checkForInput(timeout)) {
883 timedout = true;
884 if (len - cnt > 0) {
885 return len - cnt;
886 } else {
887 return -1;
888 }
889 }
890 }
891 } else {
892 has_buffer = false;
893 }
894
895 ERR_clear_error();
896 rc = SSL_read(ssl, buff, cnt);
897
898 if (rc < 1) {
899 s_errno = SSL_get_error(ssl,rc);
900 DEBUG_network("Error SSL_read ", s_errno);
901 switch (s_errno) {
902 case SSL_ERROR_WANT_READ:
903 case SSL_ERROR_WANT_WRITE:
904 if (timeout > 0 && ssl_poll_wait(s_errno, timeout)) continue;
905 timedout = true;
906 return -1;
907 case SSL_ERROR_ZERO_RETURN: // eof
908 ishup = true;
909 return len - cnt;
910 case SSL_ERROR_SYSCALL: // ssl stopped at remote end
911 ishup = true;
912 return len - cnt;
913 default:
914 log_ssl_errors("ssl_read failed %s", "");
915 DEBUG_network("ssl_read failed", s_errno, " failed to read ",cnt, " bytes");
916 ishup = true;
917 return len - cnt;
918 }
919
920 }
921 DEBUG_network("SSL read returned ", rc);
922
923 buff += rc;
924 cnt -= rc;
925 if(ret_part) return len - cnt;
926 }
927
928 return len;
929 }
930
931
932 void Socket::resetChunk() {
933 chunk_to_read = 0;
934 chunked_trailer = "";
935 ieof = false;
936 }
937
938 bool Socket::writeChunk( char *buffout, int len, int timeout){
939 std::stringstream stm;
940 stm << std::hex << len;
941 std::string hexs (stm.str());
942 //int lw;
943 hexs += "\r\n";
944 DEBUG_network("writeChunk size=", hexs);
945
946 if(!writeString(hexs.c_str())) {
947 DEBUG_network(("Error on chunked size write"));
948 return false;
949 } //else {
950 // DEBUG_network("chunked size write ok");
951 //}
952
953 if(!writeToSocket(buffout,len,0,timeout)) {
954 DEBUG_network(("Error on chunked data write"));
955 return false;
956 } //else {
957 // DEBUG_network("chunked data write ok");
958 //}
959 if(!writeString("\r\n")) {
960 DEBUG_network(("Error on chunked line end write"));
961 return false;
962 } else {
963 DEBUG_network("chunked line end write ok");
964 }
965 return true;
966 };
967
968 bool Socket::writeChunkTrailer( String &trailer) {
969 std::string hexs ("0\r\n");
970 DEBUG_network("writeChunk trailer size=", hexs);
971 if(writeString(hexs.c_str()) && writeToSocket(trailer.c_str(),trailer.length(),0,timeout) && writeString("\r\n"))
972 return true;
973 return false;
974 };
975
976 int Socket::readChunk( char *buffin, int maxlen, int timeout){
977 if (chunk_to_read == 0) // need to read chunk size
978 {
979 char size[40];
980 ieof = false;
981 int len = getLine(size, 38, timeout);
982 if (len < 2) { // min valid length is 2 i.e. "0\r"
983 chunkError = true;
984 return -1;
985 }
986 DEBUG_network("readChunk size=", size);
987 String l = size;
988 l.chop();
989 String t = l.before(";");
990 if (t.length() > 0) {
991 if (l.endsWith("; ieof")) {
992 ieof = true;
993 }
994 l = t;
995 }
996 chunk_to_read = l.hexToInteger();
997 DEBUG_network("readChunk chunk_to_read =", chunk_to_read);
998 }
999
1000 int clen = chunk_to_read;
1001 if (clen > maxlen) {
1002 clen = maxlen;
1003 }
1004 int rc = 0;
1005 DEBUG_network("readChunk max_read =", clen);
1006
1007 if(clen == 0) {
1008 chunked_trailer = "";
1009 char trailer[32000];
1010 int len = 3;
1011 while( len > 2) {
1012 len = getLine(trailer, 31900, timeout);
1013 if (len > 2) {
1014 chunked_trailer += trailer;
1015 chunked_trailer += "\n";
1016 }
1017 }
1018 return 0;
1019 }
1020
1021 if (clen > 0) {
1022 rc = readFromSocket(buffin, clen, 0, timeout);
1023 DEBUG_network("readChunk read ", rc);
1024 if (rc < 0) {
1025 chunkError = true;
1026 return -1;
1027 }
1028 chunk_to_read -= rc;
1029 }
1030 if (chunk_to_read > 0) // there is more to read in this chunk - so do not check for trailing \r\n
1031 return rc;
1032 char ts[2];
1033 int len = readFromSocket(ts, 2, 0, timeout);
1034 if (len == 2 && ts[0] == '\r' && ts[1] == '\n') {
1035 return rc;
1036 } else {
1037 chunkError = true;
1038 DEBUG_network("readChunk - tail in error");
1039 return -1;
1040 }
1041 }
1042
1043 int Socket::loopChunk(int timeout) // reads chunks and sends back until 0 len chunk or timeout
1044 {
1045 char buff[32000];
1046 int tot_size = 0;
1047 int csize = 1;
1048 while (csize > 0) {
1049 csize = readChunk(buff,32000, timeout);
1050 if (csize == 0) // end chunk
1051 {
1052 if (!writeChunkTrailer(chunked_trailer))
1053 {
1054 #ifdef CHUNKDEBUG
1055 std::cerr << thread_id << "loopChunk - error in writing chunk trailer" << std::endl;
1056 #endif
1057 return -1;
1058
1059 };
1060 #ifdef CHUNKDEBUG
1061 std::cerr << thread_id << "loopChunk tot_size=" << tot_size << std::endl;
1062 #endif
1063 return tot_size;
1064 }
1065 if (!(csize > 0 && writeChunk(buff,csize,timeout))) {
1066 #ifdef CHUNKDEBUG
1067 std::cerr << thread_id << "loopChunk - error" << std::endl;
1068 #endif
1069 return -1;
1070 }
1071 tot_size += csize;
1072 }
1073 return -1; // should never get here!
1074 }
1075
1076
1077 int Socket::drainChunk(int timeout) // reads chunks until 0 len chunk or timeout
1078 {
1079 char buff[32000];
1080 int tot_size = 0;
1081 int csize = 1;
1082 while (csize > 0) {
1083 csize = readChunk(buff,32000, timeout);
1084 if (csize < 0) {
1085 #ifdef CHUNKDEBUG
1086 std::cerr << thread_id << "drainChunk - error" << std::endl;
1087 #endif
1088 return -1;
1089 }
1090 tot_size += csize;
1091 }
1092 #ifdef CHUNKDEBUG
1093 std::cerr << thread_id << "drainChunk tot_size=" << tot_size << std::endl;
1094 #endif
1095 return tot_size;
1096 }
1097
1098 bool Socket::getIeof() {
1099 return ieof;
1100 }
1101
1102
1103 bool Socket::ssl_poll_wait(int serr, int timeout) {
1104 // if(timeout == 0) {
1105 // timedout = true;
1106 // return false;
1107 //}
1108 int rc;
1109 s_errno = 0;
1110 DEBUG_network("sERR ", serr);
1111 if (serr == SSL_ERROR_WANT_READ) {
1112 if (isNoRead())
1113 return false;
1114 errno = 0;
1115 rc = poll(infds, 1, timeout);
1116 if (rc == 0) {
1117 DEBUG_network("poll returned 0");
1118 timedout = true;
1119 return false; //timeout
1120 }
1121 timedout = false;
1122 if (rc < 0) {
1123 DEBUG_network("poll returned ", s_errno);
1124 s_errno = errno;
1125 sockerr = true;
1126 return false;
1127 }
1128 if (infds[0].revents & POLLHUP) {
1129 DEBUG_network("poll returned HUP");
1130 ishup = true;
1131 }
1132 if ((infds[0].revents & ( POLLIN))) {
1133 return true;
1134 }
1135 sockerr = true;
1136 return false; // must be POLLERR or POLLNVAL
1137 } else if(serr == SSL_ERROR_WANT_WRITE) { //must be SSL_ERROR_WANT_WRITE
1138 if (isNoWrite())
1139 return false;
1140 errno = 0;
1141 rc = poll(outfds, 1, timeout);
1142 if (rc == 0) {
1143 timedout = true;
1144 DEBUG_network("poll returned 0");
1145 return false; //timeout
1146 }
1147 timedout = false;
1148 if (rc < 0) {
1149 s_errno = errno;
1150 DEBUG_network("poll returned ", s_errno);
1151 sockerr = true;
1152 return false;
1153 }
1154 if (outfds[0].revents & POLLHUP) {
1155 ishup = true;
1156 DEBUG_network("poll returned HUP");
1157 }
1158 if ((outfds[0].revents & ( POLLOUT))) {
1159 return true;
1160 }
1161 }
1162 return false;
1163 }
1164
1165 short int Socket::get_wait_flag(bool write_flag) {
1166 if (!isssl)
1167 return BaseSocket::get_wait_flag(write_flag);
1168 if(timedout) {
1169 if (s_errno == SSL_ERROR_WANT_READ) {
1170 timedout = false;
1171 return POLLIN;
1172 } else if (s_errno == SSL_ERROR_WANT_WRITE) {
1173 timedout = false;
1174 return POLLOUT;
1175 }
1176 }
1177 return POLLIN;
1178 }
1179
1180 void Socket::setClientAddr(std::string ip, int port) {
1181 client_addr = ip;
1182 client_port = port;
1183 }
1184
1185 bool Socket::s_checkPending() {
1186 if(s_checkShutdown()&SSL_RECEIVED_SHUTDOWN) {
1187 DEBUG_network("SSL shudown in progress - returning false");
1188 return (s_pending = false);
1189 }
1190 s_pending = SSL_pending(ssl);
1191 DEBUG_network("SSL_pending gives ", s_pending);
1192 #ifndef LIBRESSL_VERSION_NUMBER
1193 s_prev_has_pending = s_has_pending;
1194 s_has_pending = SSL_has_pending(ssl);
1195 DEBUG_network("SSL_has_pending gives ", s_has_pending);
1196 s_pending = s_pending || (s_has_pending && !s_prev_has_pending);
1197 #endif
1198 DEBUG_network("Returning ", s_pending);
1199 return s_pending;
1200 }
1201
1202 int Socket::s_checkShutdown() {
1203 return SSL_get_shutdown(ssl);
1204 }