Release dhcpcd-ui-0.7.6
[dhcpcd-ui] / src / libdhcpcd / dhcpcd.c
1 /*
2  * libdhcpcd
3  * Copyright 2009-2016 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 // For strverscmp(3)
28 #define _GNU_SOURCE
29
30 #include <sys/socket.h>
31 #include <sys/stat.h>
32 #include <sys/un.h>
33
34 #include <arpa/inet.h>
35
36 #include <assert.h>
37 #include <ctype.h>
38 #include <errno.h>
39 #include <fcntl.h>
40 #include <limits.h>
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <unistd.h>
45
46 #define IN_LIBDHCPCD
47
48 #include "config.h"
49 #include "dhcpcd.h"
50
51 #ifdef HAS_GETTEXT
52 #include <libintl.h>
53 #define _ gettext
54 #else
55 #define _(a) (a)
56 #endif
57
58 #ifdef HAVE_VIS_H
59 #include <vis.h>
60 #endif
61
62 #ifndef SUN_LEN
63 #define SUN_LEN(su) \
64         (sizeof(*(su)) - sizeof((su)->sun_path) + strlen((su)->sun_path))
65 #endif
66
67 #ifndef iswhite
68 #define iswhite(c)      (c == ' ' || c == '\t' || c == '\n')
69 #endif
70
71 const char * const dhcpcd_cstates[DHC_MAX] = {
72         "unknown",
73         "down",
74         "opened",
75         "initialised",
76         "disconnected",
77         "connecting",
78         "waiting",
79         "connected",
80 };
81
82 struct dhcpcd_vs {
83         unsigned int val;
84         const char *str;
85 };
86
87 static const struct dhcpcd_vs dhcpcd_states[] = {
88     { DHS_DUMP,         "DUMP" },
89     { DHS_TEST,         "TEST" },
90     { DHS_STOPPED,      "STOPPED" },
91     { DHS_FAIL,         "FAIL" },
92     { DHS_STOP,         "STOP" },
93     { DHS_PREINIT,      "PREINIT" },
94     { DHS_DEPARTED,     "DEPARTED" },
95     { DHS_NOCARRIER,    "NOCARRIER" },
96     { DHS_NAK,          "NAK" },
97     { DHS_EXPIRE,       "EXPIRE" },
98     { DHS_RECONFIGURE,  "RECONFIGURE" },
99     { DHS_CARRIER,      "CARRIER" },
100     { DHS_STATIC,       "STATIC" },
101     { DHS_3RDPARTY,     "3RDPARTY" },
102     { DHS_IPV4LL,       "IPV4LL" },
103     { DHS_INFORM,       "INFORM" },
104     { DHS_BOUND,        "BOUND" },
105     { DHS_RENEW,        "RENEW" },
106     { DHS_REBIND,       "REBIND" },
107     { DHS_REBOOT,       "REBOOT" },
108     { DHS_ROUTERADVERT, "ROUTERADVERT" },
109     { DHS_BOUND,        "DELEGATED" },
110     { DHS_UNKNOWN,      NULL    }
111 };
112
113 static ssize_t
114 dhcpcd_command_fd(DHCPCD_CONNECTION *con,
115     int fd, bool progname, const char *cmd, char **buffer)
116 {
117         size_t pl, cl, len;
118         ssize_t bytes;
119         char buf[1024], *p;
120         char *nbuf;
121
122         assert(con);
123         assert(cmd);
124
125         /* Each command is \n terminated.
126          * Each argument is NULL seperated.
127          * We may need to send a space one day, so the API
128          * in this function may need to be improved */
129         cl = strlen(cmd);
130         if (progname) {
131                 pl = strlen(con->progname);
132                 len = pl + 1 + cl + 1;
133         } else {
134                 pl = 0;
135                 len = cl + 1;
136         }
137         if (con->terminate_commands)
138                 len++;
139         if (len > sizeof(buf)) {
140                 errno = ENOBUFS;
141                 return -1;
142         }
143         p = buf;
144         if (progname) {
145                 memcpy(buf, con->progname, pl);
146                 buf[pl] = '\0';
147                 p = buf + pl + 1;
148         }
149         memcpy(p, cmd, cl);
150         p[cl] = '\0';
151         while ((p = strchr(p, ' ')) != NULL)
152                 *p++ = '\0';
153         if (con->terminate_commands) {
154                 buf[len - 2] = '\n';
155                 buf[len - 1] = '\0';
156         } else
157                 buf[len - 1] = '\0';
158         if (write(fd, buf, len) == -1)
159                 return -1;
160         if (buffer == NULL)
161                 return 0;
162
163         bytes = read(fd, buf, sizeof(size_t));
164         if (bytes == 0 || bytes == -1)
165                 return bytes;
166         memcpy(&len, buf, sizeof(size_t));
167         nbuf = realloc(*buffer, len + 1);
168         if (nbuf == NULL)
169                 return -1;
170         *buffer = nbuf;
171         bytes = read(fd, *buffer, len);
172         if (bytes != -1 && (size_t)bytes < len)
173                 *buffer[bytes] = '\0';
174         return bytes;
175 }
176
177 ssize_t
178 dhcpcd_command(DHCPCD_CONNECTION *con, const char *cmd, char **buffer)
179 {
180
181         assert(con);
182         if (!con->privileged) {
183                 errno = EACCES;
184                 return -1;
185         }
186         return dhcpcd_command_fd(con, con->command_fd, true, cmd, buffer);
187 }
188
189 static ssize_t
190 dhcpcd_ctrl_command(DHCPCD_CONNECTION *con, const char *cmd, char **buffer)
191 {
192
193         return dhcpcd_command_fd(con, con->command_fd, false, cmd, buffer);
194 }
195
196 bool
197 dhcpcd_realloc(DHCPCD_CONNECTION *con, size_t len)
198 {
199
200         assert(con);
201         if (con->buflen < len) {
202                 char *nbuf;
203
204                 nbuf = realloc(con->buf, len);
205                 if (nbuf == NULL)
206                         return false;
207                 con->buf = nbuf;
208                 con->buflen = len;
209         }
210         return true;
211 }
212
213 ssize_t
214 dhcpcd_command_arg(DHCPCD_CONNECTION *con, const char *cmd, const char *arg,
215     char **buffer)
216 {
217         size_t cmdlen, len;
218
219         assert(con);
220         assert(cmd);
221
222         cmdlen = strlen(cmd);
223         if (arg)
224                 len = cmdlen + strlen(arg) + 2;
225         else
226                 len = cmdlen + 1;
227         if (!dhcpcd_realloc(con, len))
228                 return -1;
229         strlcpy(con->buf, cmd, con->buflen);
230         if (arg) {
231                 con->buf[cmdlen] = ' ';
232                 strlcpy(con->buf + cmdlen + 1, arg, con->buflen - 1 - cmdlen);
233         }
234
235         return dhcpcd_command_fd(con, con->command_fd, true, con->buf, buffer);
236 }
237
238
239 static int
240 dhcpcd_connect(const char *path, int opts)
241 {
242         int fd;
243         socklen_t len;
244         struct sockaddr_un sun;
245
246         assert(path);
247         fd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | opts, 0);
248         if (fd == -1)
249                 return -1;
250
251         memset(&sun, 0, sizeof(sun));
252         sun.sun_family = AF_UNIX;
253         strlcpy(sun.sun_path, path, sizeof(sun.sun_path));
254         len = (socklen_t)SUN_LEN(&sun);
255         if (connect(fd, (struct sockaddr *)&sun, len) == 0)
256                 return fd;
257         close(fd);
258         return -1;
259 }
260
261 static const char *
262 get_value(const char *data, size_t len, const char *var)
263 {
264         const char *end, *p;
265         size_t vlen;
266
267         assert(var);
268         end = data + len;
269         vlen = strlen(var);
270         p = NULL;
271         while (data + vlen + 1 < end) {
272                 /* Skip past NUL padding */
273                 if (*data == '\0') {
274                         data++;
275                         continue;
276                 }
277                 if (strncmp(data, var, vlen) == 0 && data[vlen] == '=') {
278                         p = data + vlen + 1;
279                         break;
280                 }
281                 data += strlen(data) + 1;
282         }
283         if (p != NULL && *p != '\0')
284                 return p;
285         return NULL;
286 }
287
288 const char *
289 dhcpcd_get_value(const DHCPCD_IF *i, const char *var)
290 {
291
292         assert(i);
293         assert(var);
294         return get_value(i->data, i->data_len, var);
295 }
296
297 ssize_t
298 dhcpcd_encode_string_escape(char *dst, size_t len, const char *src, size_t slen)
299 {
300         const char *end;
301         size_t bytes;
302         unsigned char c;
303
304         end = src + slen;
305         bytes = 0;
306         while (src < end) {
307                 c = (unsigned char)*src++;
308                 if ((c == '\\' || !isascii(c) || !isprint(c))) {
309                         if (c == '\\') {
310                                 if (dst) {
311                                         if (len  == 0 || len == 1) {
312                                                 errno = ENOSPC;
313                                                 return -1;
314                                         }
315                                         *dst++ = '\\'; *dst++ = '\\';
316                                         len -= 2;
317                                 }
318                                 bytes += 2;
319                                 continue;
320                         }
321                         if (dst) {
322                                 if (len < 5) {
323                                         errno = ENOSPC;
324                                         return -1;
325                                 }
326                                 *dst++ = '\\';
327                                 *dst++ = (char)(((c >> 6) & 03) + '0');
328                                 *dst++ = (char)(((c >> 3) & 07) + '0');
329                                 *dst++ = (char)(( c       & 07) + '0');
330                                 len -= 4;
331                         }
332                         bytes += 4;
333                 } else {
334                         if (dst) {
335                                 if (len == 0) {
336                                         errno = ENOSPC;
337                                         return -1;
338                                 }
339                                 *dst++ = (char)c;
340                                 len--;
341                         }
342                         bytes++;
343                 }
344         }
345
346         if (dst) {
347                 if (len == 0) {
348                         errno = ENOSPC;
349                         return -1;
350                 }
351                 *dst = '\0';
352         }
353
354         return (ssize_t)bytes;
355 }
356
357 ssize_t
358 dhcpcd_decode_string_escape(char *dst, size_t dlen, const char *src)
359 {
360         char c, esc;
361         int oct;
362         ssize_t bytes;
363
364         bytes = 0;
365         for (;;) {
366                 c = *src++;
367                 if (c == '\0')
368                         break;
369                 if (dst && --dlen == 0) {
370                         errno = ENOSPC;
371                         return -1;
372                 }
373                 switch (c) {
374                 case '\\':
375                         if (*src == '\0') {
376                                 errno = EINVAL;
377                                 return -1;
378                         }
379                         esc = *src++;
380                         switch (esc) {
381                         case '\\':
382                         case '0':
383                         case '1':
384                         case '3':
385                         case '4':
386                         case '5':
387                         case '6':
388                         case '7':
389                                 oct = esc - '0';
390                                 if (*src >= '0' && *src <='7')
391                                         oct = oct * 8 + (*src++ - '0');
392                                 else {
393                                         errno = EINVAL;
394                                         return -1;
395                                 }
396                                 if (*src >= '0' && *src <='7')
397                                         oct = oct * 8 + (*src++ - '0');
398                                 else {
399                                         errno = EINVAL;
400                                         return -1;
401                                 }
402                                 if (dst)
403                                         *dst++ = (char)oct;
404                                 break;
405                         default:
406                                 errno = EINVAL;
407                                 return -1;
408                         }
409                         break;
410                 default:
411                         if (dst)
412                                 *dst++ = c;
413                 }
414                 bytes++;
415         }
416
417         if (dst) {
418                 if (--dlen == 0) {
419                         errno = ENOSPC;
420                         return -1;
421                 }
422                 *dst = '\0';
423         }
424         return bytes;
425 }
426
427 ssize_t
428 dhcpcd_decode_hex(char *dst, size_t dlen, const char *src)
429 {
430         size_t bytes, i;
431         char c;
432         int val, n;
433
434         bytes = 0;
435         while (*src) {
436                 if (dlen == 0 || dlen == 1) {
437                         errno = ENOSPC;
438                         return -1;
439                 }
440                 val = 0;
441                 for (i = 0; i < 2; i++) {
442                         c = *src++;
443                         if (c >= '0' && c <= '9')
444                                 n = c - '0';
445                         else if (c >= 'a' && c <= 'f')
446                                 n = 10 + c - 'a';
447                         else if (c >= 'A' && c <= 'F')
448                                 n = 10 + c - 'A';
449                         else {
450                                 errno = EINVAL;
451                                 return -1;
452                         }
453                         val = val * 16 + n;
454                 }
455                 *dst++ = (char)val;
456                 bytes += 2;
457                 dlen -= 2;
458                 if (*src == ':')
459                         src++;
460         }
461         return (ssize_t)bytes;
462 }
463
464 const char *
465 dhcpcd_get_prefix_value(const DHCPCD_IF *i, const char *prefix, const char *var)
466 {
467         char pvar[128], *p;
468         size_t plen, l;
469
470         assert(i);
471         assert(prefix);
472         assert(var);
473
474         p = pvar;
475         plen = sizeof(pvar);
476         l = strlcpy(p, prefix, plen);
477         if (l >= sizeof(pvar)) {
478                 errno = ENOBUFS;
479                 return NULL;
480         }
481         p += l;
482         plen -= l;
483         if (strlcpy(p, var, plen) >= plen) {
484                 errno = ENOBUFS;
485                 return NULL;
486         }
487         return dhcpcd_get_value(i, pvar);
488 }
489
490 static bool
491 strtobool(const char *var)
492 {
493
494         if (var == NULL)
495                 return false;
496
497          return (*var == '0' || *var == '\0' ||
498             strcmp(var, "false") == 0 ||
499             strcmp(var, "no") == 0) ? false : true;
500 }
501
502 static unsigned int
503 get_status(DHCPCD_CONNECTION *con)
504 {
505         DHCPCD_IF *i;
506         unsigned int status;
507
508         assert(con);
509         if (con->command_fd == -1)
510                 return DHC_DOWN;
511
512         if (con->listen_fd == -1)
513                 return DHC_OPENED;
514
515         if (con->interfaces == NULL)
516                 return DHC_INITIALISED;
517
518         status = DHC_DISCONNECTED;
519         for (i = con->interfaces; i; i = i->next) {
520                 if (i->up) {
521                         if (i->type == DHT_LINK) {
522                                 if (status == DHC_DISCONNECTED)
523                                         status = DHC_CONNECTING;
524                         } else {
525                                 if (con->af_waiting)
526                                         status = DHC_AF_WAITING;
527                                 else {
528                                         status = DHC_CONNECTED;
529                                         break;
530                                 }
531                         }
532                 }
533         }
534         return status;
535 }
536
537 static void
538 update_status(DHCPCD_CONNECTION *con, unsigned int nstatus)
539 {
540
541         assert(con);
542         if (nstatus == DHC_UNKNOWN)
543                 nstatus = get_status(con);
544         if (con->status != nstatus) {
545                 con->status = nstatus;
546                 if (con->status_cb)
547                         con->status_cb(con, con->status,
548                             dhcpcd_cstates[con->status], con->status_context);
549         }
550 }
551
552 DHCPCD_IF *
553 dhcpcd_interfaces(DHCPCD_CONNECTION *con)
554 {
555
556         assert(con);
557         return con->interfaces;
558 }
559
560 char **
561 dhcpcd_interface_names(DHCPCD_CONNECTION *con, size_t *nnames)
562 {
563         char **names;
564         size_t n;
565         DHCPCD_IF *i;
566
567         assert(con);
568         if (con->interfaces == NULL)
569                 return NULL;
570
571         n = 0;
572         for (i = con->interfaces; i; i = i->next) {
573                  if (i->type == DHT_LINK)
574                         n++;
575         }
576         names = malloc(sizeof(char *) * (n + 1));
577         if (names == NULL)
578                 return NULL;
579         n = 0;
580         for (i = con->interfaces; i; i = i->next) {
581                 if (i->type == DHT_LINK) {
582                         names[n] = strdup(i->ifname);
583                         if (names[n] == NULL) {
584                                 dhcpcd_freev(names);
585                                 return NULL;
586                         }
587                         n++;
588                 }
589         }
590         names[n] = NULL;
591         if (nnames)
592                 *nnames = n;
593
594         return names;
595 }
596
597 void
598 dhcpcd_freev(char **argv)
599 {
600         char **v;
601
602         if (argv) {
603                 for (v = argv; *v; v++)
604                         free(*v);
605                 free(argv);
606         }
607 }
608
609 static int
610 dhcpcd_cmpstring(const void *p1, const void *p2)
611 {
612         const char *s1, *s2;
613         int cmp;
614
615         s1 = *(char * const *)p1;
616         s2 = *(char * const *)p2;
617         if ((cmp = strcasecmp(s1, s2)) == 0)
618                 cmp = strcmp(s1, s2);
619         return cmp;
620 }
621
622 char **
623 dhcpcd_interface_names_sorted(DHCPCD_CONNECTION *con)
624 {
625         char **names;
626         size_t nnames;
627
628         names = dhcpcd_interface_names(con, &nnames);
629         if (names)
630                 qsort(names, nnames, sizeof(char *), dhcpcd_cmpstring);
631         return names;
632 }
633
634 DHCPCD_IF *
635 dhcpcd_get_if(DHCPCD_CONNECTION *con, const char *ifname, unsigned int type)
636 {
637         DHCPCD_IF *i;
638
639         assert(con);
640         assert(ifname);
641         assert(type);
642
643         for (i = con->interfaces; i; i = i->next)
644                 if (i->type == type && strcmp(i->ifname, ifname) == 0)
645                         return i;
646         return NULL;
647 }
648
649 static unsigned int
650 dhcpcd_reason_to_state1(const char *reason, int *isdhcp6)
651 {
652         unsigned int i;
653         char rbuf[32], *p;
654
655         assert(reason);
656
657         /* Take a copy of reason and trim 6 from the end
658          * so our DHCPv6 state can match DHCP states */
659         if (strlcpy(rbuf, reason, sizeof(rbuf)) >= sizeof(rbuf))
660                 return DHS_UNKNOWN;
661         p = rbuf + (strlen(rbuf) - 1);
662         if (*p == '6') {
663                 if (isdhcp6)
664                         *isdhcp6 = 1;
665                 *p = '\0';
666         } else if (isdhcp6)
667                 *isdhcp6 = 0;
668
669         for (i = 0; dhcpcd_states[i].val != DHS_UNKNOWN; i++) {
670                 if (strcmp(rbuf, dhcpcd_states[i].str) == 0)
671                         return dhcpcd_states[i].val;
672         }
673         return DHS_UNKNOWN;
674 }
675
676 static void
677 dhcpcd_reason_to_statetype(const char *reason,
678     unsigned int *state, unsigned int *type)
679 {
680         int isdhcp6;
681
682         assert(state);
683         assert(type);
684         *state = dhcpcd_reason_to_state1(reason, &isdhcp6);
685         switch (*state) {
686         case DHS_UNKNOWN:
687         case DHS_PREINIT:
688         case DHS_CARRIER:
689         case DHS_NOCARRIER:
690         case DHS_DEPARTED:
691         case DHS_STOPPED:
692                 *type = DHT_LINK;
693                 return;
694         case DHS_ROUTERADVERT:
695                 *type =  DHT_RA;
696                 return;
697         case DHS_IPV4LL:
698                 *type = DHT_IPV4LL;
699                 return;
700         case DHS_STATIC:
701                 if (isdhcp6) {
702                         *type = DHT_IPV6;
703                         return;
704                 }
705         }
706
707         if (isdhcp6)
708                 *type = DHT_DHCP6;
709         else
710                 *type = DHT_IPV4;
711 }
712
713 static DHCPCD_IF *
714 dhcpcd_new_if(DHCPCD_CONNECTION *con, char *data, size_t len)
715 {
716         const char *ifname, *ifclass, *reason, *order, *flags;
717         unsigned int state, type;
718         char *orderdup, *o, *p;
719         DHCPCD_IF *e, *i, *l, *n, *nl;
720         bool addedi;
721
722 #if 0
723         char *dp = data, *de = data + len;
724         while (dp < de) {
725                 printf ("XX: %s\n", dp);
726                 dp += strlen(dp) + 1;
727         }
728 #endif
729
730         ifname = get_value(data, len, "interface");
731         if (ifname == NULL || *ifname == '\0') {
732                 errno = ESRCH;
733                 return NULL;
734         }
735         reason = get_value(data, len, "reason");
736         if (reason == NULL || *reason == '\0') {
737                 errno = ESRCH;
738                 return NULL;
739         }
740         dhcpcd_reason_to_statetype(reason, &state, &type);
741
742         ifclass = get_value(data, len, "ifclass");
743         /* Skip pseudo interfaces */
744         if (ifclass && *ifclass != '\0') {
745                 errno = ENOTSUP;
746                 return NULL;
747         }
748         if (state == DHS_RECONFIGURE || state == DHS_INFORM) {
749                 errno = ENOTSUP;
750                 return NULL;
751         }
752         order = get_value(data, len, "interface_order");
753         if (order == NULL || *order == '\0') {
754                 errno = ESRCH;
755                 return NULL;
756         }
757
758         i = NULL;
759        /* Remove all instances on carrier drop */
760         if (state == DHS_NOCARRIER ||
761             state == DHS_DEPARTED || state == DHS_STOPPED)
762         {
763                 l = NULL;
764                 for (e = con->interfaces; e; e = n) {
765                         n = e->next;
766                         if (strcmp(e->ifname, ifname) == 0) {
767                                 if (e->type == type)
768                                         l = i = e;
769                                 else {
770                                         if (l)
771                                                 l->next = e->next;
772                                         else
773                                                 con->interfaces = e->next;
774                                         free(e);
775                                 }
776                         } else
777                                 l = e;
778                 }
779         } else if (type != DHT_LINK) {
780                 /* If link is down, ignore it */
781                 e = dhcpcd_get_if(con, ifname, DHT_LINK);
782                 if (e && !e->up)
783                         return NULL;
784         }
785
786         orderdup = strdup(order);
787         if (orderdup == NULL)
788                 return NULL;
789
790         /* Find our pointer */
791         if (i == NULL) {
792                 l = NULL;
793                 for (e = con->interfaces; e; e = e->next) {
794                         if (e->type == type && strcmp(e->ifname, ifname) == 0) {
795                                 i = e;
796                                 break;
797                         }
798                         l = e;
799                 }
800         }
801         if (i == NULL) {
802                 i = malloc(sizeof(*i));
803                 if (i == NULL) {
804                         free(orderdup);
805                         return NULL;
806                 }
807                 if (l)
808                         l->next = i;
809                 else
810                         con->interfaces = i;
811                 i->next = NULL;
812                 i->last_message = NULL;
813         } else
814                 free(i->data);
815
816         /* Now fill out our interface structure */
817         i->con = con;
818         i->data = data;
819         i->data_len = len;
820         i->ifname = ifname;
821         i->type = type;
822         i->state = state;
823         i->reason = reason;
824         flags = dhcpcd_get_value(i, "ifflags");
825         if (flags)
826                 i->ifflags = (unsigned int)strtoul(flags, NULL, 0);
827         else
828                 i->ifflags = 0;
829         if (state == DHS_CARRIER || state == DHS_DELEGATED)
830                 i->up = true;
831         else
832                 i->up = strtobool(dhcpcd_get_value(i, "if_up"));
833         i->wireless = strtobool(dhcpcd_get_value(i, "ifwireless"));
834         i->ssid = dhcpcd_get_value(i, "ifssid");
835         i->freq = 0; /* wpa_supplicant will set this when opened */
836         if (i->ssid == NULL && i->wireless)
837                 i->ssid = dhcpcd_get_value(i, i->up ? "new_ssid" : "old_ssid");
838
839         /* Work out if we're waiting for any other addresses */
840         if (dhcpcd_get_value(i, "af_waiting") == NULL)
841                 con->af_waiting = false;
842         else
843                 con->af_waiting = true;
844
845        /* Sort! */
846         n = nl = NULL;
847         p = orderdup;
848         addedi = false;
849         while ((o = strsep(&p, " ")) != NULL) {
850                 for (type = 0; type < DHT_MAX; type++) {
851                         l = NULL;
852                         for (e = con->interfaces; e; e = e->next) {
853                                 if (e->type == type && strcmp(e->ifname, o) == 0)
854                                         break;
855                                 l = e;
856                         }
857                         if (e == NULL)
858                                 continue;
859                         if (i == e)
860                                 addedi = true;
861                         if (l)
862                                 l->next = e->next;
863                         else
864                                 con->interfaces = e->next;
865                         e->next = NULL;
866                         if (nl == NULL)
867                                 n = nl = e;
868                         else {
869                                 nl->next = e;
870                                 nl = e;
871                         }
872                 }
873         }
874         free(orderdup);
875         /* Free any stragglers */
876         while (con->interfaces) {
877                 e = con->interfaces->next;
878                 free(con->interfaces->data);
879                 free(con->interfaces->last_message);
880                 free(con->interfaces);
881                 con->interfaces = e;
882         }
883         con->interfaces = n;
884
885         return addedi ? i : NULL;
886 }
887
888 static DHCPCD_IF *
889 dhcpcd_read_if(DHCPCD_CONNECTION *con, int fd)
890 {
891         char sbuf[sizeof(size_t)], *rbuf;
892         size_t len;
893         ssize_t bytes;
894         DHCPCD_IF *i;
895
896         bytes = read(fd, sbuf, sizeof(sbuf));
897         if (bytes == 0 || bytes == -1) {
898                 dhcpcd_close(con);
899                 return NULL;
900         }
901         memcpy(&len, sbuf, sizeof(len));
902         rbuf = malloc(len + 1);
903         if (rbuf == NULL)
904                 return NULL;
905         bytes = read(fd, rbuf, len);
906         if (bytes == 0 || bytes == -1) {
907                 free(rbuf);
908                 dhcpcd_close(con);
909                 return NULL;
910         }
911         if ((size_t)bytes != len) {
912                 free(rbuf);
913                 errno = EINVAL;
914                 return NULL;
915         }
916         rbuf[bytes] = '\0';
917
918         i = dhcpcd_new_if(con, rbuf, len);
919         if (i == NULL)
920                 free(rbuf);
921         return i;
922 }
923
924 static void
925 dhcpcd_dispatchif(DHCPCD_IF *i)
926 {
927
928         assert(i);
929         if (i->con->if_cb)
930                 i->con->if_cb(i, i->con->if_context);
931         dhcpcd_wpa_if_event(i);
932 }
933
934 void
935 dhcpcd_dispatch(DHCPCD_CONNECTION *con)
936 {
937         DHCPCD_IF *i;
938
939         assert(con);
940         i = dhcpcd_read_if(con, con->listen_fd);
941
942         if (i)
943                 dhcpcd_dispatchif(i);
944
945         /* Have to call update_status last as it could
946          * cause the interface to be destroyed. */
947         update_status(con, DHC_UNKNOWN);
948 }
949
950 DHCPCD_CONNECTION *
951 dhcpcd_new(void)
952 {
953         DHCPCD_CONNECTION *con;
954
955         con = calloc(1, sizeof(*con));
956         con->command_fd = con->listen_fd = -1;
957         con->open = false;
958         con->progname = "libdhcpcd";
959         con->af_waiting = false;
960         return con;
961 }
962
963 void
964 dhcpcd_set_progname(DHCPCD_CONNECTION *con, const char *progname)
965 {
966
967         assert(con);
968         con->progname = progname;
969 }
970
971 const char *
972 dhcpcd_get_progname(const DHCPCD_CONNECTION *con)
973 {
974
975         assert(con);
976         return con->progname;
977 }
978
979 #ifndef HAVE_STRVERSCMP
980 /* Good enough for our needs */
981 static int
982 strverscmp(const char *s1, const char *s2)
983 {
984         int s1maj, s1min, s1part;
985         int s2maj, s2min, s2part;
986         int r;
987
988         s1min = s1part = 0;
989         if (sscanf(s1, "%d.%d.%d", &s1maj, &s1min, &s1part) < 1)
990                 return -1;
991         s2min = s2part = 0;
992         if (sscanf(s2, "%d.%d.%d", &s2maj, &s2min, &s2part) < 1)
993                 return -1;
994         r = s1maj - s2maj;
995         if (r != 0)
996                 return r;
997         r = s1min - s2min;
998         if (r != 0)
999                 return r;
1000         return s1part - s2part;
1001 }
1002 #endif
1003
1004 int
1005 dhcpcd_open(DHCPCD_CONNECTION *con, bool privileged)
1006 {
1007         const char *path = privileged ? DHCPCD_SOCKET : DHCPCD_UNPRIV_SOCKET;
1008         char cmd[128];
1009         ssize_t bytes;
1010         size_t nifs, n;
1011
1012         assert(con);
1013         if (con->open) {
1014                 if (con->listen_fd != -1)
1015                         return con->listen_fd;
1016                 errno = EISCONN;
1017                 return -1;
1018         }
1019         /* We need to block the command fd */
1020         con->command_fd = dhcpcd_connect(path, 0);
1021         if (con->command_fd == -1)
1022                 goto err_exit;
1023
1024         con->terminate_commands = false;
1025         if (dhcpcd_ctrl_command(con, "--version", &con->version) <= 0)
1026                 goto err_exit;
1027         con->terminate_commands =
1028             strverscmp(con->version, "6.4.1") >= 0 ? true : false;
1029
1030         if (dhcpcd_ctrl_command(con, "--getconfigfile", &con->cffile) <= 0)
1031                 goto err_exit;
1032
1033         con->open = true;
1034         con->privileged = privileged;
1035         update_status(con, DHC_UNKNOWN);
1036
1037         con->listen_fd = dhcpcd_connect(path, SOCK_NONBLOCK);
1038         if (con->listen_fd == -1)
1039                 goto err_exit;
1040
1041         dhcpcd_command_fd(con, con->listen_fd, false, "--listen", NULL);
1042         dhcpcd_command_fd(con, con->command_fd, false, "--getinterfaces", NULL);
1043         bytes = read(con->command_fd, cmd, sizeof(nifs));
1044         if (bytes != sizeof(nifs))
1045                 goto err_exit;
1046         memcpy(&nifs, cmd, sizeof(nifs));
1047         /* We don't dispatch each interface here as that
1048          * causes too much notification spam when the GUI starts */
1049         for (n = 0; n < nifs; n++)
1050                 dhcpcd_read_if(con, con->command_fd);
1051
1052         update_status(con, DHC_UNKNOWN);
1053
1054         return con->listen_fd;
1055
1056 err_exit:
1057         dhcpcd_close(con);
1058         return -1;
1059 }
1060
1061 int
1062 dhcpcd_get_fd(DHCPCD_CONNECTION *con)
1063 {
1064
1065         assert(con);
1066         return con->listen_fd;
1067 }
1068
1069 bool
1070 dhcpcd_privileged(DHCPCD_CONNECTION *con)
1071 {
1072
1073         assert(con);
1074         return con->privileged;
1075 }
1076
1077 unsigned int
1078 dhcpcd_status(DHCPCD_CONNECTION *con, const char **status)
1079 {
1080
1081         assert(con);
1082         if (status)
1083                 *status = dhcpcd_cstates[con->status];
1084         return con->status;
1085 }
1086
1087 bool
1088 dhcpcd_af_waiting(const DHCPCD_CONNECTION *con)
1089 {
1090
1091         assert(con);
1092         return con->af_waiting;
1093 }
1094
1095 const char *
1096 dhcpcd_version(DHCPCD_CONNECTION *con)
1097 {
1098
1099         assert(con);
1100         return con->version;
1101 }
1102
1103 const char *
1104 dhcpcd_cffile(DHCPCD_CONNECTION *con)
1105 {
1106
1107         assert(con);
1108         return con->cffile;
1109 }
1110
1111 void
1112 dhcpcd_set_if_callback(DHCPCD_CONNECTION *con,
1113     void (*cb)(DHCPCD_IF *, void *), void *ctx)
1114 {
1115
1116         assert(con);
1117         con->if_cb = cb;
1118         con->if_context = ctx;
1119 }
1120
1121 void
1122 dhcpcd_set_status_callback(DHCPCD_CONNECTION *con,
1123     void (*cb)(DHCPCD_CONNECTION *, unsigned int, const char *, void *),
1124     void *ctx)
1125 {
1126
1127         assert(con);
1128         con->status_cb = cb;
1129         con->status_context = ctx;
1130 }
1131
1132 void
1133 dhcpcd_close(DHCPCD_CONNECTION *con)
1134 {
1135         DHCPCD_IF *nif;
1136         DHCPCD_WPA *nwpa;
1137         DHCPCD_WI_HIST *nh;
1138
1139         assert(con);
1140
1141         if (con->open) {
1142                 if (con->command_fd != -1)
1143                         shutdown(con->command_fd, SHUT_RDWR);
1144                 if (con->listen_fd != -1)
1145                         shutdown(con->listen_fd, SHUT_RDWR);
1146                 con->open = false;
1147         }
1148
1149         /* Shut down WPA listeners as they aren't much good without dhcpcd.
1150          * They'll be restarted anyway when dhcpcd comes back up. */
1151         while (con->wpa) {
1152                 nwpa = con->wpa->next;
1153                 dhcpcd_wpa_close(con->wpa);
1154                 free(con->wpa);
1155                 con->wpa = nwpa;
1156         }
1157         while (con->wi_history) {
1158                 nh = con->wi_history->next;
1159                 free(con->wi_history);
1160                 con->wi_history = nh;
1161         }
1162         while (con->interfaces) {
1163                 nif = con->interfaces->next;
1164                 free(con->interfaces->data);
1165                 free(con->interfaces->last_message);
1166                 free(con->interfaces);
1167                 con->interfaces = nif;
1168         }
1169
1170         update_status(con, DHC_DOWN);
1171
1172         if (con->command_fd != -1) {
1173                 close(con->command_fd);
1174                 con->command_fd = -1;
1175         }
1176         if (con->listen_fd != -1) {
1177                 close(con->listen_fd);
1178                 con->listen_fd = -1;
1179         }
1180
1181         if (con->cffile) {
1182                 free(con->cffile);
1183                 con->cffile = NULL;
1184         }
1185         if (con->version) {
1186                 free(con->version);
1187                 con->version = NULL;
1188         }
1189         if (con->buf) {
1190                 free(con->buf);
1191                 con->buf = NULL;
1192                 con->buflen = 0;
1193         }
1194 }
1195
1196 void
1197 dhcpcd_free(DHCPCD_CONNECTION *con)
1198 {
1199
1200         assert(con);
1201         free(con);
1202 }
1203
1204 DHCPCD_CONNECTION *
1205 dhcpcd_if_connection(DHCPCD_IF *i)
1206 {
1207
1208         assert(i);
1209         return i->con;
1210 }
1211
1212 char *
1213 dhcpcd_if_message(DHCPCD_IF *i, bool *new_msg)
1214 {
1215         const char *ip, *iplen, *pfx;
1216         char *msg, *p;
1217         const char *reason = NULL;
1218         size_t len;
1219         bool showssid;
1220
1221         assert(i);
1222         /* Don't report non SLAAC configurations */
1223         if (i->type == DHT_RA && i->up &&
1224             dhcpcd_get_value(i, "nd1_addr1") == NULL &&
1225             dhcpcd_get_value(i, "ra1_prefix") == NULL)
1226                 return NULL;
1227
1228         showssid = false;
1229         switch (i->state) {
1230         case DHS_EXPIRE:
1231                 reason = _("Expired");
1232                 break;
1233         case DHS_CARRIER:
1234                 if (i->wireless) {
1235                         showssid = true;
1236                         reason = _("Associated with");
1237                 } else {
1238                         /* Don't report able in if we have addresses */
1239                         const DHCPCD_IF *ci;
1240
1241                         for (ci = i->con->interfaces; ci; ci = ci->next) {
1242                                 if (ci != i &&
1243                                     strcmp(i->ifname, ci->ifname) == 0 &&
1244                                     ci->up)
1245                                         break;
1246                         }
1247                         if (ci)
1248                                 return NULL;
1249                         reason = _("Link is up, configuring");
1250                 }
1251                 break;
1252         case DHS_NOCARRIER:
1253                 if (i->wireless) {
1254                         if (i->ssid) {
1255                                 reason = _("Disassociated from");
1256                                 showssid = true;
1257                         } else
1258                                 reason = _("Not associated");
1259                 } else
1260                         reason = _("Link is down");
1261                 break;
1262         case DHS_DEPARTED:
1263                 reason = _("Departed");
1264                 break;
1265         case DHS_UNKNOWN:
1266                 reason = _("Unknown link state");
1267                 break;
1268         case DHS_FAIL:
1269                 reason = _("Automatic configuration not possible");
1270                 break;
1271         case DHS_3RDPARTY:
1272                 reason = _("Waiting for 3rd Party configuration");
1273                 break;
1274         }
1275
1276         if (reason == NULL) {
1277                 if (i->up) {
1278                         if (i->state == DHS_DELEGATED)
1279                                 reason = _("Delegated");
1280                         else
1281                                 reason = _("Configured");
1282                 } else if (i->type == DHT_RA)
1283                         reason = "Expired RA";
1284                 else if (i->type == DHT_IPV4LL)
1285                         reason = "Expired IPv4LL";
1286                 else
1287                         reason = i->reason;
1288         }
1289
1290         pfx = i->up ? "new_" : "old_";
1291         if ((ip = dhcpcd_get_prefix_value(i, pfx, "ip_address")))
1292                 iplen = dhcpcd_get_prefix_value(i, pfx, "subnet_cidr");
1293         else if ((ip = dhcpcd_get_value(i, "nd1_addr1")))
1294                 iplen = NULL;
1295         else if ((ip = dhcpcd_get_value(i, "ra1_addr")))
1296                 iplen = NULL;
1297         else if ((ip = dhcpcd_get_value(i, "ra1_prefix")))
1298                 iplen = NULL;
1299         else if ((ip = dhcpcd_get_prefix_value(i, pfx,
1300             "dhcp6_ia_na1_ia_addr1")))
1301                 iplen = "128";
1302         else if ((ip = dhcpcd_get_prefix_value(i, pfx,
1303             "delegated_dhcp6_prefix")))
1304                 iplen = NULL;
1305         else if ((ip = dhcpcd_get_prefix_value(i, pfx, "ip6_address")))
1306                 iplen = NULL;
1307         else {
1308                 ip = NULL;
1309                 iplen = NULL;
1310         }
1311
1312         len = strlen(i->ifname) + strlen(reason) + 3;
1313         if (showssid && i->ssid)
1314                 len += strlen(i->ssid) + 1;
1315         if (ip)
1316                 len += strlen(ip) + 1;
1317         if (iplen)
1318                 len += strlen(iplen) + 1;
1319         msg = p = malloc(len);
1320         if (msg == NULL)
1321                 return NULL;
1322         p += snprintf(msg, len, "%s: %s", i->ifname, reason);
1323         if (showssid)
1324                 p += snprintf(p, len - (size_t)(p - msg), " %s", i->ssid);
1325         if (iplen)
1326                 snprintf(p, len - (size_t)(p - msg), " %s/%s", ip, iplen);
1327         else if (ip)
1328                 snprintf(p, len - (size_t)(p - msg), " %s", ip);
1329
1330         if (new_msg) {
1331                 if (i->last_message == NULL || strcmp(i->last_message, msg))
1332                         *new_msg = true;
1333                 else
1334                         *new_msg = false;
1335         }
1336         free(i->last_message);
1337         i->last_message = strdup(msg);
1338
1339         return msg;
1340 }