blob: f14312fbfcef0305cff7d2a1d140a1c0e077cd5b [file] [log] [blame]
Paul Stewart95133562012-01-18 18:36:57 -08001// Copyright (c) 2012 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#include "shill/http_url.h"
6
7#include <string>
8#include <vector>
9
10#include <base/string_number_conversions.h>
11#include <base/string_split.h>
12
13using std::string;
14using std::vector;
15
16namespace shill {
17
18const int HTTPURL::kDefaultHTTPPort = 80;
19const int HTTPURL::kDefaultHTTPSPort = 443;
20
21const char HTTPURL::kDelimiters[] = " /#?";
22const char HTTPURL::kPortSeparator = ':';
23const char HTTPURL::kPrefixHTTP[] = "http://";
24const char HTTPURL::kPrefixHTTPS[] = "https://";
25
26HTTPURL::HTTPURL()
27 : port_(kDefaultHTTPPort),
28 protocol_(kProtocolHTTP) {}
29
30HTTPURL::~HTTPURL() {}
31
32bool HTTPURL::ParseFromString(const string &url_string) {
33 Protocol protocol = kProtocolUnknown;
34 size_t host_start = 0;
35 int port = 0;
36 const string http_url_prefix(kPrefixHTTP);
37 const string https_url_prefix(kPrefixHTTPS);
38 if (url_string.substr(0, http_url_prefix.length()) == http_url_prefix) {
39 host_start = http_url_prefix.length();
40 port = kDefaultHTTPPort;
41 protocol = kProtocolHTTP;
42 } else if (
43 url_string.substr(0, https_url_prefix.length()) == https_url_prefix) {
44 host_start = https_url_prefix.length();
45 port = kDefaultHTTPSPort;
46 protocol = kProtocolHTTPS;
47 } else {
48 return false;
49 }
50
51 size_t host_end = url_string.find_first_of(kDelimiters, host_start);
52 if (host_end == string::npos) {
53 host_end = url_string.length();
54 }
55 vector<string> host_parts;
56 base::SplitString(url_string.substr(host_start, host_end - host_start),
57 kPortSeparator, &host_parts);
58
59 if (host_parts[0].empty() || host_parts.size() > 2) {
60 return false;
61 } else if (host_parts.size() == 2) {
62 if (!base::StringToInt(host_parts[1], &port)) {
63 return false;
64 }
65 }
66
67 protocol_ = protocol;
68 host_ = host_parts[0];
69 port_ = port;
70 path_ = url_string.substr(host_end);
71 if (path_.empty() || path_[0] != '/') {
72 path_ = "/" + path_;
73 }
74
75 return true;
76}
77
78} // namespace shill