Coverage Report

Created: 2026-12-01 06:45

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/pupnp/upnp/src/ssdp/ssdp_server.c
Line
Count
Source
1
/**************************************************************************
2
 *
3
 * Copyright (c) 2000-2003 Intel Corporation
4
 * All rights reserved.
5
 * Copyright (C) 2011-2012 France Telecom All rights reserved.
6
 *
7
 * Redistribution and use in source and binary forms, with or without
8
 * modification, are permitted provided that the following conditions are met:
9
 *
10
 * - Redistributions of source code must retain the above copyright notice,
11
 * this list of conditions and the following disclaimer.
12
 * - Redistributions in binary form must reproduce the above copyright notice,
13
 * this list of conditions and the following disclaimer in the documentation
14
 * and/or other materials provided with the distribution.
15
 * - Neither name of Intel Corporation nor the names of its contributors
16
 * may be used to endorse or promote products derived from this software
17
 * without specific prior written permission.
18
 *
19
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL INTEL OR
23
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
27
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
 *
31
 **************************************************************************/
32
33
/*!
34
 * \addtogroup SSDPlib
35
 *
36
 * @{
37
 *
38
 * \file
39
 */
40
41
#include "UpnpGlobal.h"
42
#include "UpnpInet.h"
43
#include "config.h"
44
#include "ithread.h"
45
#include "ixml.h"
46
#include "upnp.h"
47
#include "upnpdebug.h"
48
#include "upnpdebug_internal.h"
49
#include "upnputil.h"
50
#include "uri.h"
51
#include <errno.h>
52
#include <stdint.h>
53
#include <stdlib.h>
54
#include <string.h>
55
#include <sys/types.h>
56
57
#if EXCLUDE_SSDP == 0
58
59
  #include "ssdplib.h"
60
61
  #include "ThreadPool.h"
62
  #include "httpparser.h"
63
  #include "membuffer.h"
64
  #include "miniserver.h"
65
  #include "sock.h"
66
  #include "upnpapi.h"
67
68
  #include <stdio.h>
69
70
  #include "posix_overwrites.h" // IWYU pragma: keep
71
72
  #define MAX_TIME_TOREAD 45
73
74
  #ifdef INCLUDE_CLIENT_APIS
75
SOCKET gSsdpReqSocket4 = INVALID_SOCKET;
76
    #ifdef UPNP_ENABLE_IPV6
77
SOCKET gSsdpReqSocket6 = INVALID_SOCKET;
78
    #endif /* UPNP_ENABLE_IPV6 */
79
  #endif         /* INCLUDE_CLIENT_APIS */
80
81
void RequestHandler(void);
82
83
enum Listener
84
{
85
  Idle,
86
  Stopping,
87
  Running
88
};
89
90
struct SSDPSockArray
91
{
92
  /*! socket for incoming advertisments and search requests */
93
  SOCKET ssdpSock;
94
  #ifdef INCLUDE_CLIENT_APIS
95
  /*! socket for sending search requests and receiving search replies */
96
  int ssdpReqSock;
97
  #endif /* INCLUDE_CLIENT_APIS */
98
};
99
100
  #ifdef INCLUDE_DEVICE_APIS
101
static const char SERVICELIST_STR[] = "serviceList";
102
103
int AdvertiseAndReply(int AdFlag,
104
  UpnpDevice_Handle Hnd,
105
  enum SsdpSearchType SearchType,
106
  struct sockaddr *DestAddr,
107
  char *DeviceType,
108
  char *DeviceUDN,
109
  char *ServiceType,
110
  int Exp)
