wps_upnp_ssdp.c 24 KB

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