46d6743d14c937d1d26b100d548056dd0bea8f75
[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 void TestSSLServer::loadTestCerts() {
44   ctx_->loadCertificate(kTestCert);
45   ctx_->loadPrivateKey(kTestKey);
46 }
47
48 TestSSLServer::TestSSLServer(
49     SSLServerAcceptCallbackBase* acb,
50     std::shared_ptr<SSLContext> ctx,
51     bool enableTFO)
52     : ctx_(ctx), acb_(acb) {
53   init(enableTFO);
54 }
55
56 void TestSSLServer::init(bool enableTFO) {
57   socket_ = AsyncServerSocket::newSocket(&evb_);
58
59   acb_->ctx_ = ctx_;
60   acb_->base_ = &evb_;
61
62   // Enable TFO
63   if (enableTFO) {
64     LOG(INFO) << "server TFO enabled";
65     socket_->setTFOEnabled(true, 1000);
66   }
67
68   // set up the listening socket
69   socket_->bind(0);
70   socket_->getAddress(&address_);
71   socket_->listen(100);
72   socket_->addAcceptCallback(acb_, &evb_);
73   socket_->startAccepting();
74
75   thread_ = std::thread([&] {
76     evb_.loop();
77     acb_->detach();
78     LOG(INFO) << "Server thread exited event loop";
79   });
80   LOG(INFO) << "Accepting connections on " << address_;
81 }
82 }