blob: 95691435cc21ba315afbf37f9b939fc780bb2fcb [file] [log] [blame]
Andreea Costinas054fbb52020-06-12 20:46:22 +02001// Copyright 2020 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef SYSTEM_PROXY_TEST_HTTP_SERVER_H_
6#define SYSTEM_PROXY_TEST_HTTP_SERVER_H_
7
8#include <memory>
9#include <queue>
10#include <string>
11#include <string_view>
12
13#include <base/files/scoped_file.h>
14#include <base/memory/weak_ptr.h>
15#include <base/threading/simple_thread.h>
16
17namespace patchpanel {
18class Socket;
19} // namespace patchpanel
20
21namespace system_proxy {
22
23// HTTP server implementation for testing purpose that runs on a separate
24// thread. This server allows users to setup expected HTTP server replies and
25// listen in a blocking mode until all the requests are fulfilled. It does not
26// perform client request syntax validation.
27class HttpTestServer : public base::SimpleThread {
28 public:
29 enum class HttpConnectReply {
30 kOk,
31 kAuthRequiredBasic,
32 kAuthRequiredKerberos,
33 kBadGateway
34 };
35
36 HttpTestServer();
37 HttpTestServer(const HttpTestServer&) = delete;
38 HttpTestServer& operator=(const HttpTestServer&) = delete;
39 ~HttpTestServer() override;
40
41 // Starts the HTTP server which will perform a blocking listen() on the
42 // address returned by |GetUrl| until all the requets set via
43 // |AddHttpConnectReply| are fulfilled.
44 void Run() override;
45 // Sets the expected HTTP responses from the server. Must be called before
46 // starting the thread.
47 void AddHttpConnectReply(HttpConnectReply reply);
48 // Returns the URL as scheme://host:port that points to the server.
49 std::string GetUrl();
50
51 private:
52 // Creates the proxy listening socket which is bound to the localhost and a
53 // dynamically allocated port. The proxy address can be retrieved using
54 // |GetUrl|.
55 void BeforeStart() override;
56
57 void SendConnectReply();
58 // Returns the HTTP message associate with |reply|.
59 std::string_view GetConnectReplyString(HttpConnectReply reply);
60
61 uint32_t listening_addr_;
62 int listening_port_;
63 std::queue<HttpConnectReply> expected_responses_;
Andreea Costinas054fbb52020-06-12 20:46:22 +020064 std::unique_ptr<patchpanel::Socket> listening_socket_;
65 base::WeakPtrFactory<HttpTestServer> weak_ptr_factory_{this};
66};
67} // namespace system_proxy
68
69#endif // SYSTEM_PROXY_TEST_HTTP_SERVER_H_