111
0
{
112
0
  int retVal = UPNP_E_SUCCESS;
113
0
  long unsigned int i;
114
0
  long unsigned int j;
115
0
  int defaultExp = DEFAULT_MAXAGE;
116
0
  struct Handle_Info *SInfo = NULL;
117
0
  char UDNstr[100];
118
0
  char devType[100];
119
0
  char servType[100];
120
0
  IXML_NodeList *nodeList = NULL;
121
0
  IXML_NodeList *tmpNodeList = NULL;
122
0
  IXML_Node *tmpNode = NULL;
123
0
  IXML_Node *tmpNode2 = NULL;
124
0
  IXML_Node *textNode = NULL;
125
0
  const DOMString tmpStr;
126
0
  const DOMString dbgStr;
127
0
  int NumCopy = 0;
128
129
0
  memset(UDNstr, 0, sizeof(UDNstr));
130
0
  memset(devType, 0, sizeof(devType));
131
0
  memset(servType, 0, sizeof(servType));
132
133
0
  UpnpPrintf(UPNP_ALL,
134
0
    API,
135
0
    __FILE__,
136
0
    __LINE__,
137
0
    "Inside AdvertiseAndReply with AdFlag = %d\n",
138
0
    AdFlag);
139
140
  /* Use a read lock */
141
0
  HandleReadLock(__FILE__, __LINE__);
142
0
  if (GetHandleInfo(Hnd, &SInfo) != HND_DEVICE) {
143
0
    retVal = UPNP_E_INVALID_HANDLE;
144
0
    goto end_function;
145
0
  }
146
0
  defaultExp = SInfo->MaxAge;
147
  /* parse the device list and send advertisements/replies */
148
0
  while (NumCopy == 0 || (AdFlag && NumCopy < NUM_SSDP_COPY)) {
149
0
    if (NumCopy != 0)
150
0
      imillisleep(SSDP_PAUSE);
151
0
    NumCopy++;
152
0
    for (i = 0lu;; i++) {
153
0
      UpnpPrintf(UPNP_ALL,
154
0
        API,
155
0
        __FILE__,
156
0
        __LINE__,
157
0
        "Entering new device list with i = %lu\n\n",
158
0
        i);
159
0
      tmpNode = ixmlNodeList_item(SInfo->DeviceList, i);
160
0
      if (!tmpNode) {
161
0
        UpnpPrintf(UPNP_ALL,
162
0
          API,
163
0
          __FILE__,
164
0
          __LINE__,
165
0
          "Exiting new device list with i = "
166
0
          "%lu\n\n",
167
0
          i);
168
0
        break;
169
0
      }
170
0
      dbgStr = ixmlNode_getNodeName(tmpNode);
171
0
      UpnpPrintf(UPNP_INFO,
172
0
        API,
173
0
        __FILE__,
174
0
        __LINE__,
175
0
        "Extracting device type once for %s\n",
176
0
        dbgStr);
177
0
      ixmlNodeList_free(nodeList);
178
0
      nodeList = ixmlElement_getElementsByTagName(
179
0
        (IXML_Element *)tmpNode, "deviceType");
180
0
      if (!nodeList)
181
0
        continue;
182
0
      UpnpPrintf(UPNP_ALL,
183
0
        API,
184
0
        __FILE__,
185
0
        __LINE__,
186
0
        "Extracting UDN for %s\n",
187
0
        dbgStr);
188
0
      UpnpPrintf(UPNP_ALL,
189
0
        API,
190
0
        __FILE__,
191
0
        __LINE__,
192
0
        "Extracting device type\n");
193
0
      tmpNode2 = ixmlNodeList_item(nodeList, 0lu);
194
0
      if (!tmpNode2)
195
0
        continue;
196
0
      textNode = ixmlNode_getFirstChild(tmpNode2);
197
0
      if (!textNode)
198
0
        continue;
199
0
      UpnpPrintf(UPNP_ALL,
200
0
        API,
201
0
        __FILE__,
202
0
        __LINE__,
203
0
        "Extracting device type \n");
204
0
      tmpStr = ixmlNode_getNodeValue(textNode);
205
0
      if (!tmpStr)
206
0
        continue;
207
0
      strncpy(devType, tmpStr, sizeof(devType) - 1);
208
0
      UpnpPrintf(UPNP_ALL,
209
0
        API,
210
0
        __FILE__,
211
0
        __LINE__,
212
0
        "Extracting device type = %s\n",
213
0
        devType);
214
0
      if (!tmpNode) {
215
0
        UpnpPrintf(UPNP_ALL,
216
0
          API,
217
0
          __FILE__,
218
0
          __LINE__,
219
0
          "TempNode is NULL\n");
220
0
      }
221
0
      dbgStr = ixmlNode_getNodeName(tmpNode);
222
0
      UpnpPrintf(UPNP_ALL,
223
0
        API,
224
0
        __FILE__,
225
0
        __LINE__,
226
0
        "Extracting UDN for %s\n",
227
0
        dbgStr);
228
0
      ixmlNodeList_free(nodeList);
229
0
      nodeList = ixmlElement_getElementsByTagName(
230
0
        (IXML_Element *)tmpNode, "UDN");
231
0
      if (!nodeList) {
232
0
        UpnpPrintf(UPNP_CRITICAL,
233
0
          API,
234
0
          __FILE__,
235
0
          __LINE__,
236
0
          "UDN not found!\n");
237
0
        continue;
238
0
      }
239
0
      tmpNode2 = ixmlNodeList_item(nodeList, 0lu);
240
0
      if (!tmpNode2) {
241
0
        UpnpPrintf(UPNP_CRITICAL,
242
0
          API,
243
0
          __FILE__,
244
0
          __LINE__,
245
0
          "UDN not found!\n");
246
0
        continue;
247
0
      }
248
0
      textNode = ixmlNode_getFirstChild(tmpNode2);
249
0
      if (!textNode) {
250
0
        UpnpPrintf(UPNP_CRITICAL,
251
0
          API,
252
0
          __FILE__,
253
0
          __LINE__,
254
0
          "UDN not found!\n");
255
0
        continue;
256
0
      }
257
0
      tmpStr = ixmlNode_getNodeValue(textNode);
258
0
      if (!tmpStr) {
259
0
        UpnpPrintf(UPNP_CRITICAL,
260
0
          API,
261
0
          __FILE__,
262
0
          __LINE__,
263
0
          "UDN not found!\n");
264
0
        continue;
265
0
      }
266
0
      strncpy(UDNstr, tmpStr, sizeof(UDNstr) - 1);
267
0
      UpnpPrintf(UPNP_INFO,
268
0
        API,
269
0
        __FILE__,
270
0
        __LINE__,
271
0
        "Sending UDNStr = %s \n",
272
0
        UDNstr);
273
0
      if (AdFlag) {
274
        /* send the device advertisement */
275
0
        if (AdFlag == 1) {
276
0
          DeviceAdvertisement(devType,
277
0
            i == 0lu,
278
0
            UDNstr,
279
0
            SInfo->DescURL,
280
0
            Exp,
281
0
            SInfo->DeviceAf,
282
0
            SInfo->PowerState,
283
0
            SInfo->SleepPeriod,
284
0
            SInfo->RegistrationState);
285
0
        } else {
286
          /* AdFlag == -1 */
287
0
          DeviceShutdown(devType,
288
0
            i == 0lu,
289
0
            UDNstr,
290
0
            SInfo->DescURL,
291
0
            Exp,
292
0
            SInfo->DeviceAf,
293
0
            SInfo->PowerState,
294
0
            SInfo->SleepPeriod,
295
0
            SInfo->RegistrationState);
296
0
        }
297
0
      } else {
298
0
        switch (SearchType) {
299
0
        case SSDP_ALL:
300
0
          DeviceReply(DestAddr,
301
0
            devType,
302
0
            i == 0lu,
303
0
            UDNstr,
304
0
            SInfo->DescURL,
305
0
            defaultExp,
306
0
            SInfo->PowerState,
307
0
            SInfo->SleepPeriod,
308
0
            SInfo->RegistrationState);
309
0
          break;
310
0
        case SSDP_ROOTDEVICE:
311
0
          if (i == 0lu) {
312
0
            SendReply(DestAddr,
313
0
              devType,
314
0
              1,
315
0
              UDNstr,
316
0
              SInfo->DescURL,
317
0
              defaultExp,
318
0
              0,
319
0
              SInfo->PowerState,
320
0
              SInfo->SleepPeriod,
321
0
              SInfo->RegistrationState);
322
0
          }
323
0
          break;
324
0
        case SSDP_DEVICEUDN: {
325
          /* clang-format off */
326
0
          if (DeviceUDN && strlen(DeviceUDN) != (size_t)0) {
327
0
            if (strcasecmp(DeviceUDN, UDNstr)) {
328
0
              UpnpPrintf(UPNP_INFO, API, __FILE__, __LINE__,
329
0
                "DeviceUDN=%s and search UDN=%s DID NOT match\n",
330
0
                UDNstr, DeviceUDN);
331
0
            } else {
332
0
              UpnpPrintf(UPNP_INFO, API, __FILE__, __LINE__,
333
0
                "DeviceUDN=%s and search UDN=%s MATCH\n",
334
0
                UDNstr, DeviceUDN);
335
0
              SendReply(DestAddr, devType, 0, UDNstr, SInfo->DescURL, defaultExp, 0,
336
0
                SInfo->PowerState,
337
0
                SInfo->SleepPeriod,
338
0
                SInfo->RegistrationState);
339
0
            }
340
0
          }
341
          /* clang-format on */
342
0
          break;
343
0
        }
344
0
        case SSDP_DEVICETYPE: {
345
          /* clang-format off */
346
0
          if (!strncasecmp(DeviceType, devType, strlen(DeviceType) - (size_t)2)) {
347
0
            if (atoi(strrchr(DeviceType, ':') + 1)
348
0
                < atoi(&devType[strlen(devType) - (size_t)1])) {
349
              /* the requested version is lower than the device version
350
               * must reply with the lower version number and the lower
351
               * description URL */
352
0
              UpnpPrintf(UPNP_INFO, API, __FILE__, __LINE__,
353
0
                   "DeviceType=%s and search devType=%s MATCH\n",
354
0
                   devType, DeviceType);
355
0
              SendReply(DestAddr, DeviceType, 0, UDNstr, SInfo->LowerDescURL,
356
0
                  defaultExp, 1,
357
0
                  SInfo->PowerState,
358
0
                  SInfo->SleepPeriod,
359
0
                  SInfo->RegistrationState);
360
0
            } else if (atoi(strrchr(DeviceType, ':') + 1)
361
0
                 == atoi(&devType[strlen(devType) - (size_t)1])) {
362
0
              UpnpPrintf(UPNP_INFO, API, __FILE__, __LINE__,
363
0
                   "DeviceType=%s and search devType=%s MATCH\n",
364
0
                   devType, DeviceType);
365
0
              SendReply(DestAddr, DeviceType, 0, UDNstr, SInfo->DescURL,
366
0
                  defaultExp, 1,
367
0
                  SInfo->PowerState,
368
0
                  SInfo->SleepPeriod,
369
0
                  SInfo->RegistrationState);
370
0
            } else {
371
0
              UpnpPrintf(UPNP_INFO, API, __FILE__, __LINE__,
372
0
                   "DeviceType=%s and search devType=%s DID NOT MATCH\n",
373
0
                   devType, DeviceType);
374
0
            }
375
0
          } else {
376
0
            UpnpPrintf(UPNP_INFO, API, __FILE__, __LINE__,
377
0
                 "DeviceType=%s and search devType=%s DID NOT MATCH\n",
378
0
                 devType, DeviceType);
379
0
          }
380
          /* clang-format on */
381
0
          break;
382
0
        }
383
0
        default:
384
0
          break;
385
0
        }
386
0
      }
387
      /* send service advertisements for services
388
       * corresponding to the same device */
389
0
      UpnpPrintf(UPNP_INFO,
390
0
        API,
391
0
        __FILE__,
392
0
        __LINE__,
393
0
        "Sending service Advertisement\n");
394
      /* Correct service traversal such that each device's
395
       * serviceList is directly traversed as a child of its
396
       * parent device. This ensures that the service's alive
397
       * message uses the UDN of the parent device. */
398
0
      tmpNode = ixmlNode_getFirstChild(tmpNode);
399
0
      while (tmpNode) {
400
0
        dbgStr = ixmlNode_getNodeName(tmpNode);
401
0
        if (!strncmp(dbgStr,
402
0
              SERVICELIST_STR,
403
0
              sizeof SERVICELIST_STR)) {
404
0
          break;
405
0
        }
406
0
        tmpNode = ixmlNode_getNextSibling(tmpNode);
407
0
      }
408
0
      ixmlNodeList_free(nodeList);
409
0
      if (!tmpNode) {
410
0
        nodeList = NULL;
411
0
        continue;
412
0
      }
413
0
      nodeList = ixmlElement_getElementsByTagName(
414
0
        (IXML_Element *)tmpNode, "service");
415
0
      if (!nodeList) {
416
0
        UpnpPrintf(UPNP_INFO,
417
0
          API,
418
0
          __FILE__,
419
0
          __LINE__,
420
0
          "Service not found 3\n");
421
0
        continue;
422
0
      }
423
0
      for (j = 0lu;; j++) {
424
0
        tmpNode = ixmlNodeList_item(nodeList, j);
425
0
        if (!tmpNode) {
426
0
          break;
427
0
        }
428
0
        ixmlNodeList_free(tmpNodeList);
429
0
        tmpNodeList = ixmlElement_getElementsByTagName(
430
0
          (IXML_Element *)tmpNode, "serviceType");
431
0
        if (!tmpNodeList) {
432
0
          UpnpPrintf(UPNP_CRITICAL,
433
0
            API,
434
0
            __FILE__,
435
0
            __LINE__,
436
0
            "ServiceType not found \n");
437
0
          continue;
438
0
        }
439
0
        tmpNode2 = ixmlNodeList_item(tmpNodeList, 0lu);
440
0
        if (!tmpNode2)
441
0
          continue;
442
0
        textNode = ixmlNode_getFirstChild(tmpNode2);
443
0
        if (!textNode)
444
0
          continue;
445
        /* servType is of format
446
         * Servicetype:ServiceVersion */
447
0
        tmpStr = ixmlNode_getNodeValue(textNode);
448
0
        if (!tmpStr)
449
0
          continue;
450
0
        strncpy(servType, tmpStr, sizeof(servType) - 1);
451
0
        UpnpPrintf(UPNP_INFO,
452
0
          API,
453
0
          __FILE__,
454
0
          __LINE__,
455
0
          "ServiceType = %s\n",
456
0
          servType);
457
0
        if (AdFlag) {
458
0
          if (AdFlag == 1) {
459
0
            ServiceAdvertisement(UDNstr,
460
0
              servType,
461
0
              SInfo->DescURL,
462
0
              Exp,
463
0
              SInfo->DeviceAf,
464
0
              SInfo->PowerState,
465
0
              SInfo->SleepPeriod,
466
0
              SInfo->RegistrationState);
467
0
          } else {
468
            /* AdFlag == -1 */
469
0
            ServiceShutdown(UDNstr,
470
0
              servType,
471
0
              SInfo->DescURL,
472
0
              Exp,
473
0
              SInfo->DeviceAf,
474
0
              SInfo->PowerState,
475
0
              SInfo->SleepPeriod,
476
0
              SInfo->RegistrationState);
477
0
          }
478
0
        } else {
479
0
          switch (SearchType) {
480
0
          case SSDP_ALL:
481
0
            ServiceReply(DestAddr,
482
0
              servType,
483
0
              UDNstr,
484
0
              SInfo->DescURL,
485
0
              defaultExp,
486
0
              SInfo->PowerState,
487
0
              SInfo->SleepPeriod,
488
0
              SInfo->RegistrationState);
489
0
            break;
490
0
          case SSDP_SERVICE:
491
            /* clang-format off */
492
0
            if (ServiceType) {
493
0
              if (!strncasecmp(ServiceType, servType, strlen(ServiceType) - (size_t)2)) {
494
0
                if (atoi(strrchr(ServiceType, ':') + 1) <
495
0
                    atoi(&servType[strlen(servType) - (size_t)1])) {
496
                  /* the requested version is lower than the service version
497
                   * must reply with the lower version number and the lower
498
                   * description URL */
499
0
                  UpnpPrintf(UPNP_INFO, API, __FILE__, __LINE__,
500
0
                       "ServiceType=%s and search servType=%s MATCH\n",
501
0
                       ServiceType, servType);
502
0
                  SendReply(DestAddr, ServiceType, 0, UDNstr, SInfo->LowerDescURL,
503
0
                      defaultExp, 1,
504
0
                      SInfo->PowerState,
505
0
                      SInfo->SleepPeriod,
506
0
                      SInfo->RegistrationState);
507
0
                } else if (atoi(strrchr (ServiceType, ':') + 1) ==
508
0
                     atoi(&servType[strlen(servType) - (size_t)1])) {
509
0
                  UpnpPrintf(UPNP_INFO, API, __FILE__, __LINE__,
510
0
                       "ServiceType=%s and search servType=%s MATCH\n",
511
0
                       ServiceType, servType);
512
0
                  SendReply(DestAddr, ServiceType, 0, UDNstr, SInfo->DescURL,
513
0
                      defaultExp, 1,
514
0
                      SInfo->PowerState,
515
0
                      SInfo->SleepPeriod,
516
0
                      SInfo->RegistrationState);
517
0
                } else {
518
0
                  UpnpPrintf(UPNP_INFO, API, __FILE__, __LINE__,
519
0
                     "ServiceType=%s and search servType=%s DID NOT MATCH\n",
520
0
                     ServiceType, servType);
521
0
                }
522
0
              } else {
523
0
                UpnpPrintf(UPNP_INFO, API, __FILE__, __LINE__,
524
0
                     "ServiceType=%s and search servType=%s DID NOT MATCH\n",
525
0
                     ServiceType, servType);
526
0
              }
527
0
            }
528
            /* clang-format on */
529
0
            break;
530
0
          default:
531
0
            break;
532
0
          }
533
0
        }
534
0
      }
535
0
      ixmlNodeList_free(tmpNodeList);
536
0
      tmpNodeList = NULL;
537
0
      ixmlNodeList_free(nodeList);
538
0
      nodeList = NULL;
539
0
    }
540
0
  }
541
542
0
end_function:
543
0
  ixmlNodeList_free(tmpNodeList);
544
0
  ixmlNodeList_free(nodeList);
545
0
  UpnpPrintf(UPNP_ALL,
546
0
    API,
547
0
    __FILE__,
548
0
    __LINE__,
549
0
    "Exiting AdvertiseAndReply.\n");
550
0
  HandleUnlock(__FILE__, __LINE__);
551
552
0
  return retVal;
553
0
}
554
  #endif /* INCLUDE_DEVICE_APIS */
