blob: e052f7b150741a6221b03817d3e2ca87af24d70a [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
Ben Chana0ddf462014-02-06 11:32:42 -080010#include <base/strings/string_number_conversions.h>
11#include <base/strings/string_split.h>
Paul Stewart95133562012-01-18 18:36:57 -080012
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
Paul Stewart8ae18742015-06-16 13:13:10 -070032bool HTTPURL::ParseFromString(const string& url_string) {
Paul Stewart95133562012-01-18 18:36:57 -080033 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
Paul Stewart5ad16062013-02-21 18:10:48 -080059 if (host_parts.empty() || host_parts[0].empty() || host_parts.size() > 2) {
Paul Stewart95133562012-01-18 18:36:57 -080060 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