Stop abusing errno
[folly.git] / folly / io / async / ssl / SSLErrors.cpp
1 /*
2  * Copyright 2016 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 #include <folly/io/async/ssl/SSLErrors.h>
17
18 #include <folly/Range.h>
19 #include <openssl/err.h>
20 #include <openssl/ssl.h>
21
22 using namespace folly;
23
24 namespace {
25
26 std::string decodeOpenSSLError(
27     int sslError,
28     unsigned long errError,
29     int sslOperationReturnValue) {
30   if (sslError == SSL_ERROR_SYSCALL && errError == 0) {
31     if (sslOperationReturnValue == 0) {
32       return "SSL_ERROR_SYSCALL: EOF";
33     } else {
34       // In this case errno is set, AsyncSocketException will add it.
35       return "SSL_ERROR_SYSCALL";
36     }
37   } else if (sslError == SSL_ERROR_ZERO_RETURN) {
38     // This signifies a TLS closure alert.
39     return "SSL_ERROR_ZERO_RETURN";
40   } else {
41     std::array<char, 256> buf;
42     std::string msg(ERR_error_string(errError, buf.data()));
43     return msg;
44   }
45 }
46
47 const StringPiece getSSLErrorString(SSLError error) {
48   StringPiece ret;
49   switch (error) {
50     case SSLError::CLIENT_RENEGOTIATION:
51       ret = "Client tried to renegotiate with server";
52       break;
53     case SSLError::INVALID_RENEGOTIATION:
54       ret = "Attempt to start renegotiation, but unsupported";
55       break;
56     case SSLError::EARLY_WRITE:
57       ret = "Attempt to write before SSL connection established";
58       break;
59     case SSLError::OPENSSL_ERR:
60       // decodeOpenSSLError should be used for this type.
61       ret = "OPENSSL error";
62       break;
63   }
64   return ret;
65 }
66 }
67
68 namespace folly {
69
70 SSLException::SSLException(
71     int sslError,
72     unsigned long errError,
73     int sslOperationReturnValue,
74     int errno_copy)
75     : AsyncSocketException(
76           AsyncSocketException::SSL_ERROR,
77           decodeOpenSSLError(sslError, errError, sslOperationReturnValue),
78           sslError == SSL_ERROR_SYSCALL ? errno_copy : 0),
79       sslError(SSLError::OPENSSL_ERR),
80       opensslSSLError(sslError),
81       opensslErr(errError) {}
82
83 SSLException::SSLException(SSLError error)
84     : AsyncSocketException(
85           AsyncSocketException::SSL_ERROR,
86           getSSLErrorString(error).str(),
87           0),
88       sslError(error) {}
89 }