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