555
556
int unique_service_name(char *cmd, SsdpEvent *Evt)
557
0
{
558
0
  char TempBuf[LINE_SIZE - 3];
559
0
  char *TempPtr = NULL;
560
0
  char *Ptr = NULL;
561
0
  char *ptr1 = NULL;
562
0
  char *ptr2 = NULL;
563
0
  char *ptr3 = NULL;
564
0
  int CommandFound = 0;
565
0
  size_t n = (size_t)0;
566
567
0
  if (strstr(cmd, "uuid:schemas") != NULL) {
568
0
    ptr1 = strstr(cmd, ":device");
569
0
    if (ptr1 != NULL)
570
0
      ptr2 = strstr(ptr1 + 1, ":");
571
0
    else
572
0
      return -1;
573
0
    if (ptr2 != NULL)
574
0
      ptr3 = strstr(ptr2 + 1, ":");
575
0
    else
576
0
      return -1;
577
0
    if (ptr3 != NULL) {
578
0
      if (strlen("uuid:") + strlen(ptr3 + 1) >=
579
0
        sizeof Evt->UDN)
580
0
        return -1;
581
0
      snprintf(
582
0
        Evt->UDN, sizeof Evt->UDN, "uuid:%s", ptr3 + 1);
583
0
    } else
584
0
      return -1;
585
0
    ptr1 = strstr(cmd, ":");
586
0
    if (ptr1 != NULL) {
587
0
      n = (size_t)ptr3 - (size_t)ptr1;
588
0
      n = n >= sizeof TempBuf ? sizeof TempBuf - 1 : n;
589
0
      strncpy(TempBuf, ptr1, n);
590
0
      TempBuf[n] = '\0';
591
0
      if (strlen("urn") + strlen(TempBuf) >=
592
0
        sizeof(Evt->DeviceType))
593
0
        return -1;
594
0
      snprintf(Evt->DeviceType,
595
0
        sizeof(Evt->DeviceType),
596
0
        "urn%s",
597
0
        TempBuf);
598
0
    } else
599
0
      return -1;
600
0
    return 0;
601
0
  }
602
0
  if ((TempPtr = strstr(cmd, "uuid")) != NULL) {
603
0
    if ((Ptr = strstr(cmd, "::")) != NULL) {
604
0
      n = (size_t)Ptr - (size_t)TempPtr;
605
0
      n = n >= sizeof Evt->UDN ? sizeof Evt->UDN - 1 : n;
606
0
      strncpy(Evt->UDN, TempPtr, n);
607
0
      Evt->UDN[n] = '\0';
608
0
    } else {
609
0
      memset(Evt->UDN, 0, sizeof(Evt->UDN));
610
0
      strncpy(Evt->UDN, TempPtr, sizeof Evt->UDN - 1);
611
0
    }
612
0
    CommandFound = 1;
613
0
  }
614
0
  if (strstr(cmd, "urn:") != NULL && strstr(cmd, ":service:") != NULL) {
615
0
    if ((TempPtr = strstr(cmd, "urn")) != NULL) {
616
0
      memset(Evt->ServiceType, 0, sizeof Evt->ServiceType);
617
0
      strncpy(Evt->ServiceType,
618
0
        TempPtr,
619
0
        sizeof Evt->ServiceType - 1);
620
0
      CommandFound = 1;
621
0
    }
622
0
  }
623
0
  if (strstr(cmd, "urn:") != NULL && strstr(cmd, ":device:") != NULL) {
624
0
    if ((TempPtr = strstr(cmd, "urn")) != NULL) {
625
0
      memset(Evt->DeviceType, 0, sizeof Evt->DeviceType);
626
0
      strncpy(Evt->DeviceType,
627
0
        TempPtr,
628
0
        sizeof Evt->DeviceType - 1);
629
0
      CommandFound = 1;
630
0
    }
631
0
  }
632
0
  if ((TempPtr = strstr(cmd, "::upnp:rootdevice")) != NULL) {
633
    /* Everything before "::upnp::rootdevice" is the UDN. */
634
0
    if (TempPtr != cmd) {
635
0
      n = (size_t)TempPtr - (size_t)cmd;
636
0
      n = n >= sizeof Evt->UDN ? sizeof Evt->UDN - 1 : n;
637
0
      strncpy(Evt->UDN, cmd, n);
638
0
      Evt->UDN[n] = 0;
639
0
      CommandFound = 1;
640
0
    }
641
0
  }
642
0
  if (CommandFound == 0)
643
0
    return -1;
644
645
0
  return 0;
646
0
}
647
648
enum SsdpSearchType ssdp_request_type1(char *cmd)
649
0
{
650
0
  if (strstr(cmd, ":all"))
651
0
    return SSDP_ALL;
652
0
  if (strstr(cmd, ":rootdevice"))
653
0
    return SSDP_ROOTDEVICE;
654
0
  if (strstr(cmd, "uuid:"))
655
0
    return SSDP_DEVICEUDN;
656
0
  if (strstr(cmd, "urn:") && strstr(cmd, ":device:"))
657
0
    return SSDP_DEVICETYPE;
658
0
  if (strstr(cmd, "urn:") && strstr(cmd, ":service:"))
659
0
    return SSDP_SERVICE;
660
0
  return SSDP_SERROR;
661
0
}
662
663
int ssdp_request_type(char *cmd, SsdpEvent *Evt)
664
0
{
665
  /* clear event */
666
0
  memset(Evt, 0, sizeof(SsdpEvent));
667
0
  unique_service_name(cmd, Evt);
668
0
  Evt->ErrCode = NO_ERROR_FOUND;
669
0
  if ((Evt->RequestType = ssdp_request_type1(cmd)) == SSDP_SERROR) {
670
0
    Evt->ErrCode = E_HTTP_SYNTEX;
671
0
    return -1;
672
0
  }
673
0
  return 0;
674
0
}
675
676
/*!
677
 * \brief Frees the ssdp request.
678
 */
