1 //
2 //  Copyright (C) 2015 Google, 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 "service/common/bluetooth/util/address_helper.h"
18 
19 #include <cstdlib>
20 
21 #include <base/logging.h>
22 #include <base/strings/string_split.h>
23 
24 namespace util {
25 
IsAddressValid(const std::string & address)26 bool IsAddressValid(const std::string& address) {
27   bt_bdaddr_t addr;
28   return BdAddrFromString(address, &addr);
29 }
30 
BdAddrFromString(const std::string & address,bt_bdaddr_t * out_addr)31 bool BdAddrFromString(const std::string& address, bt_bdaddr_t* out_addr) {
32   CHECK(out_addr);
33 
34   if (address.length() != 17)
35     return false;
36 
37   std::vector<std::string> byte_tokens = base::SplitString(
38       address, ":", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
39 
40   if (byte_tokens.size() != 6)
41     return false;
42 
43   for (int i = 0; i < 6; i++) {
44     const auto& token = byte_tokens[i];
45 
46     if (token.length() != 2)
47       return false;
48 
49     char* temp = nullptr;
50     out_addr->address[i] = strtol(token.c_str(), &temp, 16);
51     if (*temp != '\0')
52       return false;
53   }
54 
55   return true;
56 }
57 
58 }  // namespace util
59