Add the IPv4LL type.
[dhcpcd-ui] / src / libdhcpcd / dhcpcd.c
1 /*
2  * libdhcpcd
3  * Copyright 2009-2015 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                         default:
405                                 errno = EINVAL;
406                                 return -1;
407                         }
408                         break;
409                 default:
410                         if (dst)
411                                 *dst++ = c;
412                 }
413                 bytes++;
414         }
415
416         if (dst) {
417                 if (--dlen == 0) {
418                         errno = ENOSPC;
419                         return -1;
420                 }
421                 *dst = '\0';
422         }
423         return bytes;
424 }
425
426 ssize_t
427 dhcpcd_decode_hex(char *dst, size_t dlen, const char *src)
428 {
429         size_t bytes, i;
430         char c;
431         int val, n;
432
433         bytes = 0;
434         while (*src) {
435                 if (dlen == 0 || dlen == 1) {
436                         errno = ENOSPC;
437                         return -1;
438                 }
439                 val = 0;
440                 for (i = 0; i < 2; i++) {
441                         c = *src++;
442                         if (c >= '0' && c <= '9')
443                                 n = c - '0';
444                         else if (c >= 'a' && c <= 'f')
445                                 n = 10 + c - 'a';
446                         else if (c >= 'A' && c <= 'F')
447                                 n = 10 + c - 'A';
448                         else {
449                                 errno = EINVAL;
450                                 return -1;
451                         }
452                         val = val * 16 + n;
453                 }
454                 *dst++ = (char)val;
455                 bytes += 2;
456                 dlen -= 2;
457                 if (*src == ':')
458                         src++;
459         }
460         return (ssize_t)bytes;
461 }
462
463 const char *
464 dhcpcd_get_prefix_value(const DHCPCD_IF *i, const char *prefix, const char *var)
465 {
466         char pvar[128], *p;
467         size_t plen, l;
468
469         assert(i);
470         assert(prefix);
471         assert(var);
472
473         p = pvar;
474         plen = sizeof(pvar);
475         l = strlcpy(p, prefix, plen);
476         if (l >= sizeof(pvar)) {
477                 errno = ENOBUFS;
478                 return NULL;
479         }
480         p += l;
481         plen -= l;
482         if (strlcpy(p, var, plen) >= plen) {
483                 errno = ENOBUFS;
484                 return NULL;
485         }
486         return dhcpcd_get_value(i, pvar);
487 }
488
489 static bool
490 strtobool(const char *var)
491 {
492
493         if (var == NULL)
494                 return false;
495
496          return (*var == '0' || *var == '\0' ||
497             strcmp(var, "false") == 0 ||
498             strcmp(var, "no") == 0) ? false : true;
499 }
500
501 static unsigned int
502 get_status(DHCPCD_CONNECTION *con)
503 {
504         DHCPCD_IF *i;
505         unsigned int status;
506
507         assert(con);
508         if (con->command_fd == -1)
509                 return DHC_DOWN;
510
511         if (con->listen_fd == -1)
512                 return DHC_OPENED;
513
514         if (con->interfaces == NULL)
515                 return DHC_INITIALISED;
516
517         status = DHC_DISCONNECTED;
518         for (i = con->interfaces; i; i = i->next) {
519                 if (i->up) {
520                         if (i->type == DHT_LINK) {
521                                 if (status == DHC_DISCONNECTED)
522                                         status = DHC_CONNECTING;
523                         } else {
524                                 if (con->af_waiting)
525                                         status = DHC_AF_WAITING;
526                                 else {
527                                         status = DHC_CONNECTED;
528                                         break;
529                                 }
530                         }
531                 }
532         }
533         return status;
534 }
535
536 static void
537 update_status(DHCPCD_CONNECTION *con, unsigned int nstatus)
538 {
539
540         assert(con);
541         if (nstatus == DHC_UNKNOWN)
542                 nstatus = get_status(con);
543         if (con->status != nstatus) {
544                 con->status = nstatus;
545                 if (con->status_cb)
546                         con->status_cb(con, con->status,
547                             dhcpcd_cstates[con->status], con->status_context);
548         }
549 }
550
551 DHCPCD_IF *
552 dhcpcd_interfaces(DHCPCD_CONNECTION *con)
553 {
554
555         assert(con);
556         return con->interfaces;
557 }
558
559 char **
560 dhcpcd_interface_names(DHCPCD_CONNECTION *con, size_t *nnames)
561 {
562         char **names;
563         size_t n;
564         DHCPCD_IF *i;
565
566         assert(con);
567         if (con->interfaces == NULL)
568                 return NULL;
569
570         n = 0;
571         for (i = con->interfaces; i; i = i->next) {
572                  if (i->type == DHT_LINK)
573                         n++;
574         }
575         names = malloc(sizeof(char *) * (n + 1));
576         if (names == NULL)
577                 return NULL;
578         n = 0;
579         for (i = con->interfaces; i; i = i->next) {
580                 if (i->type == DHT_LINK) {
581                         names[n] = strdup(i->ifname);
582                         if (names[n] == NULL) {
583                                 dhcpcd_freev(names);
584                                 return NULL;
585                         }
586                         n++;
587                 }
588         }
589         names[n] = NULL;
590         if (nnames)
591                 *nnames = n;
592
593         return names;
594 }
595
596 void
597 dhcpcd_freev(char **argv)
598 {
599         char **v;
600
601         if (argv) {
602                 for (v = argv; *v; v++)
603                         free(*v);
604                 free(argv);
605         }
606 }
607
608 static int
609 dhcpcd_cmpstring(const void *p1, const void *p2)
610 {
611         const char *s1, *s2;
612         int cmp;
613
614         s1 = *(char * const *)p1;
615         s2 = *(char * const *)p2;
616         if ((cmp = strcasecmp(s1, s2)) == 0)
617                 cmp = strcmp(s1, s2);
618         return cmp;
619 }
620
621 char **
622 dhcpcd_interface_names_sorted(DHCPCD_CONNECTION *con)
623 {
624         char **names;
625         size_t nnames;
626
627         names = dhcpcd_interface_names(con, &nnames);
628         if (names)
629                 qsort(names, nnames, sizeof(char *), dhcpcd_cmpstring);
630         return names;
631 }
632
633 DHCPCD_IF *
634 dhcpcd_get_if(DHCPCD_CONNECTION *con, const char *ifname, unsigned int type)
635 {
636         DHCPCD_IF *i;
637
638         assert(con);
639         assert(ifname);
640         assert(type);
641
642         for (i = con->interfaces; i; i = i->next)
643                 if (i->type == type && strcmp(i->ifname, ifname) == 0)
644                         return i;
645         return NULL;
646 }
647
648 static unsigned int
649 dhcpcd_reason_to_state1(const char *reason, int *isdhcp6)
650 {
651         unsigned int i;
652         char rbuf[32], *p;
653
654         assert(reason);
655
656         /* Take a copy of reason and trim 6 from the end
657          * so our DHCPv6 state can match DHCP states */
658         if (strlcpy(rbuf, reason, sizeof(rbuf)) >= sizeof(rbuf))
659                 return DHS_UNKNOWN;
660         p = rbuf + (strlen(rbuf) - 1);
661         if (*p == '6') {
662                 if (isdhcp6)
663                         *isdhcp6 = 1;
664                 *p = '\0';
665         } else if (isdhcp6)
666                 *isdhcp6 = 0;
667
668         for (i = 0; dhcpcd_states[i].val != DHS_UNKNOWN; i++) {
669                 if (strcmp(rbuf, dhcpcd_states[i].str) == 0)
670                         return dhcpcd_states[i].val;
671         }
672         return DHS_UNKNOWN;
673 }
674
675 static void
676 dhcpcd_reason_to_statetype(const char *reason,
677     unsigned int *state, unsigned int *type)
678 {
679         int isdhcp6;
680
681         assert(state);
682         assert(type);
683         *state = dhcpcd_reason_to_state1(reason, &isdhcp6);
684         switch (*state) {
685         case DHS_UNKNOWN:
686         case DHS_PREINIT:
687         case DHS_CARRIER:
688         case DHS_NOCARRIER:
689         case DHS_DEPARTED:
690         case DHS_STOPPED:
691                 *type = DHT_LINK;
692                 return;
693         case DHS_ROUTERADVERT:
694                 *type =  DHT_RA;
695                 return;
696         case DHS_IPV4LL:
697                 *type = DHT_IPV4LL;
698                 return;
699         }
700
701         if (isdhcp6)
702                 *type = DHT_DHCP6;
703         else
704                 *type = DHT_IPV4;
705 }
706
707 static DHCPCD_IF *
708 dhcpcd_new_if(DHCPCD_CONNECTION *con, char *data, size_t len)
709 {
710         const char *ifname, *ifclass, *reason, *order, *flags;
711         unsigned int state, type;
712         char *orderdup, *o, *p;
713         DHCPCD_IF *e, *i, *l, *n, *nl;
714         bool addedi;
715
716 #if 0
717         char *dp = data, *de = data + len;
718         while (dp < de) {
719                 printf ("XX: %s\n", dp);
720                 dp += strlen(dp) + 1;
721         }
722 #endif
723
724         ifname = get_value(data, len, "interface");
725         if (ifname == NULL || *ifname == '\0') {
726                 errno = ESRCH;
727                 return NULL;
728         }
729         reason = get_value(data, len, "reason");
730         if (reason == NULL || *reason == '\0') {
731                 errno = ESRCH;
732                 return NULL;
733         }
734         dhcpcd_reason_to_statetype(reason, &state, &type);
735
736         ifclass = get_value(data, len, "ifclass");
737         /* Skip pseudo interfaces */
738         if (ifclass && *ifclass != '\0') {
739                 errno = ENOTSUP;
740                 return NULL;
741         }
742         if (state == DHS_RECONFIGURE || state == DHS_INFORM) {
743                 errno = ENOTSUP;
744                 return NULL;
745         }
746         order = get_value(data, len, "interface_order");
747         if (order == NULL || *order == '\0') {
748                 errno = ESRCH;
749                 return NULL;
750         }
751
752         i = NULL;
753        /* Remove all instances on carrier drop */
754         if (state == DHS_NOCARRIER ||
755             state == DHS_DEPARTED || state == DHS_STOPPED)
756         {
757                 l = NULL;
758                 for (e = con->interfaces; e; e = n) {
759                         n = e->next;
760                         if (strcmp(e->ifname, ifname) == 0) {
761                                 if (e->type == type)
762                                         l = i = e;
763                                 else {
764                                         if (l)
765                                                 l->next = e->next;
766                                         else
767                                                 con->interfaces = e->next;
768                                         free(e);
769                                 }
770                         } else
771                                 l = e;
772                 }
773         } else if (type != DHT_LINK) {
774                 /* If link is down, ignore it */
775                 e = dhcpcd_get_if(con, ifname, DHT_LINK);
776                 if (e && !e->up)
777                         return NULL;
778         }
779
780         orderdup = strdup(order);
781         if (orderdup == NULL)
782                 return NULL;
783
784         /* Find our pointer */
785         if (i == NULL) {
786                 l = NULL;
787                 for (e = con->interfaces; e; e = e->next) {
788                         if (e->type == type && strcmp(e->ifname, ifname) == 0) {
789                                 i = e;
790                                 break;
791                         }
792                         l = e;
793                 }
794         }
795         if (i == NULL) {
796                 i = malloc(sizeof(*i));
797                 if (i == NULL) {
798                         free(orderdup);
799                         return NULL;
800                 }
801                 if (l)
802                         l->next = i;
803                 else
804                         con->interfaces = i;
805                 i->next = NULL;
806                 i->last_message = NULL;
807         } else
808                 free(i->data);
809
810         /* Now fill out our interface structure */
811         i->con = con;
812         i->data = data;
813         i->data_len = len;
814         i->ifname = ifname;
815         i->type = type;
816         i->state = state;
817         i->reason = reason;
818         flags = dhcpcd_get_value(i, "ifflags");
819         if (flags)
820                 i->ifflags = (unsigned int)strtoul(flags, NULL, 0);
821         else
822                 i->ifflags = 0;
823         if (state == DHS_CARRIER || state == DHS_DELEGATED)
824                 i->up = true;
825         else
826                 i->up = strtobool(dhcpcd_get_value(i, "if_up"));
827         i->wireless = strtobool(dhcpcd_get_value(i, "ifwireless"));
828         i->ssid = dhcpcd_get_value(i, "ifssid");
829         if (i->ssid == NULL && i->wireless)
830                 i->ssid = dhcpcd_get_value(i, i->up ? "new_ssid" : "old_ssid");
831
832         /* Work out if we're waiting for any other addresses */
833         if (dhcpcd_get_value(i, "af_waiting") == NULL)
834                 con->af_waiting = false;
835         else
836                 con->af_waiting = true;
837
838        /* Sort! */
839         n = nl = NULL;
840         p = orderdup;
841         addedi = false;
842         while ((o = strsep(&p, " ")) != NULL) {
843                 for (type = 0; type < DHT_MAX; type++) {
844                         l = NULL;
845                         for (e = con->interfaces; e; e = e->next) {
846                                 if (e->type == type && strcmp(e->ifname, o) == 0)
847                                         break;
848                                 l = e;
849                         }
850                         if (e == NULL)
851                                 continue;
852                         if (i == e)
853                                 addedi = true;
854                         if (l)
855                                 l->next = e->next;
856                         else
857                                 con->interfaces = e->next;
858                         e->next = NULL;
859                         if (nl == NULL)
860                                 n = nl = e;
861                         else {
862                                 nl->next = e;
863                                 nl = e;
864                         }
865                 }
866         }
867         free(orderdup);
868         /* Free any stragglers */
869         while (con->interfaces) {
870                 e = con->interfaces->next;
871                 free(con->interfaces->data);
872                 free(con->interfaces->last_message);
873                 free(con->interfaces);
874                 con->interfaces = e;
875         }
876         con->interfaces = n;
877
878         return addedi ? i : NULL;
879 }
880
881 static DHCPCD_IF *
882 dhcpcd_read_if(DHCPCD_CONNECTION *con, int fd)
883 {
884         char sbuf[sizeof(size_t)], *rbuf;
885         size_t len;
886         ssize_t bytes;
887         DHCPCD_IF *i;
888
889         bytes = read(fd, sbuf, sizeof(sbuf));
890         if (bytes == 0 || bytes == -1) {
891                 dhcpcd_close(con);
892                 return NULL;
893         }
894         memcpy(&len, sbuf, sizeof(len));
895         rbuf = malloc(len + 1);
896         if (rbuf == NULL)
897                 return NULL;
898         bytes = read(fd, rbuf, len);
899         if (bytes == 0 || bytes == -1) {
900                 free(rbuf);
901                 dhcpcd_close(con);
902                 return NULL;
903         }
904         if ((size_t)bytes != len) {
905                 free(rbuf);
906                 errno = EINVAL;
907                 return NULL;
908         }
909         rbuf[bytes] = '\0';
910
911         i = dhcpcd_new_if(con, rbuf, len);
912         if (i == NULL)
913                 free(rbuf);
914         return i;
915 }
916
917 static void
918 dhcpcd_dispatchif(DHCPCD_IF *i)
919 {
920
921         assert(i);
922         if (i->con->if_cb)
923                 i->con->if_cb(i, i->con->if_context);
924         dhcpcd_wpa_if_event(i);
925 }
926
927 void
928 dhcpcd_dispatch(DHCPCD_CONNECTION *con)
929 {
930         DHCPCD_IF *i;
931
932         assert(con);
933         i = dhcpcd_read_if(con, con->listen_fd);
934         if (i)
935                 dhcpcd_dispatchif(i);
936
937         /* Have to call update_status last as it could
938          * cause the interface to be destroyed. */
939         update_status(con, DHC_UNKNOWN);
940 }
941
942 DHCPCD_CONNECTION *
943 dhcpcd_new(void)
944 {
945         DHCPCD_CONNECTION *con;
946
947         con = calloc(1, sizeof(*con));
948         con->command_fd = con->listen_fd = -1;
949         con->open = false;
950         con->progname = "libdhcpcd";
951         con->af_waiting = false;
952         return con;
953 }
954
955 void
956 dhcpcd_set_progname(DHCPCD_CONNECTION *con, const char *progname)
957 {
958
959         assert(con);
960         con->progname = progname;
961 }
962
963 const char *
964 dhcpcd_get_progname(const DHCPCD_CONNECTION *con)
965 {
966
967         assert(con);
968         return con->progname;
969 }
970
971 #ifndef HAVE_STRVERSCMP
972 /* Good enough for our needs */
973 static int
974 strverscmp(const char *s1, const char *s2)
975 {
976         int s1maj, s1min, s1part;
977         int s2maj, s2min, s2part;
978         int r;
979
980         s1min = s1part = 0;
981         if (sscanf(s1, "%d.%d.%d", &s1maj, &s1min, &s1part) < 1)
982                 return -1;
983         s2min = s2part = 0;
984         if (sscanf(s2, "%d.%d.%d", &s2maj, &s2min, &s2part) < 1)
985                 return -1;
986         r = s1maj - s2maj;
987         if (r != 0)
988                 return r;
989         r = s1min - s2min;
990         if (r != 0)
991                 return r;
992         return s1part - s2part;
993 }
994 #endif
995
996 int
997 dhcpcd_open(DHCPCD_CONNECTION *con, bool privileged)
998 {
999         const char *path = privileged ? DHCPCD_SOCKET : DHCPCD_UNPRIV_SOCKET;
1000         char cmd[128];
1001         ssize_t bytes;
1002         size_t nifs, n;
1003
1004         assert(con);
1005         if (con->open) {
1006                 if (con->listen_fd != -1)
1007                         return con->listen_fd;
1008                 errno = EISCONN;
1009                 return -1;
1010         }
1011         /* We need to block the command fd */
1012         con->command_fd = dhcpcd_connect(path, 0);
1013         if (con->command_fd == -1)
1014                 goto err_exit;
1015
1016         con->terminate_commands = false;
1017         if (dhcpcd_ctrl_command(con, "--version", &con->version) <= 0)
1018                 goto err_exit;
1019         con->terminate_commands =
1020             strverscmp(con->version, "6.4.1") >= 0 ? true : false;
1021
1022         if (dhcpcd_ctrl_command(con, "--getconfigfile", &con->cffile) <= 0)
1023                 goto err_exit;
1024
1025         con->open = true;
1026         con->privileged = privileged;
1027         update_status(con, DHC_UNKNOWN);
1028
1029         con->listen_fd = dhcpcd_connect(path, SOCK_NONBLOCK);
1030         if (con->listen_fd == -1)
1031                 goto err_exit;
1032
1033         dhcpcd_command_fd(con, con->listen_fd, false, "--listen", NULL);
1034         dhcpcd_command_fd(con, con->command_fd, false, "--getinterfaces", NULL);
1035         bytes = read(con->command_fd, cmd, sizeof(nifs));
1036         if (bytes != sizeof(nifs))
1037                 goto err_exit;
1038         memcpy(&nifs, cmd, sizeof(nifs));
1039         /* We don't dispatch each interface here as that
1040          * causes too much notification spam when the GUI starts */
1041         for (n = 0; n < nifs; n++)
1042                 dhcpcd_read_if(con, con->command_fd);
1043
1044         update_status(con, DHC_UNKNOWN);
1045
1046         return con->listen_fd;
1047
1048 err_exit:
1049         dhcpcd_close(con);
1050         return -1;
1051 }
1052
1053 int
1054 dhcpcd_get_fd(DHCPCD_CONNECTION *con)
1055 {
1056
1057         assert(con);
1058         return con->listen_fd;
1059 }
1060
1061 bool
1062 dhcpcd_privileged(DHCPCD_CONNECTION *con)
1063 {
1064
1065         assert(con);
1066         return con->privileged;
1067 }
1068
1069 unsigned int
1070 dhcpcd_status(DHCPCD_CONNECTION *con, const char **status)
1071 {
1072
1073         assert(con);
1074         if (status)
1075                 *status = dhcpcd_cstates[con->status];
1076         return con->status;
1077 }
1078
1079 bool
1080 dhcpcd_af_waiting(const DHCPCD_CONNECTION *con)
1081 {
1082
1083         assert(con);
1084         return con->af_waiting;
1085 }
1086
1087 const char *
1088 dhcpcd_version(DHCPCD_CONNECTION *con)
1089 {
1090
1091         assert(con);
1092         return con->version;
1093 }
1094
1095 const char *
1096 dhcpcd_cffile(DHCPCD_CONNECTION *con)
1097 {
1098
1099         assert(con);
1100         return con->cffile;
1101 }
1102
1103 void
1104 dhcpcd_set_if_callback(DHCPCD_CONNECTION *con,
1105     void (*cb)(DHCPCD_IF *, void *), void *ctx)
1106 {
1107
1108         assert(con);
1109         con->if_cb = cb;
1110         con->if_context = ctx;
1111 }
1112
1113 void
1114 dhcpcd_set_status_callback(DHCPCD_CONNECTION *con,
1115     void (*cb)(DHCPCD_CONNECTION *, unsigned int, const char *, void *),
1116     void *ctx)
1117 {
1118
1119         assert(con);
1120         con->status_cb = cb;
1121         con->status_context = ctx;
1122 }
1123
1124 void
1125 dhcpcd_close(DHCPCD_CONNECTION *con)
1126 {
1127         DHCPCD_IF *nif;
1128         DHCPCD_WPA *nwpa;
1129         DHCPCD_WI_HIST *nh;
1130
1131         assert(con);
1132
1133         if (con->open) {
1134                 if (con->command_fd != -1)
1135                         shutdown(con->command_fd, SHUT_RDWR);
1136                 if (con->listen_fd != -1)
1137                         shutdown(con->listen_fd, SHUT_RDWR);
1138                 con->open = false;
1139         }
1140
1141         /* Shut down WPA listeners as they aren't much good without dhcpcd.
1142          * They'll be restarted anyway when dhcpcd comes back up. */
1143         while (con->wpa) {
1144                 nwpa = con->wpa->next;
1145                 dhcpcd_wpa_close(con->wpa);
1146                 free(con->wpa);
1147                 con->wpa = nwpa;
1148         }
1149         while (con->wi_history) {
1150                 nh = con->wi_history->next;
1151                 free(con->wi_history);
1152                 con->wi_history = nh;
1153         }
1154         while (con->interfaces) {
1155                 nif = con->interfaces->next;
1156                 free(con->interfaces->data);
1157                 free(con->interfaces->last_message);
1158                 free(con->interfaces);
1159                 con->interfaces = nif;
1160         }
1161
1162         update_status(con, DHC_DOWN);
1163
1164         if (con->command_fd != -1) {
1165                 close(con->command_fd);
1166                 con->command_fd = -1;
1167         }
1168         if (con->listen_fd != -1) {
1169                 close(con->listen_fd);
1170                 con->listen_fd = -1;
1171         }
1172
1173         if (con->cffile) {
1174                 free(con->cffile);
1175                 con->cffile = NULL;
1176         }
1177         if (con->version) {
1178                 free(con->version);
1179                 con->version = NULL;
1180         }
1181         if (con->buf) {
1182                 free(con->buf);
1183                 con->buf = NULL;
1184                 con->buflen = 0;
1185         }
1186 }
1187
1188 void
1189 dhcpcd_free(DHCPCD_CONNECTION *con)
1190 {
1191
1192         assert(con);
1193         free(con);
1194 }
1195
1196 DHCPCD_CONNECTION *
1197 dhcpcd_if_connection(DHCPCD_IF *i)
1198 {
1199
1200         assert(i);
1201         return i->con;
1202 }
1203
1204 char *
1205 dhcpcd_if_message(DHCPCD_IF *i, bool *new_msg)
1206 {
1207         const char *ip, *iplen, *pfx;
1208         char *msg, *p;
1209         const char *reason = NULL;
1210         size_t len;
1211         bool showssid;
1212
1213         assert(i);
1214         /* Don't report non SLAAC configurations */
1215         if (i->type == DHT_RA && i->up &&
1216             dhcpcd_get_value(i, "nd1_addr1") == NULL &&
1217             dhcpcd_get_value(i, "ra1_prefix") == NULL)
1218                 return NULL;
1219
1220         showssid = false;
1221         switch (i->state) {
1222         case DHS_EXPIRE:
1223                 reason = _("Expired");
1224                 break;
1225         case DHS_CARRIER:
1226                 if (i->wireless) {
1227                         showssid = true;
1228                         reason = _("Associated with");
1229                 } else {
1230                         /* Don't report able in if we have addresses */
1231                         const DHCPCD_IF *ci;
1232
1233                         for (ci = i->con->interfaces; ci; ci = ci->next) {
1234                                 if (ci != i &&
1235                                     strcmp(i->ifname, ci->ifname) == 0 &&
1236                                     ci->up)
1237                                         break;
1238                         }
1239                         if (ci)
1240                                 return NULL;
1241                         reason = _("Link is up, configuring");
1242                 }
1243                 break;
1244         case DHS_NOCARRIER:
1245                 if (i->wireless) {
1246                         if (i->ssid) {
1247                                 reason = _("Disassociated from");
1248                                 showssid = true;
1249                         } else
1250                                 reason = _("Not associated");
1251                 } else
1252                         reason = _("Link is down");
1253                 break;
1254         case DHS_DEPARTED:
1255                 reason = _("Departed");
1256                 break;
1257         case DHS_UNKNOWN:
1258                 reason = _("Unknown link state");
1259                 break;
1260         case DHS_FAIL:
1261                 reason = _("Automatic configuration not possible");
1262                 break;
1263         case DHS_3RDPARTY:
1264                 reason = _("Waiting for 3rd Party configuration");
1265                 break;
1266         }
1267
1268         if (reason == NULL) {
1269                 if (i->up) {
1270                         if (i->state == DHS_DELEGATED)
1271                                 reason = _("Delegated");
1272                         else
1273                                 reason = _("Configured");
1274                 } else if (i->type == DHT_RA)
1275                         reason = "Expired RA";
1276                 else if (i->type == DHT_IPV4LL)
1277                         reason = "Expired IPv4LL";
1278                 else
1279                         reason = i->reason;
1280         }
1281
1282         pfx = i->up ? "new_" : "old_";
1283         if ((ip = dhcpcd_get_prefix_value(i, pfx, "ip_address")))
1284                 iplen = dhcpcd_get_prefix_value(i, pfx, "subnet_cidr");
1285         else if ((ip = dhcpcd_get_value(i, "nd1_addr1")))
1286                 iplen = NULL;
1287         else if ((ip = dhcpcd_get_value(i, "ra1_addr")))
1288                 iplen = NULL;
1289         else if ((ip = dhcpcd_get_value(i, "ra1_prefix")))
1290                 iplen = NULL;
1291         else if ((ip = dhcpcd_get_prefix_value(i, pfx,
1292             "dhcp6_ia_na1_ia_addr1")))
1293                 iplen = "128";
1294         else if ((ip = dhcpcd_get_prefix_value(i, pfx,
1295             "delegated_dhcp6_prefix")))
1296                 iplen = NULL;
1297         else {
1298                 ip = NULL;
1299                 iplen = NULL;
1300         }
1301
1302         len = strlen(i->ifname) + strlen(reason) + 3;
1303         if (showssid && i->ssid)
1304                 len += strlen(i->ssid) + 1;
1305         if (ip)
1306                 len += strlen(ip) + 1;
1307         if (iplen)
1308                 len += strlen(iplen) + 1;
1309         msg = p = malloc(len);
1310         if (msg == NULL)
1311                 return NULL;
1312         p += snprintf(msg, len, "%s: %s", i->ifname, reason);
1313         if (showssid)
1314                 p += snprintf(p, len - (size_t)(p - msg), " %s", i->ssid);
1315         if (iplen)
1316                 snprintf(p, len - (size_t)(p - msg), " %s/%s", ip, iplen);
1317         else if (ip)
1318                 snprintf(p, len - (size_t)(p - msg), " %s", ip);
1319
1320         if (new_msg) {
1321                 if (i->last_message == NULL || strcmp(i->last_message, msg))
1322                         *new_msg = true;
1323                 else
1324                         *new_msg = false;
1325         }
1326         free(i->last_message);
1327         i->last_message = strdup(msg);
1328
1329         return msg;
1330 }