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