679
static void free_ssdp_event_handler_data(
680
  /*! [in] ssdp_thread_data structure. This structure contains SSDP
681
   * request message. */
682
  void *the_data)
683
0
{
684
0
  ssdp_thread_data *data = (ssdp_thread_data *)the_data;
685
686
0
  if (data != NULL) {
687
0
    http_message_t *hmsg = &data->parser.msg;
688
    /* free data */
689
0
    httpmsg_destroy(hmsg);
690
0
    free(data);
691
0
  }
692
0
}
693
694
/*!
695
 * \brief Does some quick checking of the ssdp msg.
696
 *
697
 * \return 1 if msg is valid, else 0.
698
 */
699
static UPNP_INLINE int valid_ssdp_msg(
700
  /*! [in] ssdp_thread_data structure. This structure contains SSDP
701
   * request message. */
702
  http_message_t *hmsg)
703
0
{
704
0
  memptr hdr_value;
705
706
  /* check for valid methods - NOTIFY or M-SEARCH */
707
0
  if (hmsg->method != (http_method_t)HTTPMETHOD_NOTIFY &&
708
0
    hmsg->method != (http_method_t)HTTPMETHOD_MSEARCH &&
709
0
    hmsg->request_method != (http_method_t)HTTPMETHOD_MSEARCH) {
710
0
    return 0;
711
0
  }
712
0
  if (hmsg->request_method != (http_method_t)HTTPMETHOD_MSEARCH) {
713
    /* check PATH == "*" */
714
0
    if (hmsg->uri.type != (enum uriType)RELATIVE ||
715
0
      strncmp("*",
716
0
        hmsg->uri.pathquery.buff,
717
0
        hmsg->uri.pathquery.size) != 0) {
718
0
      return 0;
719
0
    }
720
    /* check HOST header */
721
0
    if (httpmsg_find_hdr(hmsg, HDR_HOST, &hdr_value) == NULL ||
722
0
      (memptr_cmp(&hdr_value, "239.255.255.250:1900") != 0 &&
723
0
        memptr_cmp(&hdr_value, "[FF02::C]:1900") != 0 &&
724
0
        memptr_cmp(&hdr_value, "[ff02::c]:1900") != 0 &&
725
0
        memptr_cmp(&hdr_value, "[FF05::C]:1900") != 0 &&
726
0
        memptr_cmp(&hdr_value, "[ff05::c]:1900") !=
727
0
          0)) {
728
0
      UpnpPrintf(UPNP_INFO,
729
0
        SSDP,
730
0
        __FILE__,
731
0
        __LINE__,
732
0
        "Invalid HOST header from SSDP message\n");
733
734
0
      return 0;
735
0
    }
736
0
  }
737
738
  /* passed quick check */
739
0
  return 1;
740
0
}
741
742
/*!
743
 * \brief Parses the message and dispatches it to a handler which handles the
744
 * ssdp request msg.
745
 *
746
 * \return 0 if successful, -1 if error.
747
 */
748
static UPNP_INLINE int start_event_handler(
749
  /*! [in] ssdp_thread_data structure. This structure contains SSDP
750
   * request message. */
751
  void *Data)
752
0
{
753
0
  http_parser_t *parser = NULL;
754
0
  parse_status_t status;
755
0
  ssdp_thread_data *data = (ssdp_thread_data *)Data;
756
757
0
  parser = &data->parser;
758
0
  status = parser_parse(parser);
759
0
  if (status == (parse_status_t)PARSE_FAILURE) {
760
0
    if (parser->msg.method != (http_method_t)HTTPMETHOD_NOTIFY ||
761
0
      !parser->valid_ssdp_notify_hack) {
762
0
      UpnpPrintf(UPNP_INFO,
763
0
        SSDP,
764
0
        __FILE__,
765
0
        __LINE__,
766
0
        "SSDP recvd bad msg code = %u\n",
767
0
        status);
768
      /* ignore bad msg, or not enuf mem */
769
0
      goto error_handler;
770
0
    }
771
    /* valid notify msg */
772
0
  } else if (status != (parse_status_t)PARSE_SUCCESS) {
773
0
    UpnpPrintf(UPNP_INFO,
774
0
      SSDP,
775
0
      __FILE__,
776
0
      __LINE__,
777
0
      "SSDP recvd bad msg code = %u\n",
778
0
      status);
779
780
0
    goto error_handler;
781
0
  }
782
  /* check msg */
783
0
  if (valid_ssdp_msg(&parser->msg) != 1) {
784
0
    goto error_handler;
785
0
  }
786
  /* done; thread will free 'data' */
787
0
  return 0;
788
789
0
error_handler:
790
0
  free_ssdp_event_handler_data(data);
791
0
  return -1;
792
0
}
793
794
/*!
795
 * \brief This function is a thread that handles SSDP requests.
796
 */
797
static void ssdp_event_handler_thread(
798
  /*! [] ssdp_thread_data structure. This structure contains SSDP
799
   * request message. */
800
  void *the_data)
