xref: /openbmc/phosphor-user-manager/phosphor-ldap-config/utils.cpp (revision 0615260c13895dc5534b8b4a2530c94e66c92208)
1 #include "utils.hpp"
2 
3 #include <arpa/inet.h>
4 #include <ldap.h>
5 #include <netdb.h>
6 
7 #include <cstring>
8 #include <memory>
9 
10 namespace phosphor
11 {
12 namespace ldap
13 {
14 
isValidLDAPURI(const std::string & uri,const char * scheme)15 bool isValidLDAPURI(const std::string& uri, const char* scheme)
16 {
17     // Return false if the user tries to configure port 0
18     // This check is not done in line 42, because ldap_url_parse
19     // method internally converts port 0 to ldap port 389 and it
20     // will always return true (thus allowing the user to
21     // configure port 0)
22 
23     if (uri.ends_with(":0"))
24     {
25         return false;
26     }
27 
28     LDAPURLDesc* ludpp = nullptr;
29     int res = LDAP_URL_ERR_BADURL;
30     res = ldap_url_parse(uri.c_str(), &ludpp);
31 
32     auto ludppCleanupFunc = [](LDAPURLDesc* ludpp) {
33         ldap_free_urldesc(ludpp);
34     };
35     std::unique_ptr<LDAPURLDesc, decltype(ludppCleanupFunc)> ludppPtr(
36         ludpp, ludppCleanupFunc);
37 
38     if (res != LDAP_URL_SUCCESS)
39     {
40         return false;
41     }
42     if (std::strcmp(scheme, ludppPtr->lud_scheme) != 0)
43     {
44         return false;
45     }
46     if (ludppPtr->lud_port < 0 || ludppPtr->lud_port > 65536)
47     {
48         return false;
49     }
50     addrinfo hints{};
51     addrinfo* servinfo = nullptr;
52     hints.ai_family = AF_UNSPEC;
53     hints.ai_socktype = SOCK_STREAM;
54     hints.ai_flags |= AI_CANONNAME;
55 
56     auto result = getaddrinfo(ludppPtr->lud_host, nullptr, &hints, &servinfo);
57     auto cleanupFunc = [](addrinfo* servinfo) { freeaddrinfo(servinfo); };
58     std::unique_ptr<addrinfo, decltype(cleanupFunc)> servinfoPtr(
59         servinfo, cleanupFunc);
60 
61     if (result)
62     {
63         return false;
64     }
65     return true;
66 }
67 
68 } // namespace ldap
69 } // namespace phosphor
70