Add the address waiting state, to match the waitip directive in dhcpcd.conf
[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         }
697
698         if (isdhcp6)
699                 *type = DHT_DHCP6;
700         else
701                 *type = DHT_IPV4;
702 }
703
704 static DHCPCD_IF *
705 dhcpcd_new_if(DHCPCD_CONNECTION *con, char *data, size_t len)
706 {
707         const char *ifname, *ifclass, *reason, *order, *flags;
708         unsigned int state, type;
709         char *orderdup, *o, *p;
710         DHCPCD_IF *e, *i, *l, *n, *nl;
711         bool addedi;
712
713 #if 0
714         char *dp = data, *de = data + len;
715         while (dp < de) {
716                 printf ("XX: %s\n", dp);
717                 dp += strlen(dp) + 1;
718         }
719 #endif
720
721         ifname = get_value(data, len, "interface");
722         if (ifname == NULL || *ifname == '\0') {
723                 errno = ESRCH;
724                 return NULL;
725         }
726         reason = get_value(data, len, "reason");
727         if (reason == NULL || *reason == '\0') {
728                 errno = ESRCH;
729                 return NULL;
730         }
731         dhcpcd_reason_to_statetype(reason, &state, &type);
732
733         ifclass = get_value(data, len, "ifclass");
734         /* Skip pseudo interfaces */
735         if (ifclass && *ifclass != '\0') {
736                 errno = ENOTSUP;
737                 return NULL;
738         }
739         if (state == DHS_RECONFIGURE || state == DHS_INFORM) {
740                 errno = ENOTSUP;
741                 return NULL;
742         }
743         order = get_value(data, len, "interface_order");
744         if (order == NULL || *order == '\0') {
745                 errno = ESRCH;
746                 return NULL;
747         }
748
749         i = NULL;
750        /* Remove all instances on carrier drop */
751         if (state == DHS_NOCARRIER ||
752             state == DHS_DEPARTED || state == DHS_STOPPED)
753         {
754                 l = NULL;
755                 for (e = con->interfaces; e; e = n) {
756                         n = e->next;
757                         if (strcmp(e->ifname, ifname) == 0) {
758                                 if (e->type == type)
759                                         l = i = e;
760                                 else {
761                                         if (l)
762                                                 l->next = e->next;
763                                         else
764                                                 con->interfaces = e->next;
765                                         free(e);
766                                 }
767                         } else
768                                 l = e;
769                 }
770         } else if (type != DHT_LINK) {
771                 /* If link is down, ignore it */
772                 e = dhcpcd_get_if(con, ifname, DHT_LINK);
773                 if (e && !e->up)
774                         return NULL;
775         }
776
777         orderdup = strdup(order);
778         if (orderdup == NULL)
779                 return NULL;
780
781         /* Find our pointer */
782         if (i == NULL) {
783                 l = NULL;
784                 for (e = con->interfaces; e; e = e->next) {
785                         if (e->type == type && strcmp(e->ifname, ifname) == 0) {
786                                 i = e;
787                                 break;
788                         }
789                         l = e;
790                 }
791         }
792         if (i == NULL) {
793                 i = malloc(sizeof(*i));
794                 if (i == NULL) {
795                         free(orderdup);
796                         return NULL;
797                 }
798                 if (l)
799                         l->next = i;
800                 else
801                         con->interfaces = i;
802                 i->next = NULL;
803                 i->last_message = NULL;
804         } else
805                 free(i->data);
806
807         /* Now fill out our interface structure */
808         i->con = con;
809         i->data = data;
810         i->data_len = len;
811         i->ifname = ifname;
812         i->type = type;
813         i->state = state;
814         i->reason = reason;
815         flags = dhcpcd_get_value(i, "ifflags");
816         if (flags)
817                 i->ifflags = (unsigned int)strtoul(flags, NULL, 0);
818         else
819                 i->ifflags = 0;
820         if (state == DHS_CARRIER || state == DHS_DELEGATED)
821                 i->up = true;
822         else
823                 i->up = strtobool(dhcpcd_get_value(i, "if_up"));
824         i->wireless = strtobool(dhcpcd_get_value(i, "ifwireless"));
825         i->ssid = dhcpcd_get_value(i, "ifssid");
826         if (i->ssid == NULL && i->wireless)
827                 i->ssid = dhcpcd_get_value(i, i->up ? "new_ssid" : "old_ssid");
828
829         /* Work out if we're waiting for any other addresses */
830         if (dhcpcd_get_value(i, "af_waiting") == NULL)
831                 con->af_waiting = false;
832         else
833                 con->af_waiting = true;
834
835        /* Sort! */
836         n = nl = NULL;
837         p = orderdup;
838         addedi = false;
839         while ((o = strsep(&p, " ")) != NULL) {
840                 for (type = 0; type < DHT_MAX; type++) {
841                         l = NULL;
842                         for (e = con->interfaces; e; e = e->next) {
843                                 if (e->type == type && strcmp(e->ifname, o) == 0)
844                                         break;
845                                 l = e;
846                         }
847                         if (e == NULL)
848                                 continue;
849                         if (i == e)
850                                 addedi = true;
851                         if (l)
852                                 l->next = e->next;
853                         else
854                                 con->interfaces = e->next;
855                         e->next = NULL;
856                         if (nl == NULL)
857                                 n = nl = e;
858                         else {
859                                 nl->next = e;
860                                 nl = e;
861                         }
862                 }
863         }
864         free(orderdup);
865         /* Free any stragglers */
866         while (con->interfaces) {
867                 e = con->interfaces->next;
868                 free(con->interfaces->data);
869                 free(con->interfaces->last_message);
870                 free(con->interfaces);
871                 con->interfaces = e;
872         }
873         con->interfaces = n;
874
875         return addedi ? i : NULL;
876 }
877
878 static DHCPCD_IF *
879 dhcpcd_read_if(DHCPCD_CONNECTION *con, int fd)
880 {
881         char sbuf[sizeof(size_t)], *rbuf;
882         size_t len;
883         ssize_t bytes;
884         DHCPCD_IF *i;
885
886         bytes = read(fd, sbuf, sizeof(sbuf));
887         if (bytes == 0 || bytes == -1) {
888                 dhcpcd_close(con);
889                 return NULL;
890         }
891         memcpy(&len, sbuf, sizeof(len));
892         rbuf = malloc(len + 1);
893         if (rbuf == NULL)
894                 return NULL;
895         bytes = read(fd, rbuf, len);
896         if (bytes == 0 || bytes == -1) {
897                 free(rbuf);
898                 dhcpcd_close(con);
899                 return NULL;
900         }
901         if ((size_t)bytes != len) {
902                 free(rbuf);
903                 errno = EINVAL;
904                 return NULL;
905         }
906         rbuf[bytes] = '\0';
907
908         i = dhcpcd_new_if(con, rbuf, len);
909         if (i == NULL)
910                 free(rbuf);
911         return i;
912 }
913
914 static void
915 dhcpcd_dispatchif(DHCPCD_IF *i)
916 {
917
918         assert(i);
919         if (i->con->if_cb)
920                 i->con->if_cb(i, i->con->if_context);
921         dhcpcd_wpa_if_event(i);
922 }
923
924 void
925 dhcpcd_dispatch(DHCPCD_CONNECTION *con)
926 {
927         DHCPCD_IF *i;
928
929         assert(con);
930         i = dhcpcd_read_if(con, con->listen_fd);
931         if (i)
932                 dhcpcd_dispatchif(i);
933
934         /* Have to call update_status last as it could
935          * cause the interface to be destroyed. */
936         update_status(con, DHC_UNKNOWN);
937 }
938
939 DHCPCD_CONNECTION *
940 dhcpcd_new(void)
941 {
942         DHCPCD_CONNECTION *con;
943
944         con = calloc(1, sizeof(*con));
945         con->command_fd = con->listen_fd = -1;
946         con->open = false;
947         con->progname = "libdhcpcd";
948         con->af_waiting = false;
949         return con;
950 }
951
952 void
953 dhcpcd_set_progname(DHCPCD_CONNECTION *con, const char *progname)
954 {
955
956         assert(con);
957         con->progname = progname;
958 }
959
960 const char *
961 dhcpcd_get_progname(const DHCPCD_CONNECTION *con)
962 {
963
964         assert(con);
965         return con->progname;
966 }
967
968 #ifndef HAVE_STRVERSCMP
969 /* Good enough for our needs */
970 static int
971 strverscmp(const char *s1, const char *s2)
972 {
973         int s1maj, s1min, s1part;
974         int s2maj, s2min, s2part;
975         int r;
976
977         s1min = s1part = 0;
978         if (sscanf(s1, "%d.%d.%d", &s1maj, &s1min, &s1part) < 1)
979                 return -1;
980         s2min = s2part = 0;
981         if (sscanf(s2, "%d.%d.%d", &s2maj, &s2min, &s2part) < 1)
982                 return -1;
983         r = s1maj - s2maj;
984         if (r != 0)
985                 return r;
986         r = s1min - s2min;
987         if (r != 0)
988                 return r;
989         return s1part - s2part;
990 }
991 #endif
992
993 int
994 dhcpcd_open(DHCPCD_CONNECTION *con, bool privileged)
995 {
996         const char *path = privileged ? DHCPCD_SOCKET : DHCPCD_UNPRIV_SOCKET;
997         char cmd[128];
998         ssize_t bytes;
999         size_t nifs, n;
1000
1001         assert(con);
1002         if (con->open) {
1003                 if (con->listen_fd != -1)
1004                         return con->listen_fd;
1005                 errno = EISCONN;
1006                 return -1;
1007         }
1008         /* We need to block the command fd */
1009         con->command_fd = dhcpcd_connect(path, 0);
1010         if (con->command_fd == -1)
1011                 goto err_exit;
1012
1013         con->terminate_commands = false;
1014         if (dhcpcd_ctrl_command(con, "--version", &con->version) <= 0)
1015                 goto err_exit;
1016         con->terminate_commands =
1017             strverscmp(con->version, "6.4.1") >= 0 ? true : false;
1018
1019         if (dhcpcd_ctrl_command(con, "--getconfigfile", &con->cffile) <= 0)
1020                 goto err_exit;
1021
1022         con->open = true;
1023         con->privileged = privileged;
1024         update_status(con, DHC_UNKNOWN);
1025
1026         con->listen_fd = dhcpcd_connect(path, SOCK_NONBLOCK);
1027         if (con->listen_fd == -1)
1028                 goto err_exit;
1029
1030         dhcpcd_command_fd(con, con->listen_fd, false, "--listen", NULL);
1031         dhcpcd_command_fd(con, con->command_fd, false, "--getinterfaces", NULL);
1032         bytes = read(con->command_fd, cmd, sizeof(nifs));
1033         if (bytes != sizeof(nifs))
1034                 goto err_exit;
1035         memcpy(&nifs, cmd, sizeof(nifs));
1036         /* We don't dispatch each interface here as that
1037          * causes too much notification spam when the GUI starts */
1038         for (n = 0; n < nifs; n++)
1039                 dhcpcd_read_if(con, con->command_fd);
1040
1041         update_status(con, DHC_UNKNOWN);
1042
1043         return con->listen_fd;
1044
1045 err_exit:
1046         dhcpcd_close(con);
1047         return -1;
1048 }
1049
1050 int
1051 dhcpcd_get_fd(DHCPCD_CONNECTION *con)
1052 {
1053
1054         assert(con);
1055         return con->listen_fd;
1056 }
1057
1058 bool
1059 dhcpcd_privileged(DHCPCD_CONNECTION *con)
1060 {
1061
1062         assert(con);
1063         return con->privileged;
1064 }
1065
1066 unsigned int
1067 dhcpcd_status(DHCPCD_CONNECTION *con, const char **status)
1068 {
1069
1070         assert(con);
1071         if (status)
1072                 *status = dhcpcd_cstates[con->status];
1073         return con->status;
1074 }
1075
1076 bool
1077 dhcpcd_af_waiting(const DHCPCD_CONNECTION *con)
1078 {
1079
1080         assert(con);
1081         return con->af_waiting;
1082 }
1083
1084 const char *
1085 dhcpcd_version(DHCPCD_CONNECTION *con)
1086 {
1087
1088         assert(con);
1089         return con->version;
1090 }
1091
1092 const char *
1093 dhcpcd_cffile(DHCPCD_CONNECTION *con)
1094 {
1095
1096         assert(con);
1097         return con->cffile;
1098 }
1099
1100 void
1101 dhcpcd_set_if_callback(DHCPCD_CONNECTION *con,
1102     void (*cb)(DHCPCD_IF *, void *), void *ctx)
1103 {
1104
1105         assert(con);
1106         con->if_cb = cb;
1107         con->if_context = ctx;
1108 }
1109
1110 void
1111 dhcpcd_set_status_callback(DHCPCD_CONNECTION *con,
1112     void (*cb)(DHCPCD_CONNECTION *, unsigned int, const char *, void *),
1113     void *ctx)
1114 {
1115
1116         assert(con);
1117         con->status_cb = cb;
1118         con->status_context = ctx;
1119 }
1120
1121 void
1122 dhcpcd_close(DHCPCD_CONNECTION *con)
1123 {
1124         DHCPCD_IF *nif;
1125         DHCPCD_WPA *nwpa;
1126         DHCPCD_WI_HIST *nh;
1127
1128         assert(con);
1129
1130         if (con->open) {
1131                 if (con->command_fd != -1)
1132                         shutdown(con->command_fd, SHUT_RDWR);
1133                 if (con->listen_fd != -1)
1134                         shutdown(con->listen_fd, SHUT_RDWR);
1135                 con->open = false;
1136         }
1137
1138         /* Shut down WPA listeners as they aren't much good without dhcpcd.
1139          * They'll be restarted anyway when dhcpcd comes back up. */
1140         while (con->wpa) {
1141                 nwpa = con->wpa->next;
1142                 dhcpcd_wpa_close(con->wpa);
1143                 free(con->wpa);
1144                 con->wpa = nwpa;
1145         }
1146         while (con->wi_history) {
1147                 nh = con->wi_history->next;
1148                 free(con->wi_history);
1149                 con->wi_history = nh;
1150         }
1151         while (con->interfaces) {
1152                 nif = con->interfaces->next;
1153                 free(con->interfaces->data);
1154                 free(con->interfaces->last_message);
1155                 free(con->interfaces);
1156                 con->interfaces = nif;
1157         }
1158
1159         update_status(con, DHC_DOWN);
1160
1161         if (con->command_fd != -1) {
1162                 close(con->command_fd);
1163                 con->command_fd = -1;
1164         }
1165         if (con->listen_fd != -1) {
1166                 close(con->listen_fd);
1167                 con->listen_fd = -1;
1168         }
1169
1170         if (con->cffile) {
1171                 free(con->cffile);
1172                 con->cffile = NULL;
1173         }
1174         if (con->version) {
1175                 free(con->version);
1176                 con->version = NULL;
1177         }
1178         if (con->buf) {
1179                 free(con->buf);
1180                 con->buf = NULL;
1181                 con->buflen = 0;
1182         }
1183 }
1184
1185 void
1186 dhcpcd_free(DHCPCD_CONNECTION *con)
1187 {
1188
1189         assert(con);
1190         free(con);
1191 }
1192
1193 DHCPCD_CONNECTION *
1194 dhcpcd_if_connection(DHCPCD_IF *i)
1195 {
1196
1197         assert(i);
1198         return i->con;
1199 }
1200
1201 char *
1202 dhcpcd_if_message(DHCPCD_IF *i, bool *new_msg)
1203 {
1204         const char *ip, *iplen, *pfx;
1205         char *msg, *p;
1206         const char *reason = NULL;
1207         size_t len;
1208         bool showssid;
1209
1210         assert(i);
1211         /* Don't report non SLAAC configurations */
1212         if (i->type == DHT_RA && i->up &&
1213             dhcpcd_get_value(i, "nd1_addr1") == NULL &&
1214             dhcpcd_get_value(i, "ra1_prefix") == NULL)
1215                 return NULL;
1216
1217         showssid = false;
1218         switch (i->state) {
1219         case DHS_EXPIRE:
1220                 reason = _("Expired");
1221                 break;
1222         case DHS_CARRIER:
1223                 if (i->wireless) {
1224                         showssid = true;
1225                         reason = _("Associated with");
1226                 } else {
1227                         /* Don't report able in if we have addresses */
1228                         const DHCPCD_IF *ci;
1229
1230                         for (ci = i->con->interfaces; ci; ci = ci->next) {
1231                                 if (ci != i &&
1232                                     strcmp(i->ifname, ci->ifname) == 0 &&
1233                                     ci->up)
1234                                         break;
1235                         }
1236                         if (ci)
1237                                 return NULL;
1238                         reason = _("Link is up, configuring");
1239                 }
1240                 break;
1241         case DHS_NOCARRIER:
1242                 if (i->wireless) {
1243                         if (i->ssid) {
1244                                 reason = _("Disassociated from");
1245                                 showssid = true;
1246                         } else
1247                                 reason = _("Not associated");
1248                 } else
1249                         reason = _("Link is down");
1250                 break;
1251         case DHS_DEPARTED:
1252                 reason = _("Departed");
1253                 break;
1254         case DHS_UNKNOWN:
1255                 reason = _("Unknown link state");
1256                 break;
1257         case DHS_FAIL:
1258                 reason = _("Automatic configuration not possible");
1259                 break;
1260         case DHS_3RDPARTY:
1261                 reason = _("Waiting for 3rd Party configuration");
1262                 break;
1263         }
1264
1265         if (reason == NULL) {
1266                 if (i->up) {
1267                         if (i->state == DHS_DELEGATED)
1268                                 reason = _("Delegated");
1269                         else
1270                                 reason = _("Configured");
1271                 } else if (i->type == DHT_RA)
1272                         reason = "Expired RA";
1273                 else
1274                         reason = i->reason;
1275         }
1276
1277         pfx = i->up ? "new_" : "old_";
1278         if ((ip = dhcpcd_get_prefix_value(i, pfx, "ip_address")))
1279                 iplen = dhcpcd_get_prefix_value(i, pfx, "subnet_cidr");
1280         else if ((ip = dhcpcd_get_value(i, "nd1_addr1")))
1281                 iplen = NULL;
1282         else if ((ip = dhcpcd_get_value(i, "ra1_addr")))
1283                 iplen = NULL;
1284         else if ((ip = dhcpcd_get_value(i, "ra1_prefix")))
1285                 iplen = NULL;
1286         else if ((ip = dhcpcd_get_prefix_value(i, pfx,
1287             "dhcp6_ia_na1_ia_addr1")))
1288                 iplen = "128";
1289         else if ((ip = dhcpcd_get_prefix_value(i, pfx,
1290             "delegated_dhcp6_prefix")))
1291                 iplen = NULL;
1292         else {
1293                 ip = NULL;
1294                 iplen = NULL;
1295         }
1296
1297         len = strlen(i->ifname) + strlen(reason) + 3;
1298         if (showssid && i->ssid)
1299                 len += strlen(i->ssid) + 1;
1300         if (ip)
1301                 len += strlen(ip) + 1;
1302         if (iplen)
1303                 len += strlen(iplen) + 1;
1304         msg = p = malloc(len);
1305         if (msg == NULL)
1306                 return NULL;
1307         p += snprintf(msg, len, "%s: %s", i->ifname, reason);
1308         if (showssid)
1309                 p += snprintf(p, len - (size_t)(p - msg), " %s", i->ssid);
1310         if (iplen)
1311                 snprintf(p, len - (size_t)(p - msg), " %s/%s", ip, iplen);
1312         else if (ip)
1313                 snprintf(p, len - (size_t)(p - msg), " %s", ip);
1314
1315         if (new_msg) {
1316                 if (i->last_message == NULL || strcmp(i->last_message, msg))
1317                         *new_msg = true;
1318                 else
1319                         *new_msg = false;
1320         }
1321         free(i->last_message);
1322         i->last_message = strdup(msg);
1323
1324         return msg;
1325 }