Coverage Report

Created: 2025-11-05 06:12

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/pjsip/pjlib/src/pj/addr_resolv_sock.c
Line
Count
Source
1
/* 
2
 * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
3
 * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
4
 *
5
 * This program is free software; you can redistribute it and/or modify
6
 * it under the terms of the GNU General Public License as published by
7
 * the Free Software Foundation; either version 2 of the License, or
8
 * (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA 
18
 */
19
#include <pj/addr_resolv.h>
20
#include <pj/assert.h>
21
#include <pj/string.h>
22
#include <pj/errno.h>
23
#include <pj/ip_helper.h>
24
#include <pj/compat/socket.h>
25
26
#if defined(PJ_GETADDRINFO_USE_CFHOST) && PJ_GETADDRINFO_USE_CFHOST!=0
27
#   include <CoreFoundation/CFString.h>
28
#   include <CFNetwork/CFHost.h>
29
30
#elif defined(PJ_GETADDRINFO_USE_ANDROID) && PJ_GETADDRINFO_USE_ANDROID!=0
31
#   include <sys/poll.h>
32
#   include <resolv.h>
33
#   include <netdb.h>
34
#   include <android/multinetwork.h>
35
#   include <sys/system_properties.h>
36
#   include <dlfcn.h>
37
#endif
38
39
#define THIS_FILE       "addr_resolv_sock.c"
40
#define ANDROID_DNS_TIMEOUT_MS       5000
41
42
PJ_DEF(pj_status_t) pj_gethostbyname(const pj_str_t *hostname, pj_hostent *phe)
43
0
{
44
0
    struct hostent *he;
45
0
    char copy[PJ_MAX_HOSTNAME];
46
47
0
    pj_assert(hostname && hostname ->slen < PJ_MAX_HOSTNAME);
48
    
49
0
    if (hostname->slen >= PJ_MAX_HOSTNAME)
50
0
        return PJ_ENAMETOOLONG;
51
52
0
    pj_memcpy(copy, hostname->ptr, hostname->slen);
53
0
    copy[ hostname->slen ] = '\0';
54
55
0
    he = gethostbyname(copy);
56
0
    if (!he) {
57
0
        return PJ_ERESOLVE;
58
        /* DO NOT use pj_get_netos_error() since host resolution error
59
         * is reported in h_errno instead of errno!
60
        return pj_get_netos_error();
61
         */
62
0
    }
63
64
0
    phe->h_name = he->h_name;
65
0
    phe->h_aliases = he->h_aliases;
66
0
    phe->h_addrtype = he->h_addrtype;
67
0
    phe->h_length = he->h_length;
68
0
    phe->h_addr_list = he->h_addr_list;
69
70
0
    return PJ_SUCCESS;
71
0
}
72
73
/* Resolve IPv4/IPv6 address */
74
PJ_DEF(pj_status_t) pj_getaddrinfo(int af, const pj_str_t *nodename,
75
                                   unsigned *count, pj_addrinfo ai[])