801
0
{
802
0
  ssdp_thread_data *data = (ssdp_thread_data *)the_data;
803
0
  http_message_t *hmsg = &data->parser.msg;
804
805
0
  if (start_event_handler(the_data) != 0)
806
0
    return;
807
  /* send msg to device or ctrlpt */
808
0
  if (hmsg->method == (http_method_t)HTTPMETHOD_NOTIFY ||
809
0
    hmsg->request_method == (http_method_t)HTTPMETHOD_MSEARCH) {
810
0
  #ifdef INCLUDE_CLIENT_APIS
811
0
    ssdp_handle_ctrlpt_msg(hmsg, &data->dest_addr, 0);
812
0
  #endif /* INCLUDE_CLIENT_APIS */
813
0
  } else {
814
0
    ssdp_handle_device_request(hmsg, &data->dest_addr);
815
0
  }
816
817
  /* free data */
818
0
  free_ssdp_event_handler_data(data);
819
0
}
820
821
int readFromSSDPSocket(SOCKET socket)
822
0
{
823
0
  char *requestBuf = NULL;
824
0
  char staticBuf[BUFSIZE];
825
0
  struct sockaddr_storage __ss;
826
0
  ThreadPoolJob job;
827
0
  ssdp_thread_data *data = NULL;
828
0
  socklen_t socklen = sizeof(__ss);
829
0
  ssize_t byteReceived = 0;
830
0
  char ntop_buf[INET6_ADDRSTRLEN];
831
832
0
  memset(&job, 0, sizeof(job));
833
834
0
  requestBuf = staticBuf;
835
  /* in case memory can't be allocated, still drain the socket using a
836
   * static buffer. */
837
0
  data = malloc(sizeof(ssdp_thread_data));
838
0
  if (data) {
839
    /* initialize parser */
840
0
  #ifdef INCLUDE_CLIENT_APIS
841
0
    if (socket == gSsdpReqSocket4
842
0
    #ifdef UPNP_ENABLE_IPV6
843
0
      || socket == gSsdpReqSocket6
844
0
    #endif /* UPNP_ENABLE_IPV6 */
845
0
    )
846
0
      parser_response_init(&data->parser, HTTPMETHOD_MSEARCH);
847
0
    else
848
0
      parser_request_init(&data->parser);
849
  #else  /* INCLUDE_CLIENT_APIS */
850
    parser_request_init(&data->parser);
851
  #endif /* INCLUDE_CLIENT_APIS */
852
    /* set size of parser buffer */
853
0
    if (membuffer_set_size(&data->parser.msg.msg, BUFSIZE) == 0)
854
      /* use this as the buffer for recv */
855
0
      requestBuf = data->parser.msg.msg.buf;
856
0
    else {
857
0
      free(data);
858
0
      data = NULL;
859
0
    }
860
0
  }
861
0
  byteReceived = recvfrom(socket,
862
0
    requestBuf,
863
0
    BUFSIZE - (size_t)1,
864
0
    0,
865
0
    (struct sockaddr *)&__ss,
866
0
    &socklen);
867
0
  if (byteReceived > 0) {
868
0
    requestBuf[byteReceived] = '\0';
869
0
    switch (__ss.ss_family) {
870
0
    case AF_INET:
871
0
      inet_ntop(AF_INET,
872
0
        &((struct sockaddr_in *)&__ss)->sin_addr,
873
0
        ntop_buf,
874
0
        sizeof(ntop_buf));
875
0
      break;
876
0
  #ifdef UPNP_ENABLE_IPV6
877
0
    case AF_INET6:
878
0
      inet_ntop(AF_INET6,
879
0
        &((struct sockaddr_in6 *)&__ss)->sin6_addr,
880
0
        ntop_buf,
881
0
        sizeof(ntop_buf));
882
0
      break;
883
0
  #endif /* UPNP_ENABLE_IPV6 */
884
0
    default:
885
0
      memset(ntop_buf, 0, sizeof(ntop_buf));
886
0
      strncpy(ntop_buf,
887
0
        "<Invalid address family>",
888
0
        sizeof(ntop_buf) - 1);
889
0
    }
890
    /* clang-format off */
891
0
    UpnpPrintf(UPNP_INFO, SSDP, __FILE__, __LINE__,
892
0
         "Start of received response ----------------------------------------------------\n"
893
0
         "%s\n"
894
0
         "End of received response ------------------------------------------------------\n"
895
0
         "From host %s\n", requestBuf, ntop_buf);
896
    /* clang-format on */
897
    /* add thread pool job to handle request */
898
0
    if (data != NULL) {
899
0
      data->parser.msg.msg.length += (size_t)byteReceived;
900
      /* null-terminate */
901
0
      data->parser.msg.msg.buf[byteReceived] = 0;
902
0
      memcpy(&data->dest_addr, &__ss, sizeof(__ss));
903
0
      TPJobInit(&job, ssdp_event_handler_thread, data);
904
0
      TPJobSetFreeFunction(
905
0
        &job, free_ssdp_event_handler_data);
906
0
      TPJobSetPriority(&job, MED_PRIORITY);
907
0
      if (ThreadPoolAdd(&gRecvThreadPool, &job, NULL) != 0)
908
0
        free_ssdp_event_handler_data(data);
909
0
    }
910
0
    return 0;
911
0
  }
912
0
  free_ssdp_event_handler_data(data);
913
914
0
  return (byteReceived < 0) ? -1 : 0;
915
0
}
916
917
/*!
918
 * \brief
919
 */
920
static int create_ssdp_sock_v4(
921
  /*! [] SSDP IPv4 socket to be created. */
922
  SOCKET *ssdpSock)
923
0
{
924
0
  char errorBuffer[ERROR_BUFFER_LEN];
925
0
  int onOff;
926
0
  u_char ttl = (u_char)4;
927
0
  struct ip_mreq ssdpMcastAddr;
928
0
  struct sockaddr_storage __ss;
929
0
  struct sockaddr_in *ssdpAddr4 = (struct sockaddr_in *)&__ss;
930
0
  int ret = 0;
931
0
  struct in_addr addr;
932
933
0
  *ssdpSock = socket(AF_INET, SOCK_DGRAM, 0);
934
0
  if (*ssdpSock == INVALID_SOCKET) {
935
0
    strerror_r(errno, errorBuffer, ERROR_BUFFER_LEN);
936
0
    UpnpPrintf(UPNP_CRITICAL,
937
0
      SSDP,
938
0
      __FILE__,
939
0
      __LINE__,
940
0
      "Error in socket(): %s\n",
941
0
      errorBuffer);
942
943
0
    return UPNP_E_OUTOF_SOCKET;
944
0
  }
945
0
  onOff = 1;
946
0
  ret = setsockopt(*ssdpSock,
947
0
    SOL_SOCKET,
948
0
    SO_REUSEADDR,
949
0
    (OPTION_VALUE_CAST)&onOff,
950
0
    sizeof(onOff));
951
0
  if (ret == -1) {
952
0
    strerror_r(errno, errorBuffer, ERROR_BUFFER_LEN);
953
0
    UpnpPrintf(UPNP_CRITICAL,
954
0
      SSDP,
955
0
      __FILE__,
956
0
      __LINE__,
957
0
      "Error in setsockopt() SO_REUSEADDR: %s\n",
958
0
      errorBuffer);
959
0
    ret = UPNP_E_SOCKET_ERROR;
960
0
    goto error_handler;
961
0
  }
962
  #if (defined(BSD) && !defined(__GNU__)) || defined(__APPLE__)
963
  onOff = 1;
964
  ret = setsockopt(*ssdpSock,
965
    SOL_SOCKET,
966
    SO_REUSEPORT,
967
    (OPTION_VALUE_CAST)&onOff,
968
    sizeof(onOff));
969
  if (ret == -1) {
970
    strerror_r(errno, errorBuffer, ERROR_BUFFER_LEN);
971
    UpnpPrintf(UPNP_CRITICAL,
972
      SSDP,
973
      __FILE__,
974
      __LINE__,
975
      "Error in setsockopt() SO_REUSEPORT: %s\n",
976
      errorBuffer);
977
    ret = UPNP_E_SOCKET_ERROR;
978
    goto error_handler;
979
  }
980
  #endif /* BSD, __APPLE__ */
981
0
  memset(&__ss, 0, sizeof(__ss));
982
0
  ssdpAddr4->sin_family = (sa_family_t)AF_INET;
983
0
  ssdpAddr4->sin_addr.s_addr = htonl(INADDR_ANY);
984
0
  ssdpAddr4->sin_port = htons(SSDP_PORT);
985
0
  ret = bind(*ssdpSock, (struct sockaddr *)ssdpAddr4, sizeof(*ssdpAddr4));
986
0
  if (ret == -1) {
987
0
    strerror_r(errno, errorBuffer, ERROR_BUFFER_LEN);
988
0
    UpnpPrintf(UPNP_CRITICAL,
989
0
      SSDP,
990
0
      __FILE__,
991
0
      __LINE__,
992
0
      "Error in bind(), addr=0x%08X, port=%d: %s\n",
993
0
      INADDR_ANY,
994
0
      SSDP_PORT,
995
0
      errorBuffer);
996
0
    ret = UPNP_E_SOCKET_BIND;
997
0
    goto error_handler;
998
0
  }
999
  /*
1000
   * See: https://man7.org/linux/man-pages/man7/ip.7.html
1001
   * Socket options, IP_ADD_MEMBERSHIP
1002
   *
1003
   * This memset actually sets imr_address to INADDR_ANY and
1004
   * imr_ifindex to zero, which make the system choose the appropriate
1005
   * interface.
1006
   *
1007
   * Still using "struct ip_mreq" instead of "struct ip_mreqn" because
1008
   * windows does not recognize the latter.
1009
   */
1010
0
  memset((void *)&ssdpMcastAddr, 0, sizeof ssdpMcastAddr);
1011
0
  inet_pton(AF_INET, gIF_IPV4, &ssdpMcastAddr.imr_interface);
1012
0
  inet_pton(AF_INET, SSDP_IP, &ssdpMcastAddr.imr_multiaddr);
1013
0
  ret = setsockopt(*ssdpSock,
1014
0
    IPPROTO_IP,
1015
0
    IP_ADD_MEMBERSHIP,
1016
0
    (OPTION_VALUE_CAST)&ssdpMcastAddr,
1017
0
    sizeof(struct ip_mreq));
1018
0
  if (ret == -1) {
1019
0
    strerror_r(errno, errorBuffer, ERROR_BUFFER_LEN);
1020
0
    UpnpPrintf(UPNP_CRITICAL,
1021
0
      SSDP,
1022
0
      __FILE__,
1023
0
      __LINE__,
1024
0
      "Error in setsockopt() IP_ADD_MEMBERSHIP (join "
1025
0
      "multicast group): %s\n",
1026
0
      errorBuffer);
1027
0
    ret = UPNP_E_SOCKET_ERROR;
1028
0
    goto error_handler;
1029
0
  }
1030
  /* Set multicast interface. */
1031
0
  memset((void *)&addr, 0, sizeof(struct in_addr));
1032
0
  inet_pton(AF_INET, gIF_IPV4, &addr);
1033
0
  ret = setsockopt(*ssdpSock,
1034
0
    IPPROTO_IP,
1035
0
    IP_MULTICAST_IF,
1036
0
    (OPTION_VALUE_CAST)&addr,
1037
0
    sizeof addr);
1038
0
  if (ret == -1) {
1039
0
    strerror_r(errno, errorBuffer, ERROR_BUFFER_LEN);
1040
0
    UpnpPrintf(UPNP_INFO,
1041
0
      SSDP,
1042
0
      __FILE__,
1043
0
      __LINE__,
1044
0
      "Error in setsockopt() IP_MULTICAST_IF (set multicast "
1045
0
      "interface): %s\n",
1046
0
      errorBuffer);
1047
    /* This is probably not a critical error, so let's continue. */
1048
0
  }
1049
  /* result is not checked becuase it will fail in WinMe and Win9x. */
1050
0
  setsockopt(*ssdpSock,
1051
0
    IPPROTO_IP,
1052
0
    IP_MULTICAST_TTL,
1053
0
    (OPTION_VALUE_CAST)&ttl,
1054
0
    sizeof(ttl));
1055
0
  onOff = 1;
1056
0
  ret = setsockopt(*ssdpSock,
1057
0
    SOL_SOCKET,
1058
0
    SO_BROADCAST,
1059
0
    (OPTION_VALUE_CAST)&onOff,
1060
0
    sizeof(onOff));
1061
0
  if (ret == -1) {
1062
0
    strerror_r(errno, errorBuffer, ERROR_BUFFER_LEN);
1063
0
    UpnpPrintf(UPNP_CRITICAL,
1064
0
      SSDP,
1065
0
      __FILE__,
1066
0
      __LINE__,
1067
0
      "Error in setsockopt() SO_BROADCAST (set broadcast): "
1068
0
      "%s\n",
1069
0
      errorBuffer);
1070
0
    ret = UPNP_E_NETWORK_ERROR;
1071
0
    goto error_handler;
1072
0
  }
1073
0
  ret = UPNP_E_SUCCESS;
1074
1075
0
error_handler:
1076
0
  if (ret != UPNP_E_SUCCESS) {
1077
0
    UpnpCloseSocket(*ssdpSock);
1078
0
  }
1079
1080
0
  return ret;
1081
0
}
1082
1083
  #ifdef INCLUDE_CLIENT_APIS
