Split out SSL test server for reuse
[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(SSLServerAcceptCallbackBase* acb, bool enableTFO)
25     : ctx_(new SSLContext),
26       acb_(acb),
27       socket_(AsyncServerSocket::newSocket(&evb_)) {
28   // Set up the SSL context
29   ctx_->loadCertificate(kTestCert);
30   ctx_->loadPrivateKey(kTestKey);
31   ctx_->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
32
33   acb_->ctx_ = ctx_;
34   acb_->base_ = &evb_;
35
36   // Enable TFO
37   if (enableTFO) {
38     LOG(INFO) << "server TFO enabled";
39     socket_->setTFOEnabled(true, 1000);
40   }
41
42   // set up the listening socket
43   socket_->bind(0);
44   socket_->getAddress(&address_);
45   socket_->listen(100);
46   socket_->addAcceptCallback(acb_, &evb_);
47   socket_->startAccepting();
48
49   thread_ = std::thread([&] { Main(); });
50   LOG(INFO) << "Accepting connections on " << address_;
51 }
52
53 TestSSLServer::~TestSSLServer() {
54   if (thread_.joinable()) {
55     evb_.runInEventBaseThread([&]() { socket_->stopAccepting(); });
56     LOG(INFO) << "Waiting for server thread to exit";
57     thread_.join();
58   }
59 }
60 }