More OpenSSL 1.1.0 compatibility fixes
[folly.git] / folly / io / async / test / TestSSLServer.cpp
1 /*
2  * Copyright 2017 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/test/TestSSLServer.h>
17
18 namespace folly {
19
20 const char* kTestCert = "folly/io/async/test/certs/tests-cert.pem";
21 const char* kTestKey = "folly/io/async/test/certs/tests-key.pem";
22 const char* kTestCA = "folly/io/async/test/certs/ca-cert.pem";
23
24 TestSSLServer::~TestSSLServer() {
25   if (thread_.joinable()) {
26     evb_.runInEventBaseThread([&]() { socket_->stopAccepting(); });
27     LOG(INFO) << "Waiting for server thread to exit";
28     thread_.join();
29   }
30 }
31
32 TestSSLServer::TestSSLServer(SSLServerAcceptCallbackBase* acb, bool enableTFO)
33     : acb_(acb) {
34   // Set up a default SSL context
35   ctx_ = std::make_shared<SSLContext>();
36   ctx_->loadCertificate(kTestCert);
37   ctx_->loadPrivateKey(kTestKey);
38   ctx_->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
39
40   init(enableTFO);
41 }
42
43 TestSSLServer::TestSSLServer(
44     SSLServerAcceptCallbackBase* acb,
45     std::shared_ptr<SSLContext> ctx,
46     bool enableTFO)
47     : ctx_(ctx), acb_(acb) {
48   init(enableTFO);
49 }
50
51 void TestSSLServer::init(bool enableTFO) {
52   socket_ = AsyncServerSocket::newSocket(&evb_);
53
54   acb_->ctx_ = ctx_;
55   acb_->base_ = &evb_;
56
57   // Enable TFO
58   if (enableTFO) {
59     LOG(INFO) << "server TFO enabled";
60     socket_->setTFOEnabled(true, 1000);
61   }
62
63   // set up the listening socket
64   socket_->bind(0);
65   socket_->getAddress(&address_);
66   socket_->listen(100);
67   socket_->addAcceptCallback(acb_, &evb_);
68   socket_->startAccepting();
69
70   thread_ = std::thread([&] {
71     evb_.loop();
72     acb_->detach();
73     LOG(INFO) << "Server thread exited event loop";
74   });
75   LOG(INFO) << "Accepting connections on " << address_;
76 }
77 }