f4618d8750b792785a36dca071e235611cd53297
[folly.git] / folly / Uri.cpp
1 /*
2  * Copyright 2014 Facebook, Inc.
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 <folly/Uri.h>
18
19 #include <ctype.h>
20 #include <boost/regex.hpp>
21
22 namespace folly {
23
24 namespace {
25
26 fbstring submatch(const boost::cmatch& m, size_t idx) {
27   auto& sub = m[idx];
28   return fbstring(sub.first, sub.second);
29 }
30
31 template <class String>
32 void toLower(String& s) {
33   for (auto& c : s) {
34     c = tolower(c);
35   }
36 }
37
38 }  // namespace
39
40 Uri::Uri(StringPiece str) : port_(0) {
41   static const boost::regex uriRegex(
42       "([a-zA-Z][a-zA-Z0-9+.-]*):"  // scheme:
43       "([^?#]*)"                    // authority and path
44       "(?:\\?([^#]*))?"             // ?query
45       "(?:#(.*))?");                // #fragment
46   static const boost::regex authorityAndPathRegex("//([^/]*)(/.*)?");
47
48   boost::cmatch match;
49   if (UNLIKELY(!boost::regex_match(str.begin(), str.end(), match, uriRegex))) {
50     throw std::invalid_argument(to<std::string>("invalid URI ", str));
51   }
52
53   scheme_ = submatch(match, 1);
54   toLower(scheme_);
55
56   StringPiece authorityAndPath(match[2].first, match[2].second);
57   boost::cmatch authorityAndPathMatch;
58   if (!boost::regex_match(authorityAndPath.begin(),
59                           authorityAndPath.end(),
60                           authorityAndPathMatch,
61                           authorityAndPathRegex)) {
62     // Does not start with //, doesn't have authority
63     path_ = authorityAndPath.fbstr();
64   } else {
65     static const boost::regex authorityRegex(
66         "(?:([^@:]*)(?::([^@]*))?@)?"  // username, password
67         "(\\[[^\\]]*\\]|[^\\[:]*)"     // host (IP-literal (e.g. '['+IPv6+']',
68                                        // dotted-IPv4, or named host)
69         "(?::(\\d*))?");               // port
70
71     auto authority = authorityAndPathMatch[1];
72     boost::cmatch authorityMatch;
73     if (!boost::regex_match(authority.first,
74                             authority.second,
75                             authorityMatch,
76                             authorityRegex)) {
77       throw std::invalid_argument(
78           to<std::string>("invalid URI authority ",
79                           StringPiece(authority.first, authority.second)));
80     }
81
82     StringPiece port(authorityMatch[4].first, authorityMatch[4].second);
83     if (!port.empty()) {
84       port_ = to<uint16_t>(port);
85     }
86
87     username_ = submatch(authorityMatch, 1);
88     password_ = submatch(authorityMatch, 2);
89     host_ = submatch(authorityMatch, 3);
90     path_ = submatch(authorityAndPathMatch, 2);
91   }
92
93   query_ = submatch(match, 3);
94   fragment_ = submatch(match, 4);
95 }
96
97 fbstring Uri::authority() const {
98   fbstring result;
99
100   // Port is 5 characters max and we have up to 3 delimiters.
101   result.reserve(host().size() + username().size() + password().size() + 8);
102
103   if (!username().empty() || !password().empty()) {
104     result.append(username());
105
106     if (!password().empty()) {
107       result.push_back(':');
108       result.append(password());
109     }
110
111     result.push_back('@');
112   }
113
114   result.append(host());
115
116   if (port() != 0) {
117     result.push_back(':');
118     toAppend(port(), &result);
119   }
120
121   return result;
122 }
123
124 fbstring Uri::hostname() const {
125   if (host_.size() > 0 && host_[0] == '[') {
126     // If it starts with '[', then it should end with ']', this is ensured by
127     // regex
128     return host_.substr(1, host_.size() - 2);
129   }
130   return host_;
131 }
132
133 const std::vector<std::pair<fbstring, fbstring>>& Uri::getQueryParams() {
134   if (!query_.empty() && queryParams_.empty()) {
135     // Parse query string
136     static const boost::regex queryParamRegex(
137         "(^|&)" /*start of query or start of parameter "&"*/
138         "([^=&]*)=?" /*parameter name and "=" if value is expected*/
139         "([^=&]*)" /*parameter value*/
140         "(?=(&|$))" /*forward reference, next should be end of query or
141                       start of next parameter*/);
142     boost::cregex_iterator paramBeginItr(
143         query_.data(), query_.data() + query_.size(), queryParamRegex);
144     boost::cregex_iterator paramEndItr;
145     for (auto itr = paramBeginItr; itr != paramEndItr; itr++) {
146       if (itr->length(2) == 0) {
147         // key is empty, ignore it
148         continue;
149       }
150       queryParams_.emplace_back(
151           fbstring((*itr)[2].first, (*itr)[2].second), // parameter name
152           fbstring((*itr)[3].first, (*itr)[3].second) // parameter value
153           );
154     }
155   }
156   return queryParams_;
157 }
158
159 }  // namespace folly