1 // Copyright (c) 2013 The Chromium 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 #include "chrome/test/chromedriver/net/test_http_server.h"
6 
7 #include <utility>
8 
9 #include "base/bind.h"
10 #include "base/location.h"
11 #include "base/message_loop/message_pump_type.h"
12 #include "base/single_thread_task_runner.h"
13 #include "base/strings/stringprintf.h"
14 #include "base/time/time.h"
15 #include "net/base/ip_endpoint.h"
16 #include "net/base/net_errors.h"
17 #include "net/log/net_log_source.h"
18 #include "net/server/http_server_request_info.h"
19 #include "net/socket/tcp_server_socket.h"
20 #include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
21 #include "testing/gtest/include/gtest/gtest.h"
22 
23 const int kBufferSize = 100 * 1024 * 1024;  // 100 MB
24 
TestHttpServer()25 TestHttpServer::TestHttpServer()
26     : thread_("ServerThread"),
27       all_closed_event_(base::WaitableEvent::ResetPolicy::AUTOMATIC,
28                         base::WaitableEvent::InitialState::SIGNALED) {}
29 
~TestHttpServer()30 TestHttpServer::~TestHttpServer() {
31 }
32 
Start()33 bool TestHttpServer::Start() {
34   base::Thread::Options options(base::MessagePumpType::IO, 0);
35   bool thread_started = thread_.StartWithOptions(options);
36   EXPECT_TRUE(thread_started);
37   if (!thread_started)
38     return false;
39   bool success;
40   base::WaitableEvent event(base::WaitableEvent::ResetPolicy::AUTOMATIC,
41                             base::WaitableEvent::InitialState::NOT_SIGNALED);
42   thread_.task_runner()->PostTask(
43       FROM_HERE, base::BindOnce(&TestHttpServer::StartOnServerThread,
44                                 base::Unretained(this), &success, &event));
45   event.Wait();
46   return success;
47 }
48 
Stop()49 void TestHttpServer::Stop() {
50   if (!thread_.IsRunning())
51     return;
52   base::WaitableEvent event(base::WaitableEvent::ResetPolicy::AUTOMATIC,
53                             base::WaitableEvent::InitialState::NOT_SIGNALED);
54   thread_.task_runner()->PostTask(
55       FROM_HERE, base::BindOnce(&TestHttpServer::StopOnServerThread,
56                                 base::Unretained(this), &event));
57   event.Wait();
58   thread_.Stop();
59 }
60 
WaitForConnectionsToClose()61 bool TestHttpServer::WaitForConnectionsToClose() {
62   return all_closed_event_.TimedWait(base::TimeDelta::FromSeconds(10));
63 }
64 
SetRequestAction(WebSocketRequestAction action)65 void TestHttpServer::SetRequestAction(WebSocketRequestAction action) {
66   base::AutoLock lock(action_lock_);
67   request_action_ = action;
68 }
69 
SetMessageAction(WebSocketMessageAction action)70 void TestHttpServer::SetMessageAction(WebSocketMessageAction action) {
71   base::AutoLock lock(action_lock_);
72   message_action_ = action;
73 }
74 
SetMessageCallback(base::OnceClosure callback)75 void TestHttpServer::SetMessageCallback(base::OnceClosure callback) {
76   base::AutoLock lock(action_lock_);
77   message_callback_ = std::move(callback);
78 }
79 
web_socket_url() const80 GURL TestHttpServer::web_socket_url() const {
81   base::AutoLock lock(url_lock_);
82   return web_socket_url_;
83 }
84 
OnConnect(int connection_id)85 void TestHttpServer::OnConnect(int connection_id) {
86   server_->SetSendBufferSize(connection_id, kBufferSize);
87   server_->SetReceiveBufferSize(connection_id, kBufferSize);
88 }
89 
OnWebSocketRequest(int connection_id,const net::HttpServerRequestInfo & info)90 void TestHttpServer::OnWebSocketRequest(
91     int connection_id,
92     const net::HttpServerRequestInfo& info) {
93   WebSocketRequestAction action;
94   {
95     base::AutoLock lock(action_lock_);
96     action = request_action_;
97   }
98   connections_.insert(connection_id);
99   all_closed_event_.Reset();
100 
101   switch (action) {
102     case kAccept:
103       server_->AcceptWebSocket(connection_id, info,
104                                TRAFFIC_ANNOTATION_FOR_TESTS);
105       break;
106     case kNotFound:
107       server_->Send404(connection_id, TRAFFIC_ANNOTATION_FOR_TESTS);
108       break;
109     case kClose:
110       server_->Close(connection_id);
111       break;
112   }
113 }
114 
OnWebSocketMessage(int connection_id,std::string data)115 void TestHttpServer::OnWebSocketMessage(int connection_id, std::string data) {
116   WebSocketMessageAction action;
117   {
118     base::AutoLock lock(action_lock_);
119     action = message_action_;
120   }
121   if (!message_callback_.is_null())
122     std::move(message_callback_).Run();
123   switch (action) {
124     case kEchoMessage:
125       server_->SendOverWebSocket(connection_id, data,
126                                  TRAFFIC_ANNOTATION_FOR_TESTS);
127       break;
128     case kCloseOnMessage:
129       server_->Close(connection_id);
130       break;
131   }
132 }
133 
OnClose(int connection_id)134 void TestHttpServer::OnClose(int connection_id) {
135   connections_.erase(connection_id);
136   if (connections_.empty())
137     all_closed_event_.Signal();
138 }
139 
StartOnServerThread(bool * success,base::WaitableEvent * event)140 void TestHttpServer::StartOnServerThread(bool* success,
141                                          base::WaitableEvent* event) {
142   std::unique_ptr<net::ServerSocket> server_socket(
143       new net::TCPServerSocket(NULL, net::NetLogSource()));
144   server_socket->ListenWithAddressAndPort("127.0.0.1", 0, 1);
145   server_.reset(new net::HttpServer(std::move(server_socket), this));
146 
147   net::IPEndPoint address;
148   int error = server_->GetLocalAddress(&address);
149   EXPECT_EQ(net::OK, error);
150   if (error == net::OK) {
151     base::AutoLock lock(url_lock_);
152     web_socket_url_ = GURL(base::StringPrintf("ws://127.0.0.1:%d",
153                                               address.port()));
154   } else {
155     server_.reset(NULL);
156   }
157   *success = server_.get();
158   event->Signal();
159 }
160 
StopOnServerThread(base::WaitableEvent * event)161 void TestHttpServer::StopOnServerThread(base::WaitableEvent* event) {
162   server_.reset(NULL);
163   event->Signal();
164 }
165