76
0
{
77
0
#if defined(PJ_SOCK_HAS_GETADDRINFO) && PJ_SOCK_HAS_GETADDRINFO!=0
78
0
    char nodecopy[PJ_MAX_HOSTNAME];
79
0
    pj_bool_t has_addr = PJ_FALSE;
80
0
    unsigned i;
81
#if defined(PJ_GETADDRINFO_USE_CFHOST) && PJ_GETADDRINFO_USE_CFHOST!=0
82
    CFStringRef hostname;
83
    CFHostRef hostRef;
84
    pj_status_t status = PJ_SUCCESS;
85
#else
86
0
    int rc;
87
0
    struct addrinfo hint, *res, *orig_res;
88
0
#endif
89
90
0
    PJ_ASSERT_RETURN(nodename && count && *count && ai, PJ_EINVAL);
91
0
    PJ_ASSERT_RETURN(nodename->ptr && nodename->slen, PJ_EINVAL);
92
0
    PJ_ASSERT_RETURN(af==PJ_AF_INET || af==PJ_AF_INET6 ||
93
0
                     af==PJ_AF_UNSPEC, PJ_EINVAL);
94
95
#if PJ_WIN32_WINCE
96
97
    /* Check if nodename is IP address */
98
    pj_bzero(&ai[0], sizeof(ai[0]));
99
    if ((af==PJ_AF_INET || af==PJ_AF_UNSPEC) &&
100
        pj_inet_pton(PJ_AF_INET, nodename,
101
                     &ai[0].ai_addr.ipv4.sin_addr) == PJ_SUCCESS)
102
    {
103
        af = PJ_AF_INET;
104
        has_addr = PJ_TRUE;
105
    } else if ((af==PJ_AF_INET6 || af==PJ_AF_UNSPEC) &&
106
               pj_inet_pton(PJ_AF_INET6, nodename,
107
                            &ai[0].ai_addr.ipv6.sin6_addr) == PJ_SUCCESS)
108
    {
109
        af = PJ_AF_INET6;
110
        has_addr = PJ_TRUE;
111
    }
112
113
    if (has_addr) {
114
        pj_str_t tmp;
115
116
        tmp.ptr = ai[0].ai_canonname;
117
        pj_strncpy_with_null(&tmp, nodename, PJ_MAX_HOSTNAME);
118
        ai[0].ai_addr.addr.sa_family = (pj_uint16_t)af;
119
        *count = 1;
120
121
        return PJ_SUCCESS;
122
    }
123
124
#else /* PJ_WIN32_WINCE */
125
0
    PJ_UNUSED_ARG(has_addr);
126
0
#endif
127
128
    /* Copy node name to null terminated string. */
129
0
    if (nodename->slen >= PJ_MAX_HOSTNAME)
130
0
        return PJ_ENAMETOOLONG;
131
0
    pj_memcpy(nodecopy, nodename->ptr, nodename->slen);
132
0
    nodecopy[nodename->slen] = '\0';
133
134
#if defined(PJ_GETADDRINFO_USE_CFHOST) && PJ_GETADDRINFO_USE_CFHOST!=0
135
    hostname =  CFStringCreateWithCStringNoCopy(kCFAllocatorDefault, nodecopy,
136
                                                kCFStringEncodingASCII,
137
                                                kCFAllocatorNull);
138
    hostRef = CFHostCreateWithName(kCFAllocatorDefault, hostname);
139
    if (CFHostStartInfoResolution(hostRef, kCFHostAddresses, nil)) {
140
        CFArrayRef addrRef = CFHostGetAddressing(hostRef, nil);
141
        i = 0;
142
        if (addrRef != nil) {
143
            CFIndex idx, naddr;
144
            
145
            naddr = CFArrayGetCount(addrRef);
146
            for (idx = 0; idx < naddr && i < *count; idx++) {
147
                struct sockaddr *addr;
148
                size_t addr_size;
149
                
150
                addr = (struct sockaddr *)
151
                       CFDataGetBytePtr(CFArrayGetValueAtIndex(addrRef, idx));
152
                /* This should not happen. */
153
                pj_assert(addr);
154
                
155
                /* Ignore unwanted address families */
156
                if (af!=PJ_AF_UNSPEC && addr->sa_family != af)
157
                    continue;
158
159
                /* Store canonical name */
160
                pj_ansi_strxcpy(ai[i].ai_canonname, nodecopy, 
161
                                sizeof(ai[i].ai_canonname));
162
                
163
                /* Store address */
164
                addr_size = sizeof(*addr);
165
                if (addr->sa_family == PJ_AF_INET6) {
166
                    addr_size = addr->sa_len;
167
                }
168
                PJ_ASSERT_ON_FAIL(addr_size <= sizeof(pj_sockaddr), continue);
169
                pj_memcpy(&ai[i].ai_addr, addr, addr_size);
170
                PJ_SOCKADDR_RESET_LEN(&ai[i].ai_addr);
171
                
172
                i++;
173
            }
174
        }
175
        
176
        *count = i;
177
        if (*count == 0)
178
            status = PJ_ERESOLVE;
179
180
    } else {
181
        status = PJ_ERESOLVE;
182
    }
183
    
184
    CFRelease(hostRef);
185
    CFRelease(hostname);
186
    
187
    return status;
188
189
#elif defined(PJ_GETADDRINFO_USE_ANDROID) && PJ_GETADDRINFO_USE_ANDROID!=0
190
    /* Unlike Android API functions which can be safeguarded with
191
     * __builtin_available, functions from libraries like libc.so
192
     * cannot be loaded directly, even surrounded by a statement
193
     * checking their availability. ns_initparse and ns_parserr are only
194
     * available since Android API 23. This leads to failure of compiling
195
     * for Android API 21. Hence, the two functions are dynamically loaded
196
     * so that the library can be compiled with the minimal API 21.
197
     * Otherwise, PJLIB would only compile with APP_PLATFORM=23 at minimum.
198
     */
199
   
200
201
    if (__builtin_available(android 29, *)) {
202
        /* Define function pointers type for ns_initparse and ns_parserr.
203
         * These functions are in libc.so in Android (Bionic) and not
204
         * in libresolv.so like usually in Linux */
205
        typedef int (*ns_initparse_fn)(const unsigned char *, int, void *);
206
        typedef int (*ns_parserr_fn)(const void *, int, int, void *);
207
        /* Initialize function pointers to NULL */
208
        ns_initparse_fn ns_initparse_ptr = NULL;
209
        ns_parserr_fn ns_parserr_ptr = NULL;
210
        /* Load the libc.so library containing network functions */
211
        void *libc_handle = dlopen("libc.so", RTLD_NOW);
212
        if (libc_handle) {
213
            /* Get the ns_initparse, ns_initparse functions from library */
214
            ns_initparse_ptr = (ns_initparse_fn)
215
                               dlsym(libc_handle,
216
                               "ns_initparse");
217
            ns_parserr_ptr = (ns_parserr_fn)
218
                             dlsym(libc_handle,
219
                             "ns_parserr");
220
221
            /* Non-null pointers mean DNS functions are properly loaded */
222
            if (ns_initparse_ptr &&
223
                ns_parserr_ptr) {
224
                pj_bzero(&hint, sizeof(hint));
225
                hint.ai_family = af;
226
                /* Zero value of ai_socktype means the implementation shall
227
                 * attempt to resolve the service name for all supported
228
                 * socket types */
229
                hint.ai_socktype = SOCK_STREAM;
230
231
                /* Perform asynchronous DNS resolution
232
                 * Use NETWORK_UNSPECIFIED lets system choose the network */
233
                unsigned int netid = NETWORK_UNSPECIFIED;
234
        /* Buffer for the DNS response */
235
                unsigned char answer[NS_PACKETSZ];
236
                int rcode = -1;
237
                struct addrinfo *result = NULL, *last = NULL;
238
239
                /* Step 1: Send DNS query */
240
                int resp_handle = android_res_nquery(
241
                                netid, nodecopy, ns_c_in,
242
                                af == PJ_AF_INET ? ns_t_a :
243
                                af == PJ_AF_INET6 ? ns_t_aaaa :
244
                                ns_t_a,
245
                                0);
246
                if (resp_handle < 0) {
247
                    printf("android_res_nquery() failed\n");
248
                    return PJ_ERESOLVE;
249
                }
250
251
                /* Step 2: Wait for response using poll() */
252
                struct pollfd fds;
253
                fds.fd = resp_handle;
254
                fds.events = POLLIN;
255
                int ret = poll(&fds, 1, ANDROID_DNS_TIMEOUT_MS);
256
257
                if (ret <= 0) {
258
                    PJ_LOG(4,(THIS_FILE,"Poll timeout or error"));
259
                    android_res_cancel(resp_handle);
260
                    return PJ_ERESOLVE;
261
                }
262
                /* Step 3: Get DNS response */
263
                int response_size = android_res_nresult(
264
                                  resp_handle, &rcode, answer, sizeof(answer));
265
                if (response_size < 0) {
266
                    PJ_LOG(4,(THIS_FILE,
267
                              "android_res_nresult() failed"));
268
                    return PJ_ERESOLVE;
269
                }
270
271
                /* Step 4: Parse the DNS response */
272
                ns_msg msg;
273
                ns_rr rr;
274
                int num_records, resolved_count = 0;
275
276
                if (ns_initparse_ptr(answer, response_size, &msg) < 0) {
277
                    PJ_LOG(4,(THIS_FILE,
278
                              "Failed to parse DNS response"));
279
                    return PJ_ERESOLVE;
280
                }
281
282
                num_records = ns_msg_count(msg, ns_s_an);
283
                if (num_records == 0) {
284
                    PJ_LOG(4,(THIS_FILE,
285
                              "No DNS %s entries found for %s",
286
                              af == PJ_AF_INET ? "A" :
287
                              af == PJ_AF_INET6 ? "AAAA" :
288
                              "A",
289
                              nodecopy));
290
                    return PJ_ERESOLVE;
291
                }
292
293
                /* Process each answer record */
294
                for (i = 0; i < num_records && resolved_count < *count; i++) {
295
                    if (ns_parserr_ptr(&msg, ns_s_an, i, &rr) < 0) {
296
                        continue;
297
                    }
298
299
                    int type = ns_rr_type(rr);
300
                    int rdlen = ns_rr_rdlen(rr);
301
                    const unsigned char *rdata = ns_rr_rdata(rr);
302
303
                    /* We handle A records (IPv4) and AAAA records (IPv6) */
304
                    if ((type == ns_t_a && rdlen == 4) || (type == ns_t_aaaa
305
            && rdlen == 16)) {
306
307
                        /* For IPv4, fill a temporary sockaddr_in */
308
                        /* For IPv6 fill a sockaddr_in6. */
309
                        if (type == ns_t_a) {
310
                            struct sockaddr_in addr;
311
                            pj_bzero(&addr, sizeof(addr));
312
                            addr.sin_family = PJ_AF_INET;
313
                            pj_memcpy(&addr.sin_addr, rdata, 4);
314
                            /* Copy the sockaddr into pj_addrinfo.ai_addr */
315
                            pj_memcpy(&ai[resolved_count].ai_addr,
316
                                      &addr, sizeof(addr));
317
                        } else {
318
                            /* type == ns_t_aaaa */
319
                            struct sockaddr_in6 addr6;
320
                            pj_bzero(&addr6, sizeof(addr6));
321
                            addr6.sin6_family = PJ_AF_INET6;
322
                            pj_memcpy(&addr6.sin6_addr, rdata, 16);
323
                            pj_memcpy(&ai[resolved_count].ai_addr,
324
                                      &addr6, sizeof(addr6));
325
                        }
326
327
                        /* Store canonical name into ai[].ai_canonname */
328
                        pj_ansi_strxcpy(ai[resolved_count].ai_canonname,
329
                                nodename->ptr,
330
                                sizeof(ai[resolved_count].ai_canonname));
331
                        resolved_count++;
332
                    }
333
                }
334
335
                /* Update the count with the number of valid entries found. */
336
                *count = resolved_count;
337
338
                if (resolved_count == 0) {
339
                    return PJ_ERESOLVE;
340
                }
341
                return PJ_SUCCESS;
342
            }
343
        }
344
    }
345
    /* Android fallback to getaddrinfo() for API levels < 29 */
346
    pj_bzero(&hint, sizeof(hint));
347
    hint.ai_family = af;
348
    /* Zero value of ai_socktype means the implementation shall attempt
349
     * to resolve the service name for all supported socket types */
350
    hint.ai_socktype = 0;
351
352
    rc = getaddrinfo(nodecopy, NULL, &hint, &res);
353
    if (rc != 0)
354
        return PJ_ERESOLVE;
355
356
    orig_res = res;
357
358
    /* Enumerate each item in the result */
359
    for (i=0; i<*count && res; res=res->ai_next) {
360
        unsigned j;
361
        pj_bool_t duplicate_found = PJ_FALSE;
362
363
        /* Ignore unwanted address families */
364
        if (af!=PJ_AF_UNSPEC && res->ai_family != af)
365
            continue;
366
367
        if (res->ai_socktype != pj_SOCK_DGRAM() &&
368
            res->ai_socktype != pj_SOCK_STREAM() &&
369
            /* It is possible that the result's sock type
370
             * is unspecified.
371
             */
372
            res->ai_socktype != 0)
373
            {
374
            continue;
375
            }
376
377
        /* Add current address in the resulting list if there
378
         * is no duplicates only. */
379
        for (j = 0; j < i; j++) {
380
            if (!pj_sockaddr_cmp(&ai[j].ai_addr, res->ai_addr)) {
381
                duplicate_found = PJ_TRUE;
382
                break;
383
            }
384
        }
385
        if (duplicate_found) {
386
            continue;
387
        }
388
389
        /* Store canonical name (possibly truncating the name) */
390
        if (res->ai_canonname) {
391
            pj_ansi_strxcpy(ai[i].ai_canonname, res->ai_canonname,
392
                            sizeof(ai[i].ai_canonname));
393
        } else {
394
            pj_ansi_strxcpy(ai[i].ai_canonname, nodecopy,
395
                            sizeof(ai[i].ai_canonname));
396
        }
397
398
        /* Store address */
399
        PJ_ASSERT_ON_FAIL(res->ai_addrlen <= sizeof(pj_sockaddr), continue);
400
        pj_memcpy(&ai[i].ai_addr, res->ai_addr, res->ai_addrlen);
401
        PJ_SOCKADDR_RESET_LEN(&ai[i].ai_addr);
402
403
        /* Next slot */
404
        ++i;
405
    }
406
407
    *count = i;
408
409
    freeaddrinfo(orig_res);
410
411
    /* Done */
412
    return (*count > 0? PJ_SUCCESS : PJ_ERESOLVE);
413
414
#else
415
    /* Call getaddrinfo() */
416
0
    pj_bzero(&hint, sizeof(hint));
417
0
    hint.ai_family = af;
418
    /* Zero value of ai_socktype means the implementation shall attempt
419
     * to resolve the service name for all supported socket types */
420
0
    hint.ai_socktype = 0;
421
422
0
    rc = getaddrinfo(nodecopy, NULL, &hint, &res);
423
0
    if (rc != 0)
424
0
        return PJ_ERESOLVE;
425
426
0
    orig_res = res;
427
428
    /* Enumerate each item in the result */
429
0
    for (i=0; i<*count && res; res=res->ai_next) {
430
0
        unsigned j;
431
0
        pj_bool_t duplicate_found = PJ_FALSE;
432
433
        /* Ignore unwanted address families */
434
0
        if (af!=PJ_AF_UNSPEC && res->ai_family != af)
435
0
            continue;
436
437
0
        if (res->ai_socktype != pj_SOCK_DGRAM() &&
438
0
            res->ai_socktype != pj_SOCK_STREAM() &&
439
            /* It is possible that the result's sock type
440
             * is unspecified.
441
             */
442
0
            res->ai_socktype != 0)
443
0
        {
444
0
                continue;
445
0
        }
446
447
        /* Add current address in the resulting list if there
448
         * is no duplicates only. */
449
0
        for (j = 0; j < i; j++) {
450
0
            if (!pj_sockaddr_cmp(&ai[j].ai_addr, res->ai_addr)) {
451
0
                duplicate_found = PJ_TRUE;
452
0
                break;
453
0
            }
454
0
        }
455
0
        if (duplicate_found) {
456
0
            continue;
457
0
        }
458
459
        /* Store canonical name (possibly truncating the name) */
460
0
        if (res->ai_canonname) {
461
0
            pj_ansi_strxcpy(ai[i].ai_canonname, res->ai_canonname,
462
0
                            sizeof(ai[i].ai_canonname));
463
0
        } else {
464
0
            pj_ansi_strxcpy(ai[i].ai_canonname, nodecopy,
465
0
                            sizeof(ai[i].ai_canonname));
466
0
        }
467
468
        /* Store address */
469
0
        PJ_ASSERT_ON_FAIL(res->ai_addrlen <= sizeof(pj_sockaddr), continue);
470
0
        pj_memcpy(&ai[i].ai_addr, res->ai_addr, res->ai_addrlen);
471
0
        PJ_SOCKADDR_RESET_LEN(&ai[i].ai_addr);
472
473
        /* Next slot */
474
0
        ++i;
475
0
    }
476
477
0
    *count = i;
478
479
0
    freeaddrinfo(orig_res);
480
481
    /* Done */
482
0
    return (*count > 0? PJ_SUCCESS : PJ_ERESOLVE);
483
0
#endif
484
485
#else   /* PJ_SOCK_HAS_GETADDRINFO */
486
    pj_bool_t has_addr = PJ_FALSE;
487
488
    PJ_ASSERT_RETURN(count && *count, PJ_EINVAL);
489
490
#if PJ_WIN32_WINCE
491
492
    /* Check if nodename is IP address */
493
    pj_bzero(&ai[0], sizeof(ai[0]));
494
    if ((af==PJ_AF_INET || af==PJ_AF_UNSPEC) &&
495
        pj_inet_pton(PJ_AF_INET, nodename,
496
                     &ai[0].ai_addr.ipv4.sin_addr) == PJ_SUCCESS)
497
    {
498
        af = PJ_AF_INET;
499
        has_addr = PJ_TRUE;
500
    }
501
    else if ((af==PJ_AF_INET6 || af==PJ_AF_UNSPEC) &&
502
             pj_inet_pton(PJ_AF_INET6, nodename,
503
                          &ai[0].ai_addr.ipv6.sin6_addr) == PJ_SUCCESS)
504
    {
505
        af = PJ_AF_INET6;
506
        has_addr = PJ_TRUE;
507
    }
508
509
    if (has_addr) {
510
        pj_str_t tmp;
511
512
        tmp.ptr = ai[0].ai_canonname;
513
        pj_strncpy_with_null(&tmp, nodename, PJ_MAX_HOSTNAME);
514
        ai[0].ai_addr.addr.sa_family = (pj_uint16_t)af;
515
        *count = 1;
516
517
        return PJ_SUCCESS;
518
    }
519
520
#else /* PJ_WIN32_WINCE */
521
    PJ_UNUSED_ARG(has_addr);
522
#endif
523
524
    if (af == PJ_AF_INET || af == PJ_AF_UNSPEC) {
525
        pj_hostent he;
526
        unsigned i, max_count;
527
        pj_status_t status;
528
        
529
        /* VC6 complains that "he" is uninitialized */
530
        #ifdef _MSC_VER
531
        pj_bzero(&he, sizeof(he));
532
        #endif
533
534
        status = pj_gethostbyname(nodename, &he);
535
        if (status != PJ_SUCCESS)
536
            return status;
537
538
        max_count = *count;
539
        *count = 0;
540
541
        pj_bzero(ai, max_count * sizeof(pj_addrinfo));
542
543
        for (i=0; he.h_addr_list[i] && *count<max_count; ++i) {
544
            pj_ansi_strxcpy(ai[*count].ai_canonname, he.h_name,
545
                            sizeof(ai[*count].ai_canonname));
546
547
            ai[*count].ai_addr.ipv4.sin_family = PJ_AF_INET;
548
            pj_memcpy(&ai[*count].ai_addr.ipv4.sin_addr,
549
                      he.h_addr_list[i], he.h_length);
550
            PJ_SOCKADDR_RESET_LEN(&ai[*count].ai_addr);
551
552
            (*count)++;
553
        }
554
555
        return (*count > 0? PJ_SUCCESS : PJ_ERESOLVE);
556
557
    } else {
558
        /* IPv6 is not supported */
559
        *count = 0;
560
561
        return PJ_EIPV6NOTSUP;
562
    }
563
#endif  /* PJ_SOCK_HAS_GETADDRINFO */
564
0
}
565