wps_upnp_ssdp.c 26 KB

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