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