If SSID are equal, sort by strength as well.
[dhcpcd-ui] / src / libdhcpcd / wpa.c
1 /*
2  * libdhcpcd
3  * Copyright 2009-2014 Roy Marples <roy@marples.name>
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26
27 #include <sys/socket.h>
28 #include <sys/stat.h>
29 #include <sys/un.h>
30
31 #include <assert.h>
32 #include <ctype.h>
33 #include <errno.h>
34 #include <limits.h>
35 #include <poll.h>
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include <unistd.h>
40
41 #define IN_LIBDHCPCD
42 #include "config.h"
43 #include "dhcpcd.h"
44
45 #ifndef SUN_LEN
46 #define SUN_LEN(su) \
47         (sizeof(*(su)) - sizeof((su)->sun_path) + strlen((su)->sun_path))
48 #endif
49
50 #define CLAMP(x, low, high) \
51         (((x) > (high)) ? (high) : (((x) < (low)) ? (low) : (x)))
52
53 static int
54 wpa_open(const char *ifname, char **path)
55 {
56         static int counter;
57         int fd;
58         socklen_t len;
59         struct sockaddr_un sun;
60
61         if ((fd = socket(AF_UNIX,
62             SOCK_DGRAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)) == -1)
63                 return -1;
64         memset(&sun, 0, sizeof(sun));
65         sun.sun_family = AF_UNIX;
66         snprintf(sun.sun_path, sizeof(sun.sun_path),
67             "/tmp/libdhcpcd-wpa-%d.%d", getpid(), counter++);
68         *path = strdup(sun.sun_path);
69         len = (socklen_t)SUN_LEN(&sun);
70         if (bind(fd, (struct sockaddr *)&sun, len) == -1) {
71                 close(fd);
72                 unlink(*path);
73                 free(*path);
74                 *path = NULL;
75                 return -1;
76         }
77         snprintf(sun.sun_path, sizeof(sun.sun_path),
78             WPA_CTRL_DIR "/%s", ifname);
79         len = (socklen_t)SUN_LEN(&sun);
80         if (connect(fd, (struct sockaddr *)&sun, len) == -1) {
81                 close(fd);
82                 unlink(*path);
83                 free(*path);
84                 *path = NULL;
85                 return -1;
86         }
87
88         return fd;
89 }
90
91 static ssize_t
92 wpa_cmd(int fd, const char *cmd, char *buffer, size_t len)
93 {
94         int retval;
95         ssize_t bytes;
96         struct pollfd pfd;
97
98         if (buffer)
99                 *buffer = '\0';
100         bytes = write(fd, cmd, strlen(cmd));
101         if (bytes == -1 || bytes == 0)
102                 return -1;
103         if (buffer == NULL || len == 0)
104                 return 0;
105         pfd.fd = fd;
106         pfd.events = POLLIN | POLLHUP;
107         pfd.revents = 0;
108         retval = poll(&pfd, 1, 2000);
109         if (retval == -1)
110                 return -1;
111         if (retval == 0 || !(pfd.revents & (POLLIN | POLLHUP)))
112                 return -1;
113
114         bytes = read(fd, buffer, len == 1 ? 1 : len - 1);
115         if (bytes != -1)
116                 buffer[bytes] = '\0';
117         return bytes;
118 }
119
120 bool
121 dhcpcd_wpa_command(DHCPCD_WPA *wpa, const char *cmd)
122 {
123         char buf[10];
124         ssize_t bytes;
125
126         bytes = wpa_cmd(wpa->command_fd, cmd, buf, sizeof(buf));
127         return (bytes == -1 || bytes == 0 ||
128             strcmp(buf, "OK\n")) ? false : true;
129 }
130
131 bool
132 dhcpcd_wpa_command_arg(DHCPCD_WPA *wpa, const char *cmd, const char *arg)
133 {
134         size_t cmdlen, nlen;
135
136         cmdlen = strlen(cmd);
137         nlen = cmdlen + strlen(arg) + 2;
138         if (!dhcpcd_realloc(wpa->con, nlen))
139                 return -1;
140         strlcpy(wpa->con->buf, cmd, wpa->con->buflen);
141         wpa->con->buf[cmdlen] = ' ';
142         strlcpy(wpa->con->buf + cmdlen + 1, arg, wpa->con->buflen - 1 - cmdlen);
143         return dhcpcd_wpa_command(wpa, wpa->con->buf);
144 }
145
146 static bool
147 dhcpcd_attach_detach(DHCPCD_WPA *wpa, bool attach)
148 {
149         char buf[10];
150         ssize_t bytes;
151
152         if (wpa->attached == attach)
153                 return true;
154
155         bytes = wpa_cmd(wpa->listen_fd, attach > 0 ? "ATTACH" : "DETACH",
156             buf, sizeof(buf));
157         if (bytes == -1 || bytes == 0 || strcmp(buf, "OK\n"))
158                 return false;
159
160         wpa->attached = attach;
161         return true;
162 }
163
164 bool
165 dhcpcd_wpa_scan(DHCPCD_WPA *wpa)
166 {
167
168         return dhcpcd_wpa_command(wpa, "SCAN");
169 }
170
171 void
172 dhcpcd_wi_scans_free(DHCPCD_WI_SCAN *wis)
173 {
174         DHCPCD_WI_SCAN *n;
175
176         while (wis) {
177                 n = wis->next;
178                 free(wis);
179                 wis = n;
180         }
181 }
182
183 static void
184 dhcpcd_strtoi(int *val, const char *s)
185 {
186         long l;
187
188         l = strtol(s, NULL, 0);
189         if (l >= INT_MIN && l <= INT_MAX)
190                 *val = (int)l;
191         else
192                 errno = ERANGE;
193 }
194
195 static int
196 dhcpcd_wpa_hex2num(char c)
197 {
198
199         if (c >= '0' && c <= '9')
200                 return c - '0';
201         if (c >= 'a' && c <= 'f')
202                 return c - 'a' + 10;
203         if (c >= 'A' && c <= 'F')
204                 return c - 'A' + 10;
205         return -1;
206 }
207
208 static int
209 dhcpcd_wpa_hex2byte(const char *src)
210 {
211         int h, l;
212
213         if ((h = dhcpcd_wpa_hex2num(*src++)) == -1 ||
214             (l = dhcpcd_wpa_hex2num(*src)) == -1)
215                 return -1;
216         return (h << 4) | l;
217 }
218
219 static ssize_t
220 dhcpcd_wpa_decode_ssid(char *dst, size_t dlen, const char *src)
221 {
222         const char *start;
223         char c, esc;
224         int xb;
225
226         start = dst;
227         for (;;) {
228                 if (*src == '\0')
229                         break;
230                 if (--dlen == 0) {
231                         errno = ENOSPC;
232                         return -1;
233                 }
234                 c = *src++;
235                 switch (c) {
236                 case '\\':
237                         if (*src == '\0') {
238                                 errno = EINVAL;
239                                 return -1;
240                         }
241                         esc = *src++;
242                         switch (esc) {
243                         case '\\':
244                         case '"': *dst++ = esc; break;
245                         case 'n': *dst++ = '\n'; break;
246                         case 'r': *dst++ = '\r'; break;
247                         case 't': *dst++ = '\t'; break;
248                         case 'e': *dst++ = '\033'; break;
249                         case 'x':
250                                 if (src[0] == '\0' || src[1] == '\0') {
251                                         errno = EINVAL;
252                                         return -1;
253                                 }
254                                 if ((xb = dhcpcd_wpa_hex2byte(src)) == -1)
255                                         return -1;
256                                 *dst++ = (char)xb;
257                                 src += 2;
258                                 break;
259                         default: errno = EINVAL; return -1;
260                         }
261                 default: *dst++ = c; break;
262                 }
263         }
264         if (dlen == 0) {
265                 errno = ENOSPC;
266                 return -1;
267         }
268         *dst = '\0';
269         return dst - start;
270 }
271
272 static DHCPCD_WI_SCAN *
273 dhcpcd_wpa_scans_read(DHCPCD_WPA *wpa)
274 {
275         size_t i;
276         ssize_t bytes, dl;
277         DHCPCD_WI_SCAN *wis, *w, *l;
278         char *s, *p, buf[32];
279         char wssid[sizeof(w->ssid)];
280
281         if (!dhcpcd_realloc(wpa->con, 2048))
282                 return NULL;
283         wis = NULL;
284         for (i = 0; i < 1000; i++) {
285                 snprintf(buf, sizeof(buf), "BSS %zu", i);
286                 bytes = wpa_cmd(wpa->command_fd, buf,
287                     wpa->con->buf, wpa->con->buflen);
288                 if (bytes == 0 || bytes == -1 ||
289                     strncmp(wpa->con->buf, "FAIL", 4) == 0)
290                         break;
291                 p = wpa->con->buf;
292                 w = calloc(1, sizeof(*w));
293                 if (w == NULL)
294                         break;
295                 dl = 0;
296                 wssid[0] = '\0';
297                 while ((s = strsep(&p, "\n"))) {
298                         if (*s == '\0')
299                                 continue;
300                         if (strncmp(s, "bssid=", 6) == 0)
301                                 strlcpy(w->bssid, s + 6, sizeof(w->bssid));
302                         else if (strncmp(s, "freq=", 5) == 0)
303                                 dhcpcd_strtoi(&w->frequency, s + 5);
304 //                      else if (strncmp(s, "beacon_int=", 11) == 0)
305 //                              ;
306                         else if (strncmp(s, "qual=", 5) == 0)
307                                 dhcpcd_strtoi(&w->quality.value, s + 5);
308                         else if (strncmp(s, "noise=", 6) == 0)
309                                 dhcpcd_strtoi(&w->noise.value, s + 6);
310                         else if (strncmp(s, "level=", 6) == 0)
311                                 dhcpcd_strtoi(&w->level.value, s + 6);
312                         else if (strncmp(s, "flags=", 6) == 0)
313                                 strlcpy(w->flags, s + 6, sizeof(w->flags));
314                         else if (strncmp(s, "ssid=", 5) == 0) {
315                                 /* Decode it from \xNN to \NNN
316                                  * so we're consistent */
317                                 dl = dhcpcd_wpa_decode_ssid(wssid,
318                                     sizeof(wssid), s + 5);
319                                 if (dl == -1)
320                                         break;
321                                 dl = dhcpcd_encode_string_escape(w->ssid,
322                                     sizeof(w->ssid), wssid, (size_t)dl);
323                                 if (dl == -1)
324                                         break;
325                         }
326                 }
327                 if (dl == -1) {
328                         free(w);
329                         break;
330                 }
331
332                 if (wis == NULL)
333                         wis = w;
334                 else
335                         l->next = w;
336                 l = w;
337
338                 w->strength.value = w->level.value;
339                 if (w->strength.value > 110 && w->strength.value < 256)
340                         /* Convert WEXT level to dBm */
341                         w->strength.value -= 256;
342
343                 if (w->strength.value < 0) {
344                         /* Assume dBm */
345                         w->strength.value =
346                             abs(CLAMP(w->strength.value, -100, -40) + 40);
347                         w->strength.value =
348                             100 - ((100 * w->strength.value) / 60);
349                 } else {
350                         /* Assume quality percentage */
351                         w->strength.value = CLAMP(w->strength.value, 0, 100);
352                 }
353         }
354         return wis;
355 }
356
357 static int
358 dhcpcd_wi_scan_compare(DHCPCD_WI_SCAN *a, DHCPCD_WI_SCAN *b)
359 {
360         int cmp;
361
362         cmp = strcasecmp(a->ssid, b->ssid);
363         if (cmp == 0)
364                 /* Return strongest first */
365                 cmp = b->strength.value - a->strength.value;
366         return cmp;
367 }
368
369 /*
370  * This function is copyright 2001 Simon Tatham.
371  *
372  * Permission is hereby granted, free of charge, to any person
373  * obtaining a copy of this software and associated documentation
374  * files (the "Software"), to deal in the Software without
375  * restriction, including without limitation the rights to use,
376  * copy, modify, merge, publish, distribute, sublicense, and/or
377  * sell copies of the Software, and to permit persons to whom the
378  * Software is furnished to do so, subject to the following
379  * conditions:
380  *
381  * The above copyright notice and this permission notice shall be
382  * included in all copies or substantial portions of the Software.
383  *
384  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
385  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
386  * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
387  * NONINFRINGEMENT.  IN NO EVENT SHALL SIMON TATHAM BE LIABLE FOR
388  * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
389  * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
390  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
391  * SOFTWARE.
392  */
393 static DHCPCD_WI_SCAN *
394 dhcpcd_wi_scans_sort(DHCPCD_WI_SCAN *list)
395 {
396         DHCPCD_WI_SCAN *p, *q, *e, *tail;
397         size_t insize, nmerges, psize, qsize, i;
398
399         /* Silly special case: if `list' was passed in as NULL, return
400          * NULL immediately. */
401         if (!list)
402                 return NULL;
403
404         insize = 1;
405
406         for (;;) {
407                 p = list;
408                 list = tail = NULL;
409                 nmerges = 0;  /* count number of merges we do in this pass */
410
411                 while (p) {
412                         nmerges++;  /* there exists a merge to be done */
413                         /* step `insize' places along from p */
414                         q = p;
415                         psize = 0;
416                         for (i = 0; i < insize; i++) {
417                                 psize++;
418                                 q = q->next;
419                                 if (!q)
420                                         break;
421                         }
422
423                         /* if q hasn't fallen off end,
424                          * we have two lists to merge */
425                         qsize = insize;
426
427                         /* now we have two lists; merge them */
428                         while (psize > 0 || (qsize > 0 && q)) {
429                                 /* decide whether next element of merge comes
430                                  * from p or q */
431                                 if (psize == 0) {
432                                         /* p is empty; e must come from q. */
433                                         e = q; q = q->next; qsize--;
434                                 } else if (qsize == 0 || !q) {
435                                         /* q is empty; e must come from p. */
436                                         e = p; p = p->next; psize--;
437                                 } else if (dhcpcd_wi_scan_compare(p, q) <= 0) {
438                                         /* First element of p is lower
439                                          * (or same); e must come from p. */
440                                         e = p; p = p->next; psize--;
441                                 } else {
442                                         /* First element of q is lower;
443                                          * e must come from q. */
444                                         e = q; q = q->next; qsize--;
445                                 }
446
447                                 /* add the next element to the merged list */
448                                 if (tail)
449                                         tail->next = e;
450                                 else
451                                         list = e;
452                                 tail = e;
453                         }
454
455                         /* now p has stepped `insize' places along,
456                          * and q has too */
457                         p = q;
458                 }
459                 tail->next = NULL;
460
461                 /* If we have done only one merge, we're finished. */
462                 if (nmerges <= 1)   /* allow for nmerges==0, the empty list */
463                         return list;
464
465                 /* Otherwise repeat, merging lists twice the size */
466                 insize *= 2;
467         }
468 }
469
470 DHCPCD_WI_SCAN *
471 dhcpcd_wi_scans(DHCPCD_IF *i)
472 {
473         DHCPCD_WPA *wpa;
474         DHCPCD_WI_SCAN *wis, *w;
475         int nh;
476         DHCPCD_WI_HIST *h, *hl;
477
478         wpa = dhcpcd_wpa_find(i->con, i->ifname);
479         if (wpa == NULL)
480                 return NULL;
481         wis = dhcpcd_wpa_scans_read(wpa);
482
483         /* Sort the resultant list alphabetically and then by strength */
484         wis = dhcpcd_wi_scans_sort(wis);
485
486         for (w = wis; w; w = w->next) {
487                 nh = 1;
488                 hl = NULL;
489                 w->quality.average = w->quality.value;
490                 w->noise.average = w->noise.value;
491                 w->level.average = w->level.value;
492                 w->strength.average = w->strength.value;
493
494                 for (h = wpa->con->wi_history; h; h = h->next) {
495                         if (strcmp(h->ifname, i->ifname) == 0 &&
496                             strcmp(h->bssid, wis->bssid) == 0)
497                         {
498                                 w->quality.average += h->quality;
499                                 w->noise.average += h->noise;
500                                 w->level.average += h->level;
501                                 w->strength.average += h->strength;
502                                 if (++nh == DHCPCD_WI_HIST_MAX) {
503                                         hl->next = h->next;
504                                         free(h);
505                                         break;
506                                 }
507                         }
508                         hl = h;
509                 }
510
511                 if (nh != 1) {
512                         w->quality.average /= nh;
513                         w->noise.average /= nh;
514                         w->level.average /= nh;
515                         w->strength.average /= nh;
516                 }
517                 h = malloc(sizeof(*h));
518                 if (h) {
519                         strlcpy(h->ifname, i->ifname, sizeof(h->ifname));
520                         strlcpy(h->bssid, w->bssid, sizeof(h->bssid));
521                         h->quality = w->quality.value;
522                         h->noise = w->noise.value;
523                         h->level = w->level.value;
524                         h->strength = w->strength.value;
525                         h->next = wpa->con->wi_history;
526                         wpa->con->wi_history = h;
527                 }
528         }
529
530         return wis;
531 }
532
533 bool
534 dhcpcd_wpa_reassociate(DHCPCD_WPA *wpa)
535 {
536
537         return dhcpcd_wpa_command(wpa, "REASSOCIATE");
538 }
539
540 bool
541 dhcpcd_wpa_disconnect(DHCPCD_WPA *wpa)
542 {
543
544         return dhcpcd_wpa_command(wpa, "DISCONNECT");
545 }
546
547 bool
548 dhcpcd_wpa_config_write(DHCPCD_WPA *wpa)
549 {
550
551         return dhcpcd_wpa_command(wpa, "SAVE_CONFIG");
552 }
553
554 static bool
555 dhcpcd_wpa_network(DHCPCD_WPA *wpa, const char *cmd, int id)
556 {
557         size_t len;
558
559         len = strlen(cmd) + 32;
560         if (!dhcpcd_realloc(wpa->con, len))
561                 return false;
562         snprintf(wpa->con->buf, wpa->con->buflen, "%s %d", cmd, id);
563         return dhcpcd_wpa_command(wpa, wpa->con->buf);
564 }
565
566 bool
567 dhcpcd_wpa_network_disable(DHCPCD_WPA *wpa, int id)
568 {
569
570         return dhcpcd_wpa_network(wpa, "DISABLE_NETWORK", id);
571 }
572
573 bool
574 dhcpcd_wpa_network_enable(DHCPCD_WPA *wpa, int id)
575 {
576
577         return dhcpcd_wpa_network(wpa, "ENABLE_NETWORK", id);
578 }
579
580 bool
581 dhcpcd_wpa_network_remove(DHCPCD_WPA *wpa, int id)
582 {
583
584         return dhcpcd_wpa_network(wpa, "REMOVE_NETWORK", id);
585 }
586
587 char *
588 dhcpcd_wpa_network_get(DHCPCD_WPA *wpa, int id, const char *param)
589 {
590         ssize_t bytes;
591
592         if (!dhcpcd_realloc(wpa->con, 2048))
593                 return NULL;
594         snprintf(wpa->con->buf, wpa->con->buflen, "GET_NETWORK %d %s",
595             id, param);
596         bytes = wpa_cmd(wpa->command_fd, wpa->con->buf,
597             wpa->con->buf, wpa->con->buflen);
598         if (bytes == 0 || bytes == -1)
599                 return NULL;
600         if (strcmp(wpa->con->buf, "FAIL\n") == 0) {
601                 errno = EINVAL;
602                 return NULL;
603         }
604         return wpa->con->buf;
605 }
606
607 bool
608 dhcpcd_wpa_network_set(DHCPCD_WPA *wpa, int id,
609     const char *param, const char *value)
610 {
611         size_t len;
612
613         len = strlen("SET_NETWORK") + 32 + strlen(param) + strlen(value) + 3;
614         if (!dhcpcd_realloc(wpa->con, len))
615                 return false;
616         snprintf(wpa->con->buf, wpa->con->buflen, "SET_NETWORK %d %s %s",
617             id, param, value);
618         return dhcpcd_wpa_command(wpa, wpa->con->buf);
619 }
620
621 static int
622 dhcpcd_wpa_network_find(DHCPCD_WPA *wpa, const char *fssid)
623 {
624         ssize_t bytes, dl, tl;
625         size_t fl;
626         char *s, *t, *ssid, *bssid, *flags;
627         char dssid[IF_SSIDSIZE], tssid[IF_SSIDSIZE];
628         long l;
629
630         dhcpcd_realloc(wpa->con, 2048);
631         bytes = wpa_cmd(wpa->command_fd, "LIST_NETWORKS",
632             wpa->con->buf, wpa->con->buflen);
633         if (bytes == 0 || bytes == -1)
634                 return -1;
635
636         fl = strlen(fssid);
637
638         s = strchr(wpa->con->buf, '\n');
639         if (s == NULL)
640                 return -1;
641         while ((t = strsep(&s, "\b"))) {
642                 if (*t == '\0')
643                         continue;
644                 ssid = strchr(t, '\t');
645                 if (ssid == NULL)
646                         break;
647                 *ssid++ = '\0';
648                 bssid = strchr(ssid, '\t');
649                 if (bssid == NULL)
650                         break;
651                 *bssid++ = '\0';
652                 flags = strchr(bssid, '\t');
653                 if (flags == NULL)
654                         break;
655                 *flags++ = '\0';
656                 l = strtol(t, NULL, 0);
657                 if (l < 0 || l > INT_MAX) {
658                         errno = ERANGE;
659                         break;
660                 }
661
662                 /* Decode the wpa_supplicant SSID into raw chars and
663                  * then encode into our octal escaped string to
664                  * compare. */
665                 dl = dhcpcd_wpa_decode_ssid(dssid, sizeof(dssid), ssid);
666                 if (dl == -1)
667                         return -1;
668                 tl = dhcpcd_encode_string_escape(tssid,
669                     sizeof(tssid), dssid, (size_t)dl);
670                 if (tl == -1)
671                         return -1;
672                 if ((size_t)tl == fl && memcmp(tssid, fssid, (size_t)tl) == 0)
673                         return (int)l;
674         }
675         errno = ENOENT;
676         return -1;
677 }
678
679 static int
680 dhcpcd_wpa_network_new(DHCPCD_WPA *wpa)
681 {
682         ssize_t bytes;
683         long l;
684
685         dhcpcd_realloc(wpa->con, 32);
686         bytes = wpa_cmd(wpa->command_fd, "ADD_NETWORK",
687             wpa->con->buf, sizeof(wpa->con->buf));
688         if (bytes == 0 || bytes == -1)
689                 return -1;
690         l = strtol(wpa->con->buf, NULL, 0);
691         if (l < 0 || l > INT_MAX) {
692                 errno = ERANGE;
693                 return -1;
694         }
695         return (int)l;
696 }
697
698 static const char hexchrs[] = "0123456789abcdef";
699 int
700 dhcpcd_wpa_network_find_new(DHCPCD_WPA *wpa, const char *ssid)
701 {
702         int id;
703         char dssid[IF_SSIDSIZE], essid[IF_SSIDSIZE], *ep;
704         ssize_t dl, i;
705         char *dp;
706
707         id = dhcpcd_wpa_network_find(wpa, ssid);
708         if (id != -1)
709                 return id;
710
711         dl = dhcpcd_decode_string_escape(dssid, sizeof(dssid), ssid);
712         if (dl == -1)
713                 return -1;
714
715         for (i = 0; i < dl; i++) {
716                 if (!isascii((int)dssid[i]) && !isprint((int)dssid[i]))
717                         break;
718         }
719         dp = dssid;
720         ep = essid;
721         if (i < dl) {
722                 /* Non standard characters found! Encode as hex string */
723                 unsigned char c;
724
725                 for (; dl; dl--) {
726                         c = (unsigned char)*dp++;
727                         *ep++ = hexchrs[(c & 0xf0) >> 4];
728                         *ep++ = hexchrs[(c & 0x0f)];
729                 }
730         } else {
731                 *ep++ = '\"';
732                 do
733                         *ep++ = *dp;
734                 while (*++dp != '\0');
735                 *ep++ = '\"';
736         }
737         *ep = '\0';
738
739         id = dhcpcd_wpa_network_new(wpa);
740         if (id != -1)
741                 dhcpcd_wpa_network_set(wpa, id, "ssid", essid);
742         return id;
743 }
744
745 void
746 dhcpcd_wpa_close(DHCPCD_WPA *wpa)
747 {
748
749         assert(wpa);
750
751         if (wpa->command_fd == -1 || !wpa->open)
752                 return;
753
754         wpa->open = false;
755         dhcpcd_attach_detach(wpa, false);
756         shutdown(wpa->command_fd, SHUT_RDWR);
757         shutdown(wpa->listen_fd, SHUT_RDWR);
758
759         if (wpa->con->wpa_status_cb)
760                 wpa->con->wpa_status_cb(wpa, "down",
761                     wpa->con->wpa_status_context);
762
763         close(wpa->command_fd);
764         wpa->command_fd = -1;
765         close(wpa->listen_fd);
766         wpa->listen_fd = -1;
767         unlink(wpa->command_path);
768         free(wpa->command_path);
769         wpa->command_path = NULL;
770         unlink(wpa->listen_path);
771         free(wpa->listen_path);
772         wpa->listen_path = NULL;
773 }
774
775 DHCPCD_WPA *
776 dhcpcd_wpa_find(DHCPCD_CONNECTION *con, const char *ifname)
777 {
778         DHCPCD_WPA *wpa;
779
780         for (wpa = con->wpa; wpa; wpa = wpa->next) {
781                 if (strcmp(wpa->ifname, ifname) == 0)
782                         return wpa;
783         }
784         errno = ENOENT;
785         return NULL;
786 }
787
788 DHCPCD_WPA *
789 dhcpcd_wpa_new(DHCPCD_CONNECTION *con, const char *ifname)
790 {
791         DHCPCD_WPA *wpa;
792
793         wpa = dhcpcd_wpa_find(con, ifname);
794         if (wpa)
795                 return wpa;
796
797         wpa = malloc(sizeof(*wpa));
798         if (wpa == NULL)
799                 return NULL;
800
801         wpa->con = con;
802         strlcpy(wpa->ifname, ifname, sizeof(wpa->ifname));
803         wpa->command_fd = wpa->listen_fd = -1;
804         wpa->command_path = wpa->listen_path = NULL;
805         wpa->next = con->wpa;
806         con->wpa = wpa;
807         return wpa;
808 }
809
810 DHCPCD_CONNECTION *
811 dhcpcd_wpa_connection(DHCPCD_WPA *wpa)
812 {
813
814         assert(wpa);
815         return wpa->con;
816 }
817
818 DHCPCD_IF *
819 dhcpcd_wpa_if(DHCPCD_WPA *wpa)
820 {
821
822         return dhcpcd_get_if(wpa->con, wpa->ifname, "link");
823 }
824
825 int
826 dhcpcd_wpa_open(DHCPCD_WPA *wpa)
827 {
828         int cmd_fd, list_fd = -1;
829         char *cmd_path = NULL, *list_path = NULL;
830
831         if (wpa->listen_fd != -1) {
832                 if (!wpa->open) {
833                         errno = EISCONN;
834                         return -1;
835                 }
836                 return wpa->listen_fd;
837         }
838
839         cmd_fd = wpa_open(wpa->ifname, &cmd_path);
840         if (cmd_fd == -1)
841                 goto fail;
842
843         list_fd = wpa_open(wpa->ifname, &list_path);
844         if (list_fd == -1)
845                 goto fail;
846
847         wpa->open = true;
848         wpa->attached = false;
849         wpa->command_fd = cmd_fd;
850         wpa->command_path = cmd_path;
851         wpa->listen_fd = list_fd;
852         wpa->listen_path = list_path;
853         if (!dhcpcd_attach_detach(wpa, true)) {
854                 dhcpcd_wpa_close(wpa);
855                 return -1;
856         }
857
858         if (wpa->con->wi_scanresults_cb)
859                 wpa->con->wi_scanresults_cb(wpa,
860                     wpa->con->wi_scanresults_context);
861
862         return wpa->listen_fd;
863
864 fail:
865         if (cmd_fd != -1)
866                 close(cmd_fd);
867         if (list_fd != -1)
868                 close(list_fd);
869         if (cmd_path)
870                 unlink(cmd_path);
871         free(cmd_path);
872         if (list_path)
873                 free(list_path);
874         return -1;
875 }
876
877 int
878 dhcpcd_wpa_get_fd(DHCPCD_WPA *wpa)
879 {
880
881         assert(wpa);
882         return wpa->open ? wpa->listen_fd : -1;
883 }
884
885 void
886 dhcpcd_wpa_set_scan_callback(DHCPCD_CONNECTION *con,
887     void (*cb)(DHCPCD_WPA *, void *), void *context)
888 {
889
890         assert(con);
891         con->wi_scanresults_cb = cb;
892         con->wi_scanresults_context = context;
893 }
894
895
896 void dhcpcd_wpa_set_status_callback(DHCPCD_CONNECTION * con,
897     void (*cb)(DHCPCD_WPA *, const char *, void *), void *context)
898 {
899
900         assert(con);
901         con->wpa_status_cb = cb;
902         con->wpa_status_context = context;
903 }
904
905 void
906 dhcpcd_wpa_dispatch(DHCPCD_WPA *wpa)
907 {
908         char buffer[256], *p;
909         size_t bytes;
910
911         assert(wpa);
912         bytes = (size_t)read(wpa->listen_fd, buffer, sizeof(buffer));
913         if ((ssize_t)bytes == -1 || bytes == 0) {
914                 dhcpcd_wpa_close(wpa);
915                 return;
916         }
917
918         buffer[bytes] = '\0';
919         bytes = strlen(buffer);
920         if (buffer[bytes - 1] == ' ')
921                 buffer[--bytes] = '\0';
922         for (p = buffer + 1; *p != '\0'; p++)
923                 if (*p == '>') {
924                         p++;
925                         break;
926                 }
927         if (strcmp(p, "CTRL-EVENT-SCAN-RESULTS") == 0 &&
928             wpa->con->wi_scanresults_cb)
929                 wpa->con->wi_scanresults_cb(wpa,
930                     wpa->con->wi_scanresults_context);
931         return;
932 }
933
934 void
935 dhcpcd_wpa_if_event(DHCPCD_IF *i)
936 {
937         DHCPCD_WPA *wpa;
938
939         assert(i);
940         if (strcmp(i->type, "link") == 0) {
941                 if (strcmp(i->reason, "STOPPED") == 0 ||
942                     strcmp(i->reason, "DEPARTED") == 0)
943                 {
944                         wpa = dhcpcd_wpa_find(i->con, i->ifname);
945                         if (wpa)
946                                 dhcpcd_wpa_close(wpa);
947                 } else if (i->wireless && i->con->wpa_started) {
948                         wpa = dhcpcd_wpa_new(i->con, i->ifname);
949                         if (wpa && wpa->listen_fd == -1)
950                                 dhcpcd_wpa_open(wpa);
951                 }
952         }
953 }
954
955 void
956 dhcpcd_wpa_start(DHCPCD_CONNECTION *con)
957 {
958         DHCPCD_IF *i;
959
960         assert(con);
961         con->wpa_started = true;
962
963         for (i = con->interfaces; i; i = i->next)
964                 dhcpcd_wpa_if_event(i);
965 }
966
967 int
968 dhcpcd_wpa_configure_psk(DHCPCD_WPA *wpa, DHCPCD_WI_SCAN *s, const char *psk)
969 {
970         const char *mgmt, *var;
971         int id;
972         char *npsk;
973         size_t psk_len;
974         bool r;
975
976         assert(wpa);
977         assert(s);
978
979         id = dhcpcd_wpa_network_find_new(wpa, s->ssid);
980         if (id == -1)
981                 return DHCPCD_WPA_ERR;
982
983         if (strcmp(s->flags, "[WEP]") == 0) {
984                 mgmt = "NONE";
985                 var = "wep_key0";
986         } else {
987                 mgmt = "WPA-PSK";
988                 var = "psk";
989         }
990
991         if (!dhcpcd_wpa_network_set(wpa, id, "key_mgmt", mgmt))
992                 return DHCPCD_WPA_ERR_SET;
993
994         if (psk)
995                 psk_len = strlen(psk);
996         else
997                 psk_len = 0;
998         npsk = malloc(psk_len + 3);
999         if (npsk == NULL)
1000                 return DHCPCD_WPA_ERR;
1001         npsk[0] = '"';
1002         if (psk_len)
1003                 memcpy(npsk + 1, psk, psk_len);
1004         npsk[psk_len + 1] = '"';
1005         npsk[psk_len + 2] = '\0';
1006         r = dhcpcd_wpa_network_set(wpa, id, var, npsk);
1007         free(npsk);
1008         if (!r)
1009                 return DHCPCD_WPA_ERR_SET_PSK;
1010
1011         if (!dhcpcd_wpa_network_enable(wpa, id))
1012                 return DHCPCD_WPA_ERR_ENABLE;
1013         if (!dhcpcd_wpa_reassociate(wpa))
1014                 return DHCPCD_WPA_ERR_ASSOC;
1015         if (!dhcpcd_wpa_config_write(wpa))
1016                 return DHCPCD_WPA_ERR_WRITE;
1017         return DHCPCD_WPA_SUCCESS;
1018 }