1084
/*!
1085
 * \brief Creates the SSDP IPv4 socket to be used by the control point.
1086
 *
1087
 * \return UPNP_E_SUCCESS on successful socket creation.
1088
 */
1089
static int create_ssdp_sock_reqv4(
1090
  /*! [out] SSDP IPv4 request socket to be created. */
1091
  SOCKET *ssdpReqSock)
1092
0
{
1093
0
  char errorBuffer[ERROR_BUFFER_LEN];
1094
0
  u_char ttl = 4;
1095
1096
0
  *ssdpReqSock = socket(AF_INET, SOCK_DGRAM, 0);
1097
0
  if (*ssdpReqSock == INVALID_SOCKET) {
1098
0
    strerror_r(errno, errorBuffer, ERROR_BUFFER_LEN);
1099
0
    UpnpPrintf(UPNP_CRITICAL,
1100
0
      SSDP,
1101
0
      __FILE__,
1102
0
      __LINE__,
1103
0
      "Error in socket(): %s\n",
1104
0
      errorBuffer);
1105
0
    return UPNP_E_OUTOF_SOCKET;
1106
0
  }
1107
0
  setsockopt(*ssdpReqSock,
1108
0
    IPPROTO_IP,
1109
0
    IP_MULTICAST_TTL,
1110
0
    (OPTION_VALUE_CAST)&ttl,
1111
0
    sizeof(ttl));
1112
  /* just do it, regardless if fails or not. */
1113
0
  sock_make_no_blocking(*ssdpReqSock);
1114
1115
0
  return UPNP_E_SUCCESS;
1116
0
}
1117
  #endif /* INCLUDE_CLIENT_APIS */
1118
1119
  #ifdef UPNP_ENABLE_IPV6
1120
/*!
1121
 * \brief This function ...
1122
 */
1123
static int create_ssdp_sock_v6(
1124
  /* [] SSDP IPv6 socket to be created. */
1125
  SOCKET *ssdpSock)
1126
0
{
1127
0
  char errorBuffer[ERROR_BUFFER_LEN];
1128
0
  struct ipv6_mreq ssdpMcastAddr;
1129
0
  struct sockaddr_storage __ss;
1130
0
  struct sockaddr_in6 *ssdpAddr6 = (struct sockaddr_in6 *)&__ss;
1131
0
  int onOff;
1132
0
  int ret = 0;
1133
1134
0
  *ssdpSock = socket(AF_INET6, SOCK_DGRAM, 0);
1135
0
  if (*ssdpSock == INVALID_SOCKET) {
1136
0
    strerror_r(errno, errorBuffer, ERROR_BUFFER_LEN);
1137
0
    UpnpPrintf(UPNP_CRITICAL,
1138
0
      SSDP,
1139
0
      __FILE__,
1140
0
      __LINE__,
1141
0
      "Error in socket(): %s\n",
1142
0
      errorBuffer);
1143
1144
0
    return UPNP_E_OUTOF_SOCKET;
1145
0
  }
1146
0
  onOff = 1;
1147
0
  ret = setsockopt(*ssdpSock,
1148
0
    SOL_SOCKET,
1149
0
    SO_REUSEADDR,
1150
0
    (OPTION_VALUE_CAST)&onOff,
1151
0
    sizeof(onOff));
1152
0
  if (ret == -1) {
1153
0
    strerror_r(errno, errorBuffer, ERROR_BUFFER_LEN);
1154
0
    UpnpPrintf(UPNP_CRITICAL,
1155
0
      SSDP,
1156
0
      __FILE__,
1157
0
      __LINE__,
1158
0
      "Error in setsockopt() SO_REUSEADDR: %s\n",
1159
0
      errorBuffer);
1160
0
    ret = UPNP_E_SOCKET_ERROR;
1161
0
    goto error_handler;
1162
0
  }
1163
    #if (defined(BSD) && !defined(__GNU__)) || defined(__APPLE__)
1164
  onOff = 1;
1165
  ret = setsockopt(*ssdpSock,
1166
    SOL_SOCKET,
1167
    SO_REUSEPORT,
1168
    (OPTION_VALUE_CAST)&onOff,
1169
    sizeof(onOff));
1170
  if (ret == -1) {
1171
    strerror_r(errno, errorBuffer, ERROR_BUFFER_LEN);
1172
    UpnpPrintf(UPNP_CRITICAL,
1173
      SSDP,
1174
      __FILE__,
1175
      __LINE__,
1176
      "Error in setsockopt() SO_REUSEPORT: %s\n",
1177
      errorBuffer);
1178
    ret = UPNP_E_SOCKET_ERROR;
1179
    goto error_handler;
1180
  }
1181
    #endif /* BSD, __APPLE__ */
1182
0
  onOff = 1;
1183
0
  ret = setsockopt(*ssdpSock,
1184
0
    IPPROTO_IPV6,
1185
0
    IPV6_V6ONLY,
1186
0
    (OPTION_VALUE_CAST)&onOff,
1187
0
    sizeof(onOff));
1188
0
  if (ret == -1) {
1189
0
    strerror_r(errno, errorBuffer, ERROR_BUFFER_LEN);
1190
0
    UpnpPrintf(UPNP_CRITICAL,
1191
0
      SSDP,
1192
0
      __FILE__,
1193
0
      __LINE__,
1194
0
      "Error in setsockopt() IPV6_V6ONLY: %s\n",
1195
0
      errorBuffer);
1196
0
    ret = UPNP_E_SOCKET_ERROR;
1197
0
    goto error_handler;
1198
0
  }
1199
0
  memset(&__ss, 0, sizeof(__ss));
1200
0
  ssdpAddr6->sin6_family = (sa_family_t)AF_INET6;
1201
0
  ssdpAddr6->sin6_addr = in6addr_any;
1202
0
    #ifndef _WIN32
1203
0
  ssdpAddr6->sin6_scope_id = gIF_INDEX;
1204
0
    #endif
1205
0
  ssdpAddr6->sin6_port = htons(SSDP_PORT);
1206
0
  ret = bind(*ssdpSock, (struct sockaddr *)ssdpAddr6, sizeof(*ssdpAddr6));
1207
0
  if (ret == -1) {
1208
0
    #ifndef _WIN32
1209
0
    strerror_r(errno, errorBuffer, ERROR_BUFFER_LEN);
1210
0
    UpnpPrintf(UPNP_CRITICAL,
1211
0
      SSDP,
1212
0
      __FILE__,
1213
0
      __LINE__,
1214
0
      "Error in bind(), addr=%s, index=%u, port=%d: %s\n",
1215
0
      gIF_IPV6,
1216
0
      gIF_INDEX,
1217
0
      SSDP_PORT,
1218
0
      errorBuffer);
1219
0
    ret = UPNP_E_SOCKET_BIND;
1220
0
    goto error_handler;
1221
    #else
1222
    int wsa_err = WSAGetLastError();
1223
    UpnpPrintf(UPNP_CRITICAL,
1224
      SSDP,
1225
      __FILE__,
1226
      __LINE__,
1227
      "Error in bind(), addr=%s, index=%u, port=%d: %d\n",
1228
      gIF_IPV6,
1229
      gIF_INDEX,
1230
      SSDP_PORT,
1231
      wsa_err);
1232
    ret = UPNP_E_SOCKET_BIND;
1233
    goto error_handler;
1234
    #endif
1235
0
  }
1236
0
  memset((void *)&ssdpMcastAddr, 0, sizeof(ssdpMcastAddr));
1237
0
  ssdpMcastAddr.ipv6mr_interface = gIF_INDEX;
1238
0
  inet_pton(
1239
0
    AF_INET6, SSDP_IPV6_LINKLOCAL, &ssdpMcastAddr.ipv6mr_multiaddr);
1240
0
  ret = setsockopt(*ssdpSock,
1241
0
    IPPROTO_IPV6,
1242
0
    IPV6_JOIN_GROUP,
1243
0
    (OPTION_VALUE_CAST)&ssdpMcastAddr,
1244
0
    sizeof(ssdpMcastAddr));
1245
0
  if (ret == -1) {
1246
0
    uint32_t *p = (uint32_t *)&ssdpMcastAddr.ipv6mr_multiaddr;
1247
0
    strerror_r(errno, errorBuffer, ERROR_BUFFER_LEN);
1248
0
    UpnpPrintf(UPNP_CRITICAL,
1249
0
      SSDP,
1250
0
      __FILE__,
1251
0
      __LINE__,
1252
0
      "Error in setsockopt() IPV6_JOIN_GROUP (join multicast "
1253
0
      "group): %s.\n"
1254
0
      "SSDP_IPV6_LINKLOCAL = %s,\n"
1255
0
      "ipv6mr_interface = %u,\n"
1256
0
      "ipv6mr_multiaddr[0,1,2,3] = "
1257
0
      "0x%08X:0x%08X:0x%08X:0x%08X\n"
1258
0
      "gIF_NAME = %s\n",
1259
0
      errorBuffer,
1260
0
      SSDP_IPV6_LINKLOCAL,
1261
0
      ssdpMcastAddr.ipv6mr_interface,
1262
0
      p[0],
1263
0
      p[1],
1264
0
      p[2],
1265
0
      p[3],
1266
0
      gIF_NAME);
1267
0
    ret = UPNP_E_SOCKET_ERROR;
1268
0
    goto error_handler;
1269
0
  }
1270
0
  onOff = 1;
1271
0
  ret = setsockopt(*ssdpSock,
1272
0
    SOL_SOCKET,
1273
0
    SO_BROADCAST,
1274
0
    (OPTION_VALUE_CAST)&onOff,
1275
0
    sizeof(onOff));
1276
0
  if (ret == -1) {
1277
0
    strerror_r(errno, errorBuffer, ERROR_BUFFER_LEN);
1278
0
    UpnpPrintf(UPNP_CRITICAL,
1279
0
      SSDP,
1280
0
      __FILE__,
1281
0
      __LINE__,
1282
0
      "Error in setsockopt() SO_BROADCAST (set broadcast): "
1283
0
      "%s\n",
1284
0
      errorBuffer);
1285
0
    ret = UPNP_E_NETWORK_ERROR;
1286
0
    goto error_handler;
1287
0
  }
1288
0
  ret = UPNP_E_SUCCESS;
1289
1290
0
error_handler:
1291
0
  if (ret != UPNP_E_SUCCESS) {
1292
0
    UpnpCloseSocket(*ssdpSock);
1293
0
  }
1294
1295
0
  return ret;
1296
0
}
1297
  #endif /* IPv6 */
