Roll src/third_party/WebKit d9c6159:8139f33 (svn 201974:201975)
[chromium-blink-merge.git] / net / tools / flip_server / flip_in_mem_edsm_server.cc
blob1e6a8cef3616510879e64e2b5a32f362ecad90cf
1 // Copyright (c) 2011 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.
5 #include <errno.h>
6 #include <signal.h>
7 #include <stdio.h>
8 #include <sys/file.h>
9 #include <sys/stat.h>
11 #include <string>
12 #include <vector>
14 #include "base/command_line.h"
15 #include "base/logging.h"
16 #include "base/strings/string_split.h"
17 #include "base/synchronization/lock.h"
18 #include "net/tools/balsa/split.h"
19 #include "net/tools/flip_server/acceptor_thread.h"
20 #include "net/tools/flip_server/constants.h"
21 #include "net/tools/flip_server/flip_config.h"
22 #include "net/tools/flip_server/output_ordering.h"
23 #include "net/tools/flip_server/sm_connection.h"
24 #include "net/tools/flip_server/sm_interface.h"
25 #include "net/tools/flip_server/spdy_interface.h"
26 #include "net/tools/flip_server/streamer_interface.h"
28 // If true, then disables the nagle algorithm);
29 bool FLAGS_disable_nagle = true;
31 // The number of times that accept() will be called when the
32 // alarm goes off when the accept_using_alarm flag is set to true.
33 // If set to 0, accept() will be performed until the accept queue
34 // is completely drained and the accept() call returns an error);
35 int32 FLAGS_accepts_per_wake = 0;
37 // The size of the TCP accept backlog);
38 int32 FLAGS_accept_backlog_size = 1024;
40 // If set to false a single socket will be used. If set to true
41 // then a new socket will be created for each accept thread.
42 // Note that this only works with kernels that support
43 // SO_REUSEPORT);
44 bool FLAGS_reuseport = false;
46 // Flag to force spdy, even if NPN is not negotiated.
47 bool FLAGS_force_spdy = false;
49 // The amount of time the server delays before sending back the
50 // reply);
51 double FLAGS_server_think_time_in_s = 0;
53 net::FlipConfig g_proxy_config;
55 bool GotQuitFromStdin() {
56 // Make stdin nonblocking. Yes this is done each time. Oh well.
57 fcntl(0, F_SETFL, O_NONBLOCK);
58 char c;
59 std::string maybequit;
60 while (read(0, &c, 1) > 0) {
61 maybequit += c;
63 if (maybequit.size()) {
64 VLOG(1) << "scanning string: \"" << maybequit << "\"";
66 return (maybequit.size() > 1 &&
67 (maybequit.c_str()[0] == 'q' || maybequit.c_str()[0] == 'Q'));
70 const char* BoolToStr(bool b) {
71 if (b)
72 return "true";
73 return "false";
76 static bool wantExit = false;
77 static bool wantLogClose = false;
78 void SignalHandler(int signum) {
79 switch (signum) {
80 case SIGTERM:
81 case SIGINT:
82 wantExit = true;
83 break;
84 case SIGHUP:
85 wantLogClose = true;
86 break;
90 static int OpenPidFile(const char* pidfile) {
91 int fd;
92 struct stat pid_stat;
93 int ret;
95 fd = open(pidfile, O_RDWR | O_CREAT, 0600);
96 if (fd == -1) {
97 fprintf(stderr, "Could not open pid file '%s' for reading.\n", pidfile);
98 exit(1);
101 ret = flock(fd, LOCK_EX | LOCK_NB);
102 if (ret == -1) {
103 if (errno == EWOULDBLOCK) {
104 fprintf(stderr, "Flip server is already running.\n");
105 } else {
106 perror("Error getting lock on pid file");
108 exit(1);
111 if (fstat(fd, &pid_stat) == -1) {
112 fprintf(
113 stderr, "Could not stat pid file '%s': %s\n", pidfile, strerror(errno));
114 exit(1);
116 if (pid_stat.st_size != 0) {
117 if (ftruncate(fd, pid_stat.st_size) == -1) {
118 fprintf(stderr,
119 "Could not truncate pid file '%s': %s\n",
120 pidfile,
121 strerror(errno));
122 exit(1);
126 char pid_str[8];
127 snprintf(pid_str, sizeof(pid_str), "%d", getpid());
128 int bytes = static_cast<int>(strlen(pid_str));
129 if (write(fd, pid_str, strlen(pid_str)) != bytes) {
130 perror("Could not write pid file");
131 close(fd);
132 exit(1);
135 return fd;
138 int main(int argc, char** argv) {
139 unsigned int i = 0;
140 bool wait_for_iface = false;
141 int pidfile_fd;
143 signal(SIGPIPE, SIG_IGN);
144 signal(SIGTERM, SignalHandler);
145 signal(SIGINT, SignalHandler);
146 signal(SIGHUP, SignalHandler);
148 base::CommandLine::Init(argc, argv);
149 base::CommandLine cl(argc, argv);
151 if (cl.HasSwitch("help") || argc < 2) {
152 printf("%s <options>\n", argv[0]);
153 printf(" Proxy options:\n");
154 printf(
155 "\t--proxy<1..n>=\"<listen ip>,<listen port>,"
156 "<ssl cert filename>,\n"
157 "\t <ssl key filename>,<http server ip>,"
158 "<http server port>,\n"
159 "\t [https server ip],[https server port],"
160 "<spdy only 0|1>\"\n"
161 "\t * The https server ip and port may be left empty if they are"
162 " the same as\n"
163 "\t the http server fields.\n"
164 "\t * spdy only prevents non-spdy https connections from being"
165 " passed\n"
166 "\t through the proxy listen ip:port.\n"
167 "\t--forward-ip-header=<header name>\n"
168 "\n Server options:\n"
169 "\t--spdy-server=\"<listen ip>,<listen port>,[ssl cert filename],"
170 "\n\t [ssl key filename]\"\n"
171 "\t--http-server=\"<listen ip>,<listen port>,[ssl cert filename],"
172 "\n\t [ssl key filename]\"\n"
173 "\t * Leaving the ssl cert and key fields empty will disable ssl"
174 " for the\n"
175 "\t http and spdy flip servers\n"
176 "\n Global options:\n"
177 "\t--logdest=<file|system|both>\n"
178 "\t--logfile=<logfile>\n"
179 "\t--wait-for-iface\n"
180 "\t * The flip server will block until the listen ip has been"
181 " raised.\n"
182 "\t--ssl-session-expiry=<seconds> (default is 300)\n"
183 "\t--ssl-disable-compression\n"
184 "\t--idle-timeout=<seconds> (default is 300)\n"
185 "\t--pidfile=<filepath> (default /var/run/flip-server.pid)\n"
186 "\t--help\n");
187 exit(0);
190 if (cl.HasSwitch("pidfile")) {
191 pidfile_fd = OpenPidFile(cl.GetSwitchValueASCII("pidfile").c_str());
192 } else {
193 pidfile_fd = OpenPidFile(PIDFILE);
196 net::OutputOrdering::set_server_think_time_in_s(FLAGS_server_think_time_in_s);
198 if (cl.HasSwitch("forward-ip-header")) {
199 net::SpdySM::set_forward_ip_header(
200 cl.GetSwitchValueASCII("forward-ip-header"));
201 net::StreamerSM::set_forward_ip_header(
202 cl.GetSwitchValueASCII("forward-ip-header"));
205 if (cl.HasSwitch("logdest")) {
206 std::string log_dest_value = cl.GetSwitchValueASCII("logdest");
207 if (log_dest_value.compare("file") == 0) {
208 g_proxy_config.log_destination_ = logging::LOG_TO_FILE;
209 } else if (log_dest_value.compare("system") == 0) {
210 g_proxy_config.log_destination_ = logging::LOG_TO_SYSTEM_DEBUG_LOG;
211 } else if (log_dest_value.compare("both") == 0) {
212 g_proxy_config.log_destination_ = logging::LOG_TO_ALL;
213 } else {
214 LOG(FATAL) << "Invalid logging destination value: " << log_dest_value;
216 } else {
217 g_proxy_config.log_destination_ = logging::LOG_NONE;
220 if (cl.HasSwitch("logfile")) {
221 g_proxy_config.log_filename_ = cl.GetSwitchValueASCII("logfile");
222 if (g_proxy_config.log_destination_ == logging::LOG_NONE) {
223 g_proxy_config.log_destination_ = logging::LOG_TO_FILE;
225 } else if ((g_proxy_config.log_destination_ & logging::LOG_TO_FILE) != 0) {
226 LOG(FATAL) << "Logging destination requires a log file to be specified.";
229 if (cl.HasSwitch("wait-for-iface")) {
230 wait_for_iface = true;
233 if (cl.HasSwitch("ssl-session-expiry")) {
234 std::string session_expiry = cl.GetSwitchValueASCII("ssl-session-expiry");
235 g_proxy_config.ssl_session_expiry_ = atoi(session_expiry.c_str());
238 if (cl.HasSwitch("ssl-disable-compression")) {
239 g_proxy_config.ssl_disable_compression_ = true;
242 if (cl.HasSwitch("idle-timeout")) {
243 g_proxy_config.idle_socket_timeout_s_ =
244 atoi(cl.GetSwitchValueASCII("idle-timeout").c_str());
247 if (cl.HasSwitch("force_spdy"))
248 net::SMConnection::set_force_spdy(true);
250 logging::LoggingSettings settings;
251 settings.logging_dest = g_proxy_config.log_destination_;
252 settings.log_file = g_proxy_config.log_filename_.c_str();
253 settings.lock_log = logging::DONT_LOCK_LOG_FILE;
254 logging::InitLogging(settings);
256 LOG(INFO) << "Flip SPDY proxy started with configuration:";
257 LOG(INFO) << "Logging destination : " << g_proxy_config.log_destination_;
258 LOG(INFO) << "Log file : " << g_proxy_config.log_filename_;
259 LOG(INFO) << "Forward IP Header : "
260 << (net::SpdySM::forward_ip_header().length()
261 ? net::SpdySM::forward_ip_header()
262 : "<disabled>");
263 LOG(INFO) << "Wait for interfaces : " << (wait_for_iface ? "true"
264 : "false");
265 LOG(INFO) << "Accept backlog size : " << FLAGS_accept_backlog_size;
266 LOG(INFO) << "Accepts per wake : " << FLAGS_accepts_per_wake;
267 LOG(INFO) << "Disable nagle : " << (FLAGS_disable_nagle ? "true"
268 : "false");
269 LOG(INFO) << "Reuseport : " << (FLAGS_reuseport ? "true"
270 : "false");
271 LOG(INFO) << "Force SPDY : " << (FLAGS_force_spdy ? "true"
272 : "false");
273 LOG(INFO) << "SSL session expiry : "
274 << g_proxy_config.ssl_session_expiry_;
275 LOG(INFO) << "SSL disable compression : "
276 << g_proxy_config.ssl_disable_compression_;
277 LOG(INFO) << "Connection idle timeout : "
278 << g_proxy_config.idle_socket_timeout_s_;
280 // Proxy Acceptors
281 while (true) {
282 i += 1;
283 std::stringstream name;
284 name << "proxy" << i;
285 if (!cl.HasSwitch(name.str())) {
286 break;
288 std::string value = cl.GetSwitchValueASCII(name.str());
289 std::vector<std::string> valueArgs = base::SplitString(
290 value, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
291 CHECK_EQ((unsigned int)9, valueArgs.size());
292 int spdy_only = atoi(valueArgs[8].c_str());
293 // If wait_for_iface is enabled, then this call will block
294 // indefinitely until the interface is raised.
295 g_proxy_config.AddAcceptor(net::FLIP_HANDLER_PROXY,
296 valueArgs[0],
297 valueArgs[1],
298 valueArgs[2],
299 valueArgs[3],
300 valueArgs[4],
301 valueArgs[5],
302 valueArgs[6],
303 valueArgs[7],
304 spdy_only,
305 FLAGS_accept_backlog_size,
306 FLAGS_disable_nagle,
307 FLAGS_accepts_per_wake,
308 FLAGS_reuseport,
309 wait_for_iface,
310 NULL);
313 // Spdy Server Acceptor
314 net::MemoryCache spdy_memory_cache;
315 if (cl.HasSwitch("spdy-server")) {
316 spdy_memory_cache.AddFiles();
317 std::string value = cl.GetSwitchValueASCII("spdy-server");
318 std::vector<std::string> valueArgs = base::SplitString(
319 value, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
320 while (valueArgs.size() < 4)
321 valueArgs.push_back(std::string());
322 g_proxy_config.AddAcceptor(net::FLIP_HANDLER_SPDY_SERVER,
323 valueArgs[0],
324 valueArgs[1],
325 valueArgs[2],
326 valueArgs[3],
327 std::string(),
328 std::string(),
329 std::string(),
330 std::string(),
332 FLAGS_accept_backlog_size,
333 FLAGS_disable_nagle,
334 FLAGS_accepts_per_wake,
335 FLAGS_reuseport,
336 wait_for_iface,
337 &spdy_memory_cache);
340 // Spdy Server Acceptor
341 net::MemoryCache http_memory_cache;
342 if (cl.HasSwitch("http-server")) {
343 http_memory_cache.AddFiles();
344 std::string value = cl.GetSwitchValueASCII("http-server");
345 std::vector<std::string> valueArgs = base::SplitString(
346 value, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
347 while (valueArgs.size() < 4)
348 valueArgs.push_back(std::string());
349 g_proxy_config.AddAcceptor(net::FLIP_HANDLER_HTTP_SERVER,
350 valueArgs[0],
351 valueArgs[1],
352 valueArgs[2],
353 valueArgs[3],
354 std::string(),
355 std::string(),
356 std::string(),
357 std::string(),
359 FLAGS_accept_backlog_size,
360 FLAGS_disable_nagle,
361 FLAGS_accepts_per_wake,
362 FLAGS_reuseport,
363 wait_for_iface,
364 &http_memory_cache);
367 std::vector<net::SMAcceptorThread*> sm_worker_threads_;
369 for (i = 0; i < g_proxy_config.acceptors_.size(); i++) {
370 net::FlipAcceptor* acceptor = g_proxy_config.acceptors_[i];
372 sm_worker_threads_.push_back(new net::SMAcceptorThread(
373 acceptor, (net::MemoryCache*)acceptor->memory_cache_));
374 // Note that spdy_memory_cache is not threadsafe, it is merely
375 // thread compatible. Thus, if ever we are to spawn multiple threads,
376 // we either must make the MemoryCache threadsafe, or use
377 // a separate MemoryCache for each thread.
379 // The latter is what is currently being done as we spawn
380 // a separate thread for each http and spdy server acceptor.
382 sm_worker_threads_.back()->InitWorker();
383 sm_worker_threads_.back()->Start();
386 while (!wantExit) {
387 // Close logfile when HUP signal is received. Logging system will
388 // automatically reopen on next log message.
389 if (wantLogClose) {
390 wantLogClose = false;
391 VLOG(1) << "HUP received, reopening log file.";
392 logging::CloseLogFile();
394 if (GotQuitFromStdin()) {
395 for (unsigned int i = 0; i < sm_worker_threads_.size(); ++i) {
396 sm_worker_threads_[i]->Quit();
398 for (unsigned int i = 0; i < sm_worker_threads_.size(); ++i) {
399 sm_worker_threads_[i]->Join();
401 break;
403 usleep(1000 * 10); // 10 ms
406 unlink(PIDFILE);
407 close(pidfile_fd);
408 return 0;