blob: f6efdd9f1fcb809ca81482b5156bc694bc051f5a [file] [log] [blame]
Nagaraju Goruganti59287f02018-10-12 07:00:20 -05001#include "utils.hpp"
Patrick Williams9638afb2021-02-22 17:16:24 -06002
Nagaraju Goruganti59287f02018-10-12 07:00:20 -05003#include <arpa/inet.h>
4#include <ldap.h>
Patrick Williams9638afb2021-02-22 17:16:24 -06005#include <netdb.h>
6
Asmitha Karunanithi2f64e422022-03-10 01:35:21 -06007#include <boost/algorithm/string.hpp>
8
Patrick Williams9638afb2021-02-22 17:16:24 -06009#include <cstring>
Nagaraju Goruganti59287f02018-10-12 07:00:20 -050010#include <memory>
11
12namespace phosphor
13{
14namespace ldap
15{
16
Nan Zhou78d85042022-08-29 17:50:22 +000017bool isValidLDAPURI(const std::string& uri, const char* scheme)
Nagaraju Goruganti59287f02018-10-12 07:00:20 -050018{
Asmitha Karunanithi2f64e422022-03-10 01:35:21 -060019 // Return false if the user tries to configure port 0
20 // This check is not done in line 42, because ldap_url_parse
21 // method internally converts port 0 to ldap port 389 and it
22 // will always return true (thus allowing the user to
23 // configure port 0)
24
Nan Zhou78d85042022-08-29 17:50:22 +000025 if (boost::algorithm::ends_with(uri, ":0"))
Asmitha Karunanithi2f64e422022-03-10 01:35:21 -060026 {
27 return false;
28 }
29
Nagaraju Goruganti59287f02018-10-12 07:00:20 -050030 LDAPURLDesc* ludpp = nullptr;
31 int res = LDAP_URL_ERR_BADURL;
Nan Zhou78d85042022-08-29 17:50:22 +000032 res = ldap_url_parse(uri.c_str(), &ludpp);
Nagaraju Goruganti59287f02018-10-12 07:00:20 -050033
34 auto ludppCleanupFunc = [](LDAPURLDesc* ludpp) {
35 ldap_free_urldesc(ludpp);
36 };
37 std::unique_ptr<LDAPURLDesc, decltype(ludppCleanupFunc)> ludppPtr(
38 ludpp, ludppCleanupFunc);
39
40 if (res != LDAP_URL_SUCCESS)
41 {
42 return false;
43 }
44 if (std::strcmp(scheme, ludppPtr->lud_scheme) != 0)
45 {
46 return false;
47 }
Asmitha Karunanithi2f64e422022-03-10 01:35:21 -060048 if (ludppPtr->lud_port < 0 || ludppPtr->lud_port > 65536)
49 {
50 return false;
51 }
Nagaraju Goruganti59287f02018-10-12 07:00:20 -050052 addrinfo hints{};
53 addrinfo* servinfo = nullptr;
54 hints.ai_family = AF_UNSPEC;
55 hints.ai_socktype = SOCK_STREAM;
56 hints.ai_flags |= AI_CANONNAME;
57
58 auto result = getaddrinfo(ludppPtr->lud_host, nullptr, &hints, &servinfo);
59 auto cleanupFunc = [](addrinfo* servinfo) { freeaddrinfo(servinfo); };
Patrick Williams16c2b682024-08-16 15:20:56 -040060 std::unique_ptr<addrinfo, decltype(cleanupFunc)> servinfoPtr(
61 servinfo, cleanupFunc);
Nagaraju Goruganti59287f02018-10-12 07:00:20 -050062
63 if (result)
64 {
65 return false;
66 }
67 return true;
68}
69
70} // namespace ldap
71} // namespace phosphor