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.
4
5#include <stdio.h>
6
7#include "base/at_exit.h"
8#include "base/command_line.h"
9#include "base/file_path.h"
10#include "base/logging.h"
11#include "base/message_loop.h"
12#include "base/utf_string_conversions.h"
13#include "net/test/test_server.h"
14
15static void PrintUsage() {
16  printf("run_testserver --doc-root=relpath [--http|--https|--ftp|--sync]\n");
17  printf("(NOTE: relpath should be relative to the 'src' directory)\n");
18}
19
20int main(int argc, const char* argv[]) {
21  base::AtExitManager at_exit_manager;
22  MessageLoopForIO message_loop;
23
24  // Process command line
25  CommandLine::Init(argc, argv);
26  CommandLine* command_line = CommandLine::ForCurrentProcess();
27
28  if (!logging::InitLogging(
29          FILE_PATH_LITERAL("testserver.log"),
30          logging::LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG,
31          logging::LOCK_LOG_FILE,
32          logging::APPEND_TO_OLD_LOG_FILE,
33          logging::DISABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS)) {
34    printf("Error: could not initialize logging. Exiting.\n");
35    return -1;
36  }
37
38  if (command_line->GetSwitchCount() == 0 ||
39      command_line->HasSwitch("help")) {
40    PrintUsage();
41    return -1;
42  }
43
44  net::TestServer::Type server_type(net::TestServer::TYPE_HTTP);
45  if (command_line->HasSwitch("https")) {
46    server_type = net::TestServer::TYPE_HTTPS;
47  } else if (command_line->HasSwitch("ftp")) {
48    server_type = net::TestServer::TYPE_FTP;
49  } else if (command_line->HasSwitch("sync")) {
50    server_type = net::TestServer::TYPE_SYNC;
51  }
52
53  FilePath doc_root = command_line->GetSwitchValuePath("doc-root");
54  if ((server_type != net::TestServer::TYPE_SYNC) && doc_root.empty()) {
55    printf("Error: --doc-root must be specified\n");
56    PrintUsage();
57    return -1;
58  }
59
60  net::TestServer test_server(server_type, doc_root);
61  if (!test_server.Start()) {
62    printf("Error: failed to start test server. Exiting.\n");
63    return -1;
64  }
65
66  if (!file_util::DirectoryExists(test_server.document_root())) {
67    printf("Error: invalid doc root: \"%s\" does not exist!\n",
68        UTF16ToUTF8(test_server.document_root().LossyDisplayName()).c_str());
69    return -1;
70  }
71
72  printf("testserver running at %s (type ctrl+c to exit)\n",
73         test_server.host_port_pair().ToString().c_str());
74
75  message_loop.Run();
76  return 0;
77}
78