1298
1299
  #ifdef UPNP_ENABLE_IPV6
1300
/*!
1301
 * \brief This function ...
1302
 */
1303
static int create_ssdp_sock_v6_ula_gua(
1304
  /*! [] SSDP IPv6 socket to be created. */
1305
  SOCKET *ssdpSock)
1306
0
{
1307
0
  char errorBuffer[ERROR_BUFFER_LEN];
1308
0
  struct ipv6_mreq ssdpMcastAddr;
1309
0
  struct sockaddr_storage __ss;
1310
0
  struct sockaddr_in6 *ssdpAddr6 = (struct sockaddr_in6 *)&__ss;
1311
0
  int onOff;
1312
0
  int ret = 0;
1313
1314
0
  *ssdpSock = socket(AF_INET6, SOCK_DGRAM, 0);
1315
0
  if (*ssdpSock == INVALID_SOCKET) {
1316
0
    strerror_r(errno, errorBuffer, ERROR_BUFFER_LEN);
1317
0
    UpnpPrintf(UPNP_CRITICAL,
1318
0
      SSDP,
1319
0
      __FILE__,
1320
0
      __LINE__,
1321
0
      "Error in socket(): %s\n",
1322
0
      errorBuffer);
1323
1324
0
    return UPNP_E_OUTOF_SOCKET;
1325
0
  }
1326
0
  onOff = 1;
1327
0
  ret = setsockopt(*ssdpSock,
1328
0
    SOL_SOCKET,
1329
0
    SO_REUSEADDR,
1330
0
    (OPTION_VALUE_CAST)&onOff,
1331
0
    sizeof(onOff));
1332
0
  if (ret == -1) {
1333
0
    strerror_r(errno, errorBuffer, ERROR_BUFFER_LEN);
1334
0
    UpnpPrintf(UPNP_CRITICAL,
1335
0
      SSDP,
1336
0
      __FILE__,
1337
0
      __LINE__,
1338
0
      "Error in setsockopt() SO_REUSEADDR: %s\n",
1339
0
      errorBuffer);
1340
0
    ret = UPNP_E_SOCKET_ERROR;
1341
0
    goto error_handler;
1342
0
  }
1343
    #if (defined(BSD) && !defined(__GNU__)) || defined(__APPLE__)
1344
  onOff = 1;
1345
  ret = setsockopt(*ssdpSock,
1346
    SOL_SOCKET,
1347
    SO_REUSEPORT,
1348
    (OPTION_VALUE_CAST)&onOff,
1349
    sizeof(onOff));
1350
  if (ret == -1) {
1351
    strerror_r(errno, errorBuffer, ERROR_BUFFER_LEN);
1352
    UpnpPrintf(UPNP_CRITICAL,
1353
      SSDP,
1354
      __FILE__,
1355
      __LINE__,
1356
      "Error in setsockopt() SO_REUSEPORT: %s\n",
1357
      errorBuffer);
1358
    ret = UPNP_E_SOCKET_ERROR;
1359
    goto error_handler;
1360
  }
1361
    #endif /* BSD, __APPLE__ */
1362
0
  onOff = 1;
1363
0
  ret = setsockopt(*ssdpSock,
1364
0
    IPPROTO_IPV6,
1365
0
    IPV6_V6ONLY,
1366
0
    (OPTION_VALUE_CAST)&onOff,
1367
0
    sizeof(onOff));
1368
0
  if (ret == -1) {
1369
0
    strerror_r(errno, errorBuffer, ERROR_BUFFER_LEN);
1370
0
    UpnpPrintf(UPNP_CRITICAL,
1371
0
      SSDP,
1372
0
      __FILE__,
1373
0
      __LINE__,
1374
0
      "Error in setsockopt() IPV6_V6ONLY: %s\n",
1375
0
      errorBuffer);
1376
0
    ret = UPNP_E_SOCKET_ERROR;
1377
0
    goto error_handler;
1378
0
  }
1379
0
  memset(&__ss, 0, sizeof(__ss));
1380
0
  ssdpAddr6->sin6_family = (sa_family_t)AF_INET6;
1381
0
  ssdpAddr6->sin6_addr = in6addr_any;
1382
0
  ssdpAddr6->sin6_scope_id = gIF_INDEX;
1383
0
  ssdpAddr6->sin6_port = htons(SSDP_PORT);
1384
0
  ret = bind(*ssdpSock, (struct sockaddr *)ssdpAddr6, sizeof(*ssdpAddr6));
1385
0
  if (ret == -1) {
1386
0
    strerror_r(errno, errorBuffer, ERROR_BUFFER_LEN);
1387
0
    UpnpPrintf(UPNP_CRITICAL,
1388
0
      SSDP,
1389
0
      __FILE__,
1390
0
      __LINE__,
1391
0
      "Error in bind(), addr=0x%032lX, port=%d: %s\n",
1392
0
      0lu,
1393
0
      SSDP_PORT,
1394
0
      errorBuffer);
1395
0
    ret = UPNP_E_SOCKET_BIND;
1396
0
    goto error_handler;
1397
0
  }
1398
0
  memset((void *)&ssdpMcastAddr, 0, sizeof(ssdpMcastAddr));
1399
0
  ssdpMcastAddr.ipv6mr_interface = gIF_INDEX;
1400
  /* SITE LOCAL */
1401
0
  inet_pton(
1402
0
    AF_INET6, SSDP_IPV6_SITELOCAL, &ssdpMcastAddr.ipv6mr_multiaddr);
1403
0
  ret = setsockopt(*ssdpSock,
1404
0
    IPPROTO_IPV6,
1405
0
    IPV6_JOIN_GROUP,
1406
0
    (OPTION_VALUE_CAST)&ssdpMcastAddr,
1407
0
    sizeof(ssdpMcastAddr));
1408
0
  if (ret == -1) {
1409
0
    strerror_r(errno, errorBuffer, ERROR_BUFFER_LEN);
1410
0
    UpnpPrintf(UPNP_CRITICAL,
1411
0
      SSDP,
1412
0
      __FILE__,
1413
0
      __LINE__,
1414
0
      "Error in setsockopt() IPV6_JOIN_GROUP (join multicast "
1415
0
      "group): %s\n",
1416
0
      errorBuffer);
1417
0
    ret = UPNP_E_SOCKET_ERROR;
1418
0
    goto error_handler;
1419
0
  }
1420
0
  onOff = 1;
1421
0
  ret = setsockopt(*ssdpSock,
1422
0
    SOL_SOCKET,
1423
0
    SO_BROADCAST,
1424
0
    (OPTION_VALUE_CAST)&onOff,
1425
0
    sizeof(onOff));
1426
0
  if (ret == -1) {
1427
0
    strerror_r(errno, errorBuffer, ERROR_BUFFER_LEN);
1428
0
    UpnpPrintf(UPNP_CRITICAL,
1429
0
      SSDP,
1430
0
      __FILE__,
1431
0
      __LINE__,
1432
0
      "Error in setsockopt() SO_BROADCAST (set broadcast): "
1433
0
      "%s\n",
1434
0
      errorBuffer);
1435
0
    ret = UPNP_E_NETWORK_ERROR;
1436
0
    goto error_handler;
1437
0
  }
1438
0
  ret = UPNP_E_SUCCESS;
1439
1440
0
error_handler:
1441
0
  if (ret != UPNP_E_SUCCESS) {
1442
0
    UpnpCloseSocket(*ssdpSock);
1443
0
  }
1444
1445
0
  return ret;
1446
0
}
1447
  #endif /* IPv6 */
