[Android WebView] Fix webview perf bot switchover to use org.chromium.webview_shell...
[chromium-blink-merge.git] / net / base / dns_util.cc
blob9afaf4faec903234bc27c11202169c04d25407a9
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.
5 #include "net/base/dns_util.h"
7 #include <cstring>
9 namespace net {
11 // Based on DJB's public domain code.
12 bool DNSDomainFromDot(const base::StringPiece& dotted, std::string* out) {
13 const char* buf = dotted.data();
14 unsigned n = dotted.size();
15 char label[63];
16 size_t labellen = 0; /* <= sizeof label */
17 char name[255];
18 size_t namelen = 0; /* <= sizeof name */
19 char ch;
21 for (;;) {
22 if (!n)
23 break;
24 ch = *buf++;
25 --n;
26 if (ch == '.') {
27 // Don't allow empty labels per http://crbug.com/456391.
28 if (!labellen)
29 return false;
30 if (namelen + labellen + 1 > sizeof name)
31 return false;
32 name[namelen++] = static_cast<char>(labellen);
33 memcpy(name + namelen, label, labellen);
34 namelen += labellen;
35 labellen = 0;
36 continue;
38 if (labellen >= sizeof label)
39 return false;
40 label[labellen++] = ch;
43 // Allow empty label at end of name to disable suffix search.
44 if (labellen) {
45 if (namelen + labellen + 1 > sizeof name)
46 return false;
47 name[namelen++] = static_cast<char>(labellen);
48 memcpy(name + namelen, label, labellen);
49 namelen += labellen;
50 labellen = 0;
53 if (namelen + 1 > sizeof name)
54 return false;
55 if (namelen == 0) // Empty names e.g. "", "." are not valid.
56 return false;
57 name[namelen++] = 0; // This is the root label (of length 0).
59 *out = std::string(name, namelen);
60 return true;
63 std::string DNSDomainToString(const base::StringPiece& domain) {
64 std::string ret;
66 for (unsigned i = 0; i < domain.size() && domain[i]; i += domain[i] + 1) {
67 #if CHAR_MIN < 0
68 if (domain[i] < 0)
69 return std::string();
70 #endif
71 if (domain[i] > 63)
72 return std::string();
74 if (i)
75 ret += ".";
77 if (static_cast<unsigned>(domain[i]) + i + 1 > domain.size())
78 return std::string();
80 domain.substr(i + 1, domain[i]).AppendToString(&ret);
82 return ret;
85 std::string TrimEndingDot(const base::StringPiece& host) {
86 base::StringPiece host_trimmed = host;
87 size_t len = host_trimmed.length();
88 if (len > 1 && host_trimmed[len - 1] == '.') {
89 host_trimmed.remove_suffix(1);
91 return host_trimmed.as_string();
94 } // namespace net