| 677 | } |
| 678 | |
| 679 | SSLState DetectSSLState(int fd, int* error_code) { |
| 680 | // Peek the first few bytes inside socket to detect whether |
| 681 | // it's an SSL connection. If it is, create an SSL session |
| 682 | // which will be used to read/write after |
| 683 | |
| 684 | // Header format of SSLv2 |
| 685 | // +-----------+------+----- |
| 686 | // | 2B header | 0x01 | etc. |
| 687 | // +-----------+------+----- |
| 688 | // The first bit of header is always 1, with the following |
| 689 | // 15 bits are the length of data |
| 690 | |
| 691 | // Header format of SSLv3 or TLSv1.0, 1.1, 1.2 |
| 692 | // +------+------------+-----------+------+----- |
| 693 | // | 0x16 | 2B version | 2B length | 0x01 | etc. |
| 694 | // +------+------------+-----------+------+----- |
| 695 | char header[6]; |
| 696 | const ssize_t nr = recv(fd, header, sizeof(header), MSG_PEEK); |
| 697 | if (nr < (ssize_t)sizeof(header)) { |
| 698 | if (nr < 0) { |
| 699 | if (errno == ENOTSOCK) { |
| 700 | return SSL_OFF; |
| 701 | } |
| 702 | *error_code = errno; // Including EAGAIN and EINTR |
| 703 | } else if (nr == 0) { // EOF |
| 704 | *error_code = 0; |
| 705 | } else { // Not enough data, need retry |
| 706 | *error_code = EAGAIN; |
| 707 | } |
| 708 | return SSL_UNKNOWN; |
| 709 | } |
| 710 | |
| 711 | if ((header[0] == 0x16 && header[5] == 0x01) // SSLv3 or TLSv1.0, 1.1, 1.2 |
| 712 | || ((header[0] & 0x80) == 0x80 && header[2] == 0x01)) { // SSLv2 |
| 713 | return SSL_CONNECTING; |
| 714 | } else { |
| 715 | return SSL_OFF; |
| 716 | } |
| 717 | } |
| 718 | |
| 719 | #if OPENSSL_VERSION_NUMBER < 0x10100000L |
| 720 | |