1448
1449
  #ifdef INCLUDE_CLIENT_APIS
1450
    #ifdef UPNP_ENABLE_IPV6
1451
/*!
1452
 * \brief Creates the SSDP IPv6 socket to be used by the control
1453
 * point.
1454
 */
1455
static int create_ssdp_sock_reqv6(
1456
  /* [out] SSDP IPv6 request socket to be created. */
1457
  SOCKET *ssdpReqSock)
1458
0
{
1459
0
  char errorBuffer[ERROR_BUFFER_LEN];
1460
0
  char hops = 1;
1461
1462
0
  *ssdpReqSock = socket(AF_INET6, SOCK_DGRAM, 0);
1463
0
  if (*ssdpReqSock == INVALID_SOCKET) {
1464
0
    strerror_r(errno, errorBuffer, ERROR_BUFFER_LEN);
1465
0
    UpnpPrintf(UPNP_CRITICAL,
1466
0
      SSDP,
1467
0
      __FILE__,
1468
0
      __LINE__,
1469
0
      "Error in socket(): %s\n",
1470
0
      errorBuffer);
1471
0
    return UPNP_E_OUTOF_SOCKET;
1472
0
  }
1473
  /* MUST use scoping of IPv6 addresses to control the propagation os SSDP
1474
   * messages instead of relying on the Hop Limit (Equivalent to the TTL
1475
   * limit in IPv4). */
1476
0
  setsockopt(*ssdpReqSock,
1477
0
    IPPROTO_IPV6,
1478
0
    IPV6_MULTICAST_HOPS,
1479
0
    (OPTION_VALUE_CAST)&hops,
1480
0
    sizeof(hops));
1481
  /* just do it, regardless if fails or not. */
1482
0
  sock_make_no_blocking(*ssdpReqSock);
1483
1484
0
  return UPNP_E_SUCCESS;
1485
0
}
1486
    #endif /* IPv6 */
1487
  #endif         /* INCLUDE_CLIENT_APIS */
1488
1489
int get_ssdp_sockets(MiniServerSockArray *out)
1490
0
{
1491
0
  int retVal;
1492
1493
0
  #ifdef INCLUDE_CLIENT_APIS
1494
0
  out->ssdpReqSock4 = INVALID_SOCKET;
1495
0
  out->ssdpReqSock6 = INVALID_SOCKET;
1496
  /* Create the IPv4 socket for SSDP REQUESTS */
1497
0
  if (strlen(gIF_IPV4) > (size_t)0) {
1498
0
    retVal = create_ssdp_sock_reqv4(&out->ssdpReqSock4);
1499
0
    if (retVal != UPNP_E_SUCCESS)
1500
0
      return retVal;
1501
    /* For use by ssdp control point. */
1502
0
    gSsdpReqSocket4 = out->ssdpReqSock4;
1503
0
  } else
1504
0
    out->ssdpReqSock4 = INVALID_SOCKET;
1505
    /* Create the IPv6 socket for SSDP REQUESTS */
1506
0
    #ifdef UPNP_ENABLE_IPV6
1507
0
  if (strlen(gIF_IPV6) > (size_t)0) {
1508
0
    retVal = create_ssdp_sock_reqv6(&out->ssdpReqSock6);
1509
0
    if (retVal != UPNP_E_SUCCESS) {
1510
0
      UpnpCloseSocket(out->ssdpReqSock4);
1511
0
      return retVal;
1512
0
    }
1513
    /* For use by ssdp control point. */
1514
0
    gSsdpReqSocket6 = out->ssdpReqSock6;
1515
0
  } else
1516
0
    out->ssdpReqSock6 = INVALID_SOCKET;
1517
0
    #endif /* IPv6 */
1518
0
  #endif         /* INCLUDE_CLIENT_APIS */
1519
  /* Create the IPv4 socket for SSDP */
1520
0
  if (strlen(gIF_IPV4) > (size_t)0) {
1521
0
    retVal = create_ssdp_sock_v4(&out->ssdpSock4);
1522
0
    if (retVal != UPNP_E_SUCCESS) {
1523
0
  #ifdef INCLUDE_CLIENT_APIS
1524
0
      UpnpCloseSocket(out->ssdpReqSock4);
1525
0
      UpnpCloseSocket(out->ssdpReqSock6);
1526
0
  #endif /* INCLUDE_CLIENT_APIS */
1527
0
      return retVal;
1528
0
    }
1529
0
  } else
1530
0
    out->ssdpSock4 = INVALID_SOCKET;
1531
0
  #ifdef UPNP_ENABLE_IPV6
1532
  /* Create the IPv6 socket for SSDP */
1533
0
  if (strlen(gIF_IPV6) > (size_t)0) {
1534
0
    retVal = create_ssdp_sock_v6(&out->ssdpSock6);
1535
0
    if (retVal != UPNP_E_SUCCESS) {
1536
0
      UpnpCloseSocket(out->ssdpSock4);
1537
0
    #ifdef INCLUDE_CLIENT_APIS
1538
0
      UpnpCloseSocket(out->ssdpReqSock4);
1539
0
      UpnpCloseSocket(out->ssdpReqSock6);
1540
0
    #endif /* INCLUDE_CLIENT_APIS */
1541
0
      return retVal;
1542
0
    }
1543
0
  } else
1544
0
    out->ssdpSock6 = INVALID_SOCKET;
1545
0
  if (strlen(gIF_IPV6_ULA_GUA) > (size_t)0) {
1546
0
    retVal = create_ssdp_sock_v6_ula_gua(&out->ssdpSock6UlaGua);
1547
0
    if (retVal != UPNP_E_SUCCESS) {
1548
0
      UpnpCloseSocket(out->ssdpSock4);
1549
0
      UpnpCloseSocket(out->ssdpSock6);
1550
0
    #ifdef INCLUDE_CLIENT_APIS
1551
0
      UpnpCloseSocket(out->ssdpReqSock4);
1552
0
      UpnpCloseSocket(out->ssdpReqSock6);
1553
0
    #endif /* INCLUDE_CLIENT_APIS */
1554
0
      return retVal;
1555
0
    }
1556
0
  } else
1557
0
    out->ssdpSock6UlaGua = INVALID_SOCKET;
1558
0
  #endif /* UPNP_ENABLE_IPV6 */
1559
1560
0
  return UPNP_E_SUCCESS;
1561
0
}
1562
#endif /* EXCLUDE_SSDP */
1563
1564
/* @} SSDPlib */