WPS: Add support for external Registrars using UPnP transport
[mech_eap.git] / src / wps / wps_upnp_ssdp.c
1 /*
2  * UPnP SSDP for WPS
3  * Copyright (c) 2000-2003 Intel Corporation
4  * Copyright (c) 2006-2007 Sony Corporation
5  * Copyright (c) 2008-2009 Atheros Communications
6  * Copyright (c) 2009, Jouni Malinen <j@w1.fi>
7  *
8  * See wps_upnp.c for more details on licensing and code history.
9  */
10
11 #include "includes.h"
12
13 #include <fcntl.h>
14 #include <sys/ioctl.h>
15 #include <net/route.h>
16
17 #include "common.h"
18 #include "uuid.h"
19 #include "eloop.h"
20 #include "wps.h"
21 #include "wps_upnp.h"
22 #include "wps_upnp_i.h"
23
24 #define UPNP_CACHE_SEC (UPNP_CACHE_SEC_MIN + 1) /* cache time we use */
25 #define UPNP_CACHE_SEC_MIN 1800 /* min cachable time per UPnP standard */
26 #define UPNP_ADVERTISE_REPEAT 2 /* no more than 3 */
27 #define MULTICAST_MAX_READ 1600 /* max bytes we'll read for UPD request */
28 #define MAX_MSEARCH 20          /* max simultaneous M-SEARCH replies ongoing */
29 #define SSDP_TARGET  "239.0.0.0"
30 #define SSDP_NETMASK "255.0.0.0"
31
32
33 /* Check tokens for equality, where tokens consist of letters, digits,
34  * underscore and hyphen, and are matched case insensitive.
35  */
36 static int token_eq(const char *s1, const char *s2)
37 {
38         int c1;
39         int c2;
40         int end1 = 0;
41         int end2 = 0;
42         for (;;) {
43                 c1 = *s1++;
44                 c2 = *s2++;
45                 if (isalpha(c1) && isupper(c1))
46                         c1 = tolower(c1);
47                 if (isalpha(c2) && isupper(c2))
48                         c2 = tolower(c2);
49                 end1 = !(isalnum(c1) || c1 == '_' || c1 == '-');
50                 end2 = !(isalnum(c2) || c2 == '_' || c2 == '-');
51                 if (end1 || end2 || c1 != c2)
52                         break;
53         }
54         return (end1 && end2);  /* reached end of both words? */
55 }
56
57
58 /* Return length of token (see above for definition of token) */
59 static int token_length(const char *s)
60 {
61         const char *begin = s;
62         for (;; s++) {
63                 int c = *s;
64                 int end = !(isalnum(c) || c == '_' || c == '-');
65                 if (end)
66                         break;
67         }
68         return s - begin;
69 }
70
71
72 /* return length of interword separation.
73  * This accepts only spaces/tabs and thus will not traverse a line
74  * or buffer ending.
75  */
76 static int word_separation_length(const char *s)
77 {
78         const char *begin = s;
79         for (;; s++) {
80                 int c = *s;
81                 if (c == ' ' || c == '\t')
82                         continue;
83                 break;
84         }
85         return s - begin;
86 }
87
88
89 /* No. of chars through (including) end of line */
90 static int line_length(const char *l)
91 {
92         const char *lp = l;
93         while (*lp && *lp != '\n')
94                 lp++;
95         if (*lp == '\n')
96                 lp++;
97         return lp - l;
98 }
99
100
101 /* No. of chars excluding trailing whitespace */
102 static int line_length_stripped(const char *l)
103 {
104         const char *lp = l + line_length(l);
105         while (lp > l && !isgraph(lp[-1]))
106                 lp--;
107         return lp - l;
108 }
109
110
111 static int str_starts(const char *str, const char *start)
112 {
113         return os_strncmp(str, start, os_strlen(start)) == 0;
114 }
115
116
117 /***************************************************************************
118  * Advertisements.
119  * These are multicast to the world to tell them we are here.
120  * The individual packets are spread out in time to limit loss,
121  * and then after a much longer period of time the whole sequence
122  * is repeated again (for NOTIFYs only).
123  **************************************************************************/
124
125 /**
126  * next_advertisement - Build next message and advance the state machine
127  * @a: Advertisement state
128  * @islast: Buffer for indicating whether this is the last message (= 1)
129  * Returns: The new message (caller is responsible for freeing this)
130  *
131  * Note: next_advertisement is shared code with msearchreply_* functions
132  */
133 static struct wpabuf *
134 next_advertisement(struct advertisement_state_machine *a, int *islast)
135 {
136         struct wpabuf *msg;
137         char *NTString = "";
138         char uuid_string[80];
139
140         *islast = 0;
141         uuid_bin2str(a->sm->wps->uuid, uuid_string, sizeof(uuid_string));
142         msg = wpabuf_alloc(800); /* more than big enough */
143         if (msg == NULL)
144                 goto fail;
145         switch (a->type) {
146         case ADVERTISE_UP:
147         case ADVERTISE_DOWN:
148                 NTString = "NT";
149                 wpabuf_put_str(msg, "NOTIFY * HTTP/1.1\r\n");
150                 wpabuf_printf(msg, "HOST: %s:%d\r\n",
151                               UPNP_MULTICAST_ADDRESS, UPNP_MULTICAST_PORT);
152                 wpabuf_printf(msg, "CACHE-CONTROL: max-age=%d\r\n",
153                               UPNP_CACHE_SEC);
154                 wpabuf_printf(msg, "NTS: %s\r\n",
155                               (a->type == ADVERTISE_UP ?
156                                "ssdp:alive" : "ssdp:byebye"));
157                 break;
158         case MSEARCH_REPLY:
159                 NTString = "ST";
160                 wpabuf_put_str(msg, "HTTP/1.1 200 OK\r\n");
161                 wpabuf_printf(msg, "CACHE-CONTROL: max-age=%d\r\n",
162                               UPNP_CACHE_SEC);
163
164                 wpabuf_put_str(msg, "DATE: ");
165                 format_date(msg);
166                 wpabuf_put_str(msg, "\r\n");
167
168                 wpabuf_put_str(msg, "EXT:\r\n");
169                 break;
170         }
171
172         if (a->type != ADVERTISE_DOWN) {
173                 /* Where others may get our XML files from */
174                 wpabuf_printf(msg, "LOCATION: http://%s:%d/%s\r\n",
175                               a->sm->ip_addr_text, a->sm->web_port,
176                               UPNP_WPS_DEVICE_XML_FILE);
177         }
178
179         /* The SERVER line has three comma-separated fields:
180          *      operating system / version
181          *      upnp version
182          *      software package / version
183          * However, only the UPnP version is really required, the
184          * others can be place holders... for security reasons
185          * it is better to NOT provide extra information.
186          */
187         wpabuf_put_str(msg, "SERVER: Unspecified, UPnP/1.0, Unspecified\r\n");
188
189         switch (a->state / UPNP_ADVERTISE_REPEAT) {
190         case 0:
191                 wpabuf_printf(msg, "%s: upnp:rootdevice\r\n", NTString);
192                 wpabuf_printf(msg, "USN: uuid:%s::upnp:rootdevice\r\n",
193                               uuid_string);
194                 break;
195         case 1:
196                 wpabuf_printf(msg, "%s: uuid:%s\r\n", NTString, uuid_string);
197                 wpabuf_printf(msg, "USN: uuid:%s\r\n", uuid_string);
198                 break;
199         case 2:
200                 wpabuf_printf(msg, "%s: urn:schemas-wifialliance-org:device:"
201                               "WFADevice:1\r\n", NTString);
202                 wpabuf_printf(msg, "USN: uuid:%s::urn:schemas-wifialliance-"
203                               "org:device:WFADevice:1\r\n", uuid_string);
204                 break;
205         case 3:
206                 wpabuf_printf(msg, "%s: urn:schemas-wifialliance-org:service:"
207                               "WFAWLANConfig:1\r\n", NTString);
208                 wpabuf_printf(msg, "USN: uuid:%s::urn:schemas-wifialliance-"
209                               "org:service:WFAWLANConfig:1\r\n", uuid_string);
210                 break;
211         }
212         wpabuf_put_str(msg, "\r\n");
213
214         if (a->state + 1 >= 4 * UPNP_ADVERTISE_REPEAT)
215                 *islast = 1;
216
217         return msg;
218
219 fail:
220         wpabuf_free(msg);
221         return NULL;
222 }
223
224
225 static void advertisement_state_machine_handler(void *eloop_data,
226                                                 void *user_ctx);
227
228
229 /**
230  * advertisement_state_machine_stop - Stop SSDP advertisements
231  * @sm: WPS UPnP state machine from upnp_wps_device_init()
232  */
233 void advertisement_state_machine_stop(struct upnp_wps_device_sm *sm)
234 {
235         eloop_cancel_timeout(advertisement_state_machine_handler, NULL, sm);
236 }
237
238
239 static void advertisement_state_machine_handler(void *eloop_data,
240                                                 void *user_ctx)
241 {
242         struct upnp_wps_device_sm *sm = user_ctx;
243         struct advertisement_state_machine *a = &sm->advertisement;
244         struct wpabuf *msg;
245         int next_timeout_msec = 100;
246         int next_timeout_sec = 0;
247         struct sockaddr_in dest;
248         int islast = 0;
249
250         /*
251          * Each is sent twice (in case lost) w/ 100 msec delay between;
252          * spec says no more than 3 times.
253          * One pair for rootdevice, one pair for uuid, and a pair each for
254          * each of the two urns.
255          * The entire sequence must be repeated before cache control timeout
256          * (which  is min  1800 seconds),
257          * recommend random portion of half of the advertised cache control age
258          * to ensure against loss... perhaps 1800/4 + rand*1800/4 ?
259          * Delay random interval < 100 msec prior to initial sending.
260          * TTL of 4
261          */
262
263         wpa_printf(MSG_MSGDUMP, "WPS UPnP: Advertisement state=%d", a->state);
264         msg = next_advertisement(a, &islast);
265         if (msg == NULL)
266                 return;
267
268         os_memset(&dest, 0, sizeof(dest));
269         dest.sin_family = AF_INET;
270         dest.sin_addr.s_addr = inet_addr(UPNP_MULTICAST_ADDRESS);
271         dest.sin_port = htons(UPNP_MULTICAST_PORT);
272
273         if (sendto(sm->multicast_sd, wpabuf_head(msg), wpabuf_len(msg), 0,
274                    (struct sockaddr *) &dest, sizeof(dest)) == -1) {
275                 wpa_printf(MSG_ERROR, "WPS UPnP: Advertisement sendto failed:"
276                            "%d (%s)", errno, strerror(errno));
277                 next_timeout_msec = 0;
278                 next_timeout_sec = 10; /* ... later */
279         } else if (islast) {
280                 a->state = 0; /* wrap around */
281                 if (a->type == ADVERTISE_DOWN) {
282                         wpa_printf(MSG_DEBUG, "WPS UPnP: ADVERTISE_DOWN->UP");
283                         a->type = ADVERTISE_UP;
284                         /* do it all over again right away */
285                 } else {
286                         u16 r;
287                         /*
288                          * Start over again after a long timeout
289                          * (see notes above)
290                          */
291                         next_timeout_msec = 0;
292                         os_get_random((void *) &r, sizeof(r));
293                         next_timeout_sec = UPNP_CACHE_SEC / 4 +
294                                 (((UPNP_CACHE_SEC / 4) * r) >> 16);
295                         sm->advertise_count++;
296                         wpa_printf(MSG_DEBUG, "WPS UPnP: ADVERTISE_UP (#%u); "
297                                    "next in %d sec",
298                                    sm->advertise_count, next_timeout_sec);
299                 }
300         } else {
301                 a->state++;
302         }
303
304         wpabuf_free(msg);
305
306         eloop_register_timeout(next_timeout_sec, next_timeout_msec,
307                                advertisement_state_machine_handler, NULL, sm);
308 }
309
310
311 /**
312  * advertisement_state_machine_start - Start SSDP advertisements
313  * @sm: WPS UPnP state machine from upnp_wps_device_init()
314  * Returns: 0 on success, -1 on failure
315  */
316 int advertisement_state_machine_start(struct upnp_wps_device_sm *sm)
317 {
318         struct advertisement_state_machine *a = &sm->advertisement;
319         int next_timeout_msec;
320
321         advertisement_state_machine_stop(sm);
322
323         /*
324          * Start out advertising down, this automatically switches
325          * to advertising up which signals our restart.
326          */
327         a->type = ADVERTISE_DOWN;
328         a->state = 0;
329         a->sm = sm;
330         /* (other fields not used here) */
331
332         /* First timeout should be random interval < 100 msec */
333         next_timeout_msec = (100 * (os_random() & 0xFF)) >> 8;
334         return eloop_register_timeout(0, next_timeout_msec,
335                                       advertisement_state_machine_handler,
336                                       NULL, sm);
337 }
338
339
340 /***************************************************************************
341  * M-SEARCH replies
342  * These are very similar to the multicast advertisements, with some
343  * small changes in data content; and they are sent (UDP) to a specific
344  * unicast address instead of multicast.
345  * They are sent in response to a UDP M-SEARCH packet.
346  **************************************************************************/
347
348 static void msearchreply_state_machine_handler(void *eloop_data,
349                                                void *user_ctx);
350
351
352 /**
353  * msearchreply_state_machine_stop - Stop M-SEARCH reply state machine
354  * @a: Selected advertisement/reply state
355  */
356 void msearchreply_state_machine_stop(struct advertisement_state_machine *a)
357 {
358         struct upnp_wps_device_sm *sm = a->sm;
359         wpa_printf(MSG_DEBUG, "WPS UPnP: M-SEARCH stop");
360         if (a->next == a) {
361                 sm->msearch_replies = NULL;
362         } else  {
363                 if (sm->msearch_replies == a) {
364                         sm->msearch_replies = a->next;
365                 }
366                 a->next->prev = a->prev;
367                 a->prev->next = a->next;
368         }
369         os_free(a);
370         sm->n_msearch_replies--;
371 }
372
373
374 static void msearchreply_state_machine_handler(void *eloop_data,
375                                                void *user_ctx)
376 {
377         struct advertisement_state_machine *a = user_ctx;
378         struct upnp_wps_device_sm *sm = a->sm;
379         struct wpabuf *msg;
380         int next_timeout_msec = 100;
381         int next_timeout_sec = 0;
382         int islast = 0;
383
384         /*
385          * Each response is sent twice (in case lost) w/ 100 msec delay
386          * between; spec says no more than 3 times.
387          * One pair for rootdevice, one pair for uuid, and a pair each for
388          * each of the two urns.
389          */
390
391         /* TODO: should only send the requested response types */
392
393         wpa_printf(MSG_MSGDUMP, "WPS UPnP: M-SEARCH reply state=%d (%s:%d)",
394                    a->state, inet_ntoa(a->client.sin_addr),
395                    ntohs(a->client.sin_port));
396         msg = next_advertisement(a, &islast);
397         if (msg == NULL)
398                 return;
399
400         /*
401          * Send it on the multicast socket to avoid having to set up another
402          * socket.
403          */
404         if (sendto(sm->multicast_sd, wpabuf_head(msg), wpabuf_len(msg), 0,
405                    (struct sockaddr *) &a->client, sizeof(a->client)) < 0) {
406                 wpa_printf(MSG_DEBUG, "WPS UPnP: M-SEARCH reply sendto "
407                            "errno %d (%s) for %s:%d",
408                            errno, strerror(errno),
409                            inet_ntoa(a->client.sin_addr),
410                            ntohs(a->client.sin_port));
411                 /* Ignore error and hope for the best */
412         }
413         wpabuf_free(msg);
414         if (islast) {
415                 wpa_printf(MSG_DEBUG, "WPS UPnP: M-SEARCH reply done");
416                 msearchreply_state_machine_stop(a);
417                 return;
418         }
419         a->state++;
420
421         wpa_printf(MSG_MSGDUMP, "WPS UPnP: M-SEARCH reply in %d.%03d sec",
422                    next_timeout_sec, next_timeout_msec);
423         eloop_register_timeout(next_timeout_sec, next_timeout_msec,
424                                msearchreply_state_machine_handler, sm, a);
425 }
426
427
428 /**
429  * msearchreply_state_machine_start - Reply to M-SEARCH discovery request
430  * @sm: WPS UPnP state machine from upnp_wps_device_init()
431  * @client: Client address
432  * @mx: Maximum delay in seconds
433  *
434  * Use TTL of 4 (this was done when socket set up).
435  * A response should be given in randomized portion of min(MX,120) seconds
436  *
437  * UPnP-arch-DeviceArchitecture, 1.2.3:
438  * To be found, a device must send a UDP response to the source IP address and
439  * port that sent the request to the multicast channel. Devices respond if the
440  * ST header of the M-SEARCH request is "ssdp:all", "upnp:rootdevice", "uuid:"
441  * followed by a UUID that exactly matches one advertised by the device.
442  */
443 static void msearchreply_state_machine_start(struct upnp_wps_device_sm *sm,
444                                              struct sockaddr_in *client,
445                                              int mx)
446 {
447         struct advertisement_state_machine *a;
448         int next_timeout_sec;
449         int next_timeout_msec;
450
451         wpa_printf(MSG_DEBUG, "WPS UPnP: M-SEARCH reply start (%d "
452                    "outstanding)", sm->n_msearch_replies);
453         if (sm->n_msearch_replies >= MAX_MSEARCH) {
454                 wpa_printf(MSG_INFO, "WPS UPnP: Too many outstanding "
455                            "M-SEARCH replies");
456                 return;
457         }
458
459         a = os_zalloc(sizeof(*a));
460         if (a == NULL)
461                 return;
462         a->type = MSEARCH_REPLY;
463         a->state = 0;
464         a->sm = sm;
465         os_memcpy(&a->client, client, sizeof(client));
466         /* Wait time depending on MX value */
467         next_timeout_msec = (1000 * mx * (os_random() & 0xFF)) >> 8;
468         next_timeout_sec = next_timeout_msec / 1000;
469         next_timeout_msec = next_timeout_msec % 1000;
470         if (eloop_register_timeout(next_timeout_sec, next_timeout_msec,
471                                    msearchreply_state_machine_handler, sm,
472                                    a)) {
473                 /* No way to recover (from malloc failure) */
474                 goto fail;
475         }
476         /* Remember for future cleanup */
477         if (sm->msearch_replies) {
478                 a->next = sm->msearch_replies;
479                 a->prev = a->next->prev;
480                 a->prev->next = a;
481                 a->next->prev = a;
482         } else {
483                 sm->msearch_replies = a->next = a->prev = a;
484         }
485         sm->n_msearch_replies++;
486         return;
487
488 fail:
489         wpa_printf(MSG_INFO, "WPS UPnP: M-SEARCH reply failure!");
490         eloop_cancel_timeout(msearchreply_state_machine_handler, sm, a);
491         os_free(a);
492 }
493
494
495 /**
496  * ssdp_parse_msearch - Process a received M-SEARCH
497  * @sm: WPS UPnP state machine from upnp_wps_device_init()
498  * @client: Client address
499  * @data: NULL terminated M-SEARCH message
500  *
501  * Given that we have received a header w/ M-SEARCH, act upon it
502  *
503  * Format of M-SEARCH (case insensitive!):
504  *
505  * First line must be:
506  *      M-SEARCH * HTTP/1.1
507  * Other lines in arbitrary order:
508  *      HOST:239.255.255.250:1900
509  *      ST:<varies -- must match>
510  *      MAN:"ssdp:discover"
511  *      MX:<varies>
512  *
513  * It should be noted that when Microsoft Vista is still learning its IP
514  * address, it sends out host lines like: HOST:[FF02::C]:1900
515  */
516 static void ssdp_parse_msearch(struct upnp_wps_device_sm *sm,
517                                struct sockaddr_in *client, const char *data)
518 {
519         const char *start = data;
520         const char *end;
521         int got_host = 0;
522         int got_st = 0, st_match = 0;
523         int got_man = 0;
524         int got_mx = 0;
525         int mx = 0;
526
527         /*
528          * Skip first line M-SEARCH * HTTP/1.1
529          * (perhaps we should check remainder of the line for syntax)
530          */
531         data += line_length(data);
532
533         /* Parse remaining lines */
534         for (; *data != '\0'; data += line_length(data)) {
535                 end = data + line_length_stripped(data);
536                 if (token_eq(data, "host")) {
537                         /* The host line indicates who the packet
538                          * is addressed to... but do we really care?
539                          * Note that Microsoft sometimes does funny
540                          * stuff with the HOST: line.
541                          */
542 #if 0   /* could be */
543                         data += token_length(data);
544                         data += word_separation_length(data);
545                         if (*data != ':')
546                                 goto bad;
547                         data++;
548                         data += word_separation_length(data);
549                         /* UPNP_MULTICAST_ADDRESS */
550                         if (!str_starts(data, "239.255.255.250"))
551                                 goto bad;
552                         data += os_strlen("239.255.255.250");
553                         if (*data == ':') {
554                                 if (!str_starts(data, ":1900"))
555                                         goto bad;
556                         }
557 #endif  /* could be */
558                         got_host = 1;
559                         continue;
560                 } else if (token_eq(data, "st")) {
561                         /* There are a number of forms; we look
562                          * for one that matches our case.
563                          */
564                         got_st = 1;
565                         data += token_length(data);
566                         data += word_separation_length(data);
567                         if (*data != ':')
568                                 continue;
569                         data++;
570                         data += word_separation_length(data);
571                         if (str_starts(data, "ssdp:all")) {
572                                 st_match = 1;
573                                 continue;
574                         }
575                         if (str_starts(data, "upnp:rootdevice")) {
576                                 st_match = 1;
577                                 continue;
578                         }
579                         if (str_starts(data, "uuid:")) {
580                                 char uuid_string[80];
581                                 data += os_strlen("uuid:");
582                                 uuid_bin2str(sm->wps->uuid, uuid_string,
583                                              sizeof(uuid_string));
584                                 if (str_starts(data, uuid_string))
585                                         st_match = 1;
586                                 continue;
587                         }
588 #if 0
589                         /* FIX: should we really reply to IGD string? */
590                         if (str_starts(data, "urn:schemas-upnp-org:device:"
591                                        "InternetGatewayDevice:1")) {
592                                 st_match = 1;
593                                 continue;
594                         }
595 #endif
596                         if (str_starts(data, "urn:schemas-wifialliance-org:"
597                                        "service:WFAWLANConfig:1")) {
598                                 st_match = 1;
599                                 continue;
600                         }
601                         if (str_starts(data, "urn:schemas-wifialliance-org:"
602                                        "device:WFADevice:1")) {
603                                 st_match = 1;
604                                 continue;
605                         }
606                         continue;
607                 } else if (token_eq(data, "man")) {
608                         data += token_length(data);
609                         data += word_separation_length(data);
610                         if (*data != ':')
611                                 continue;
612                         data++;
613                         data += word_separation_length(data);
614                         if (!str_starts(data, "\"ssdp:discover\"")) {
615                                 wpa_printf(MSG_DEBUG, "WPS UPnP: Unexpected "
616                                            "M-SEARCH man-field");
617                                 goto bad;
618                         }
619                         got_man = 1;
620                         continue;
621                 } else if (token_eq(data, "mx")) {
622                         data += token_length(data);
623                         data += word_separation_length(data);
624                         if (*data != ':')
625                                 continue;
626                         data++;
627                         data += word_separation_length(data);
628                         mx = atol(data);
629                         got_mx = 1;
630                         continue;
631                 }
632                 /* ignore anything else */
633         }
634         if (!got_host || !got_st || !got_man || !got_mx || mx < 0) {
635                 wpa_printf(MSG_DEBUG, "WPS UPnP: Invalid M-SEARCH: %d %d %d "
636                            "%d mx=%d", got_host, got_st, got_man, got_mx, mx);
637                 goto bad;
638         }
639         if (!st_match) {
640                 wpa_printf(MSG_DEBUG, "WPS UPnP: Ignored M-SEARCH (no ST "
641                            "match)");
642                 return;
643         }
644         if (mx > 120)
645                 mx = 120; /* UPnP-arch-DeviceArchitecture, 1.2.3 */
646         msearchreply_state_machine_start(sm, client, mx);
647         return;
648
649 bad:
650         wpa_printf(MSG_INFO, "WPS UPnP: Failed to parse M-SEARCH");
651         wpa_printf(MSG_MSGDUMP, "WPS UPnP: M-SEARCH data:\n%s", start);
652 }
653
654
655 /* Listening for (UDP) discovery (M-SEARCH) packets */
656
657 /**
658  * ssdp_listener_stop - Stop SSDP listered
659  * @sm: WPS UPnP state machine from upnp_wps_device_init()
660  *
661  * This function stops the SSDP listerner that was started by calling
662  * ssdp_listener_start().
663  */
664 void ssdp_listener_stop(struct upnp_wps_device_sm *sm)
665 {
666         if (sm->ssdp_sd_registered) {
667                 eloop_unregister_sock(sm->ssdp_sd, EVENT_TYPE_READ);
668                 sm->ssdp_sd_registered = 0;
669         }
670
671         if (sm->ssdp_sd != -1) {
672                 close(sm->ssdp_sd);
673                 sm->ssdp_sd = -1;
674         }
675
676         eloop_cancel_timeout(msearchreply_state_machine_handler, sm,
677                              ELOOP_ALL_CTX);
678 }
679
680
681 static void ssdp_listener_handler(int sd, void *eloop_ctx, void *sock_ctx)
682 {
683         struct upnp_wps_device_sm *sm = sock_ctx;
684         struct sockaddr_in addr; /* client address */
685         socklen_t addr_len;
686         int nread;
687         char buf[MULTICAST_MAX_READ], *pos;
688
689         addr_len = sizeof(addr);
690         nread = recvfrom(sm->ssdp_sd, buf, sizeof(buf) - 1, 0,
691                          (struct sockaddr *) &addr, &addr_len);
692         if (nread <= 0)
693                 return;
694         buf[nread] = '\0'; /* need null termination for algorithm */
695
696         if (str_starts(buf, "NOTIFY ")) {
697                 /*
698                  * Silently ignore NOTIFYs to avoid filling debug log with
699                  * unwanted messages.
700                  */
701                 return;
702         }
703
704         pos = os_strchr(buf, '\n');
705         if (pos)
706                 *pos = '\0';
707         wpa_printf(MSG_MSGDUMP, "WPS UPnP: Received SSDP packet from %s:%d: "
708                    "%s", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port), buf);
709         if (pos)
710                 *pos = '\n';
711
712         /* Parse first line */
713         if (os_strncasecmp(buf, "M-SEARCH", os_strlen("M-SEARCH")) == 0 &&
714             !isgraph(buf[strlen("M-SEARCH")])) {
715                 ssdp_parse_msearch(sm, &addr, buf);
716                 return;
717         }
718
719         /* Ignore anything else */
720 }
721
722
723 /**
724  * ssdp_listener_start - Set up for receiving discovery (UDP) packets
725  * @sm: WPS UPnP state machine from upnp_wps_device_init()
726  * Returns: 0 on success, -1 on failure
727  *
728  * The SSDP listerner is stopped by calling ssdp_listener_stop().
729  */
730 int ssdp_listener_start(struct upnp_wps_device_sm *sm)
731 {
732         int sd = -1;
733         struct sockaddr_in addr;
734         struct ip_mreq mcast_addr;
735         int on = 1;
736         /* per UPnP spec, keep IP packet time to live (TTL) small */
737         unsigned char ttl = 4;
738
739         sm->ssdp_sd = sd = socket(AF_INET, SOCK_DGRAM, 0);
740         if (sd < 0)
741                 goto fail;
742         if (fcntl(sd, F_SETFL, O_NONBLOCK) != 0)
743                 goto fail;
744         if (setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)))
745                 goto fail;
746         os_memset(&addr, 0, sizeof(addr));
747         addr.sin_family = AF_INET;
748         addr.sin_addr.s_addr = htonl(INADDR_ANY);
749         addr.sin_port = htons(UPNP_MULTICAST_PORT);
750         if (bind(sd, (struct sockaddr *) &addr, sizeof(addr)))
751                 goto fail;
752         os_memset(&mcast_addr, 0, sizeof(mcast_addr));
753         mcast_addr.imr_interface.s_addr = htonl(INADDR_ANY);
754         mcast_addr.imr_multiaddr.s_addr = inet_addr(UPNP_MULTICAST_ADDRESS);
755         if (setsockopt(sd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
756                        (char *) &mcast_addr, sizeof(mcast_addr)))
757                 goto fail;
758         if (setsockopt(sd, IPPROTO_IP, IP_MULTICAST_TTL,
759                        &ttl, sizeof(ttl)))
760                 goto fail;
761         if (eloop_register_sock(sd, EVENT_TYPE_READ, ssdp_listener_handler,
762                                 NULL, sm))
763                 goto fail;
764         sm->ssdp_sd_registered = 1;
765         return 0;
766
767 fail:
768         /* Error */
769         wpa_printf(MSG_ERROR, "WPS UPnP: ssdp_listener_start failed");
770         ssdp_listener_stop(sm);
771         return -1;
772 }
773
774
775 /**
776  * add_ssdp_network - Add routing entry for SSDP
777  * @net_if: Selected network interface name
778  * Returns: 0 on success, -1 on failure
779  *
780  * This function assures that the multicast address will be properly
781  * handled by Linux networking code (by a modification to routing tables).
782  * This must be done per network interface. It really only needs to be done
783  * once after booting up, but it does not hurt to call this more frequently
784  * "to be safe".
785  */
786 int add_ssdp_network(char *net_if)
787 {
788         int ret = -1;
789         int sock = -1;
790         struct rtentry rt;
791         struct sockaddr_in *sin;
792
793         if (!net_if)
794                 goto fail;
795
796         os_memset(&rt, 0, sizeof(rt));
797         sock = socket(AF_INET, SOCK_DGRAM, 0);
798         if (sock < 0)
799                 goto fail;
800
801         rt.rt_dev = net_if;
802         sin = (struct sockaddr_in *) &rt.rt_dst;
803         sin->sin_family = AF_INET;
804         sin->sin_port = 0;
805         sin->sin_addr.s_addr = inet_addr(SSDP_TARGET);
806         sin = (struct sockaddr_in *) &rt.rt_genmask;
807         sin->sin_family = AF_INET;
808         sin->sin_port = 0;
809         sin->sin_addr.s_addr = inet_addr(SSDP_NETMASK);
810         rt.rt_flags = RTF_UP;
811         if (ioctl(sock, SIOCADDRT, &rt) < 0) {
812                 if (errno == EPERM) {
813                         wpa_printf(MSG_DEBUG, "add_ssdp_network: No "
814                                    "permissions to add routing table entry");
815                         /* Continue to allow testing as non-root */
816                 } else if (errno != EEXIST) {
817                         wpa_printf(MSG_INFO, "add_ssdp_network() ioctl errno "
818                                    "%d (%s)", errno, strerror(errno));
819                         goto fail;
820                 }
821         }
822
823         ret = 0;
824
825 fail:
826         if (sock >= 0)
827                 close(sock);
828
829         return ret;
830 }
831
832
833 /**
834  * ssdp_open_multicast - Open socket for sending multicast SSDP messages
835  * @sm: WPS UPnP state machine from upnp_wps_device_init()
836  * Returns: 0 on success, -1 on failure
837  */
838 int ssdp_open_multicast(struct upnp_wps_device_sm *sm)
839 {
840         int sd = -1;
841          /* per UPnP-arch-DeviceArchitecture, 1. Discovery, keep IP packet
842           * time to live (TTL) small */
843         unsigned char ttl = 4;
844
845         sm->multicast_sd = sd = socket(AF_INET, SOCK_DGRAM, 0);
846         if (sd < 0)
847                 return -1;
848
849 #if 0   /* maybe ok if we sometimes block on writes */
850         if (fcntl(sd, F_SETFL, O_NONBLOCK) != 0)
851                 return -1;
852 #endif
853
854         if (setsockopt(sd, IPPROTO_IP, IP_MULTICAST_IF,
855                        &sm->ip_addr, sizeof(sm->ip_addr)))
856                 return -1;
857         if (setsockopt(sd, IPPROTO_IP, IP_MULTICAST_TTL,
858                        &ttl, sizeof(ttl)))
859                 return -1;
860
861 #if 0   /* not needed, because we don't receive using multicast_sd */
862         {
863                 struct ip_mreq mreq;
864                 mreq.imr_multiaddr.s_addr = inet_addr(UPNP_MULTICAST_ADDRESS);
865                 mreq.imr_interface.s_addr = sm->ip_addr;
866                 wpa_printf(MSG_DEBUG, "WPS UPnP: Multicast addr 0x%x if addr "
867                            "0x%x",
868                            mreq.imr_multiaddr.s_addr,
869                            mreq.imr_interface.s_addr);
870                 if (setsockopt(sd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq,
871                                 sizeof(mreq))) {
872                         wpa_printf(MSG_ERROR,
873                                    "WPS UPnP: setsockopt "
874                                    "IP_ADD_MEMBERSHIP errno %d (%s)",
875                                    errno, strerror(errno));
876                         return -1;
877                 }
878         }
879 #endif  /* not needed */
880
881         /*
882          * TODO: What about IP_MULTICAST_LOOP? It seems to be on by default?
883          * which aids debugging I suppose but isn't really necessary?
884          */
885
886         return 0;
887 }