wps_upnp_ssdp.c 25 KB

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