1 // 2 // Copyright (C) 2012 The Android Open Source Project 3 // 4 // Licensed under the Apache License, Version 2.0 (the "License"); 5 // you may not use this file except in compliance with the License. 6 // You may obtain a copy of the License at 7 // 8 // http://www.apache.org/licenses/LICENSE-2.0 9 // 10 // Unless required by applicable law or agreed to in writing, software 11 // distributed under the License is distributed on an "AS IS" BASIS, 12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 // See the License for the specific language governing permissions and 14 // limitations under the License. 15 // 16 17 #include "shill/http_url.h" 18 19 #include <string> 20 #include <vector> 21 22 #include <base/strings/string_number_conversions.h> 23 #include <base/strings/string_split.h> 24 25 using std::string; 26 using std::vector; 27 28 namespace shill { 29 30 const int HTTPURL::kDefaultHTTPPort = 80; 31 const int HTTPURL::kDefaultHTTPSPort = 443; 32 33 const char HTTPURL::kDelimiters[] = " /#?"; 34 const char HTTPURL::kPortSeparator = ':'; 35 const char HTTPURL::kPrefixHTTP[] = "http://"; 36 const char HTTPURL::kPrefixHTTPS[] = "https://"; 37 38 HTTPURL::HTTPURL() 39 : port_(kDefaultHTTPPort), 40 protocol_(kProtocolHTTP) {} 41 42 HTTPURL::~HTTPURL() {} 43 44 bool HTTPURL::ParseFromString(const string& url_string) { 45 Protocol protocol = kProtocolUnknown; 46 size_t host_start = 0; 47 int port = 0; 48 const string http_url_prefix(kPrefixHTTP); 49 const string https_url_prefix(kPrefixHTTPS); 50 if (url_string.substr(0, http_url_prefix.length()) == http_url_prefix) { 51 host_start = http_url_prefix.length(); 52 port = kDefaultHTTPPort; 53 protocol = kProtocolHTTP; 54 } else if ( 55 url_string.substr(0, https_url_prefix.length()) == https_url_prefix) { 56 host_start = https_url_prefix.length(); 57 port = kDefaultHTTPSPort; 58 protocol = kProtocolHTTPS; 59 } else { 60 return false; 61 } 62 63 size_t host_end = url_string.find_first_of(kDelimiters, host_start); 64 if (host_end == string::npos) { 65 host_end = url_string.length(); 66 } 67 vector<string> host_parts = base::SplitString( 68 url_string.substr(host_start, host_end - host_start), 69 std::string{kPortSeparator}, base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); 70 71 if (host_parts.empty() || host_parts[0].empty() || host_parts.size() > 2) { 72 return false; 73 } else if (host_parts.size() == 2) { 74 if (!base::StringToInt(host_parts[1], &port)) { 75 return false; 76 } 77 } 78 79 protocol_ = protocol; 80 host_ = host_parts[0]; 81 port_ = port; 82 path_ = url_string.substr(host_end); 83 if (path_.empty() || path_[0] != '/') { 84 path_ = "/" + path_; 85 } 86 87 return true; 88 } 89 90 } // namespace shill 91