xref: /freebsd/usr.sbin/pkg/config.c (revision c1557708f1fae1bb9c8e23e3bbb2aa2b055e1211)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2014-2025 Baptiste Daroussin <bapt@FreeBSD.org>
5  * Copyright (c) 2013 Bryan Drewery <bdrewery@FreeBSD.org>
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include <sys/param.h>
30 #include <sys/queue.h>
31 #include <sys/utsname.h>
32 #include <sys/sysctl.h>
33 
34 #include <dirent.h>
35 #include <ucl.h>
36 #include <err.h>
37 #include <errno.h>
38 #include <libutil.h>
39 #include <paths.h>
40 #include <stdbool.h>
41 #include <unistd.h>
42 #include <ctype.h>
43 
44 #include "config.h"
45 
46 struct config_value {
47 	char *value;
48 	STAILQ_ENTRY(config_value) next;
49 };
50 
51 struct config_entry {
52 	uint8_t type;
53 	const char *key;
54 	const char *val;
55 	char *value;
56 	STAILQ_HEAD(, config_value) *list;
57 	bool envset;
58 	bool main_only;				/* Only set in pkg.conf. */
59 };
60 
61 static struct repositories repositories = STAILQ_HEAD_INITIALIZER(repositories);
62 
63 static struct config_entry c[] = {
64 	[PACKAGESITE] = {
65 		PKG_CONFIG_STRING,
66 		"PACKAGESITE",
67 		URL_SCHEME_PREFIX "http://pkg.FreeBSD.org/${ABI}/latest",
68 		NULL,
69 		NULL,
70 		false,
71 		false,
72 	},
73 	[ABI] = {
74 		PKG_CONFIG_STRING,
75 		"ABI",
76 		NULL,
77 		NULL,
78 		NULL,
79 		false,
80 		true,
81 	},
82 	[MIRROR_TYPE] = {
83 		PKG_CONFIG_STRING,
84 		"MIRROR_TYPE",
85 		"SRV",
86 		NULL,
87 		NULL,
88 		false,
89 		false,
90 	},
91 	[ASSUME_ALWAYS_YES] = {
92 		PKG_CONFIG_BOOL,
93 		"ASSUME_ALWAYS_YES",
94 		"NO",
95 		NULL,
96 		NULL,
97 		false,
98 		true,
99 	},
100 	[SIGNATURE_TYPE] = {
101 		PKG_CONFIG_STRING,
102 		"SIGNATURE_TYPE",
103 		NULL,
104 		NULL,
105 		NULL,
106 		false,
107 		false,
108 	},
109 	[FINGERPRINTS] = {
110 		PKG_CONFIG_STRING,
111 		"FINGERPRINTS",
112 		NULL,
113 		NULL,
114 		NULL,
115 		false,
116 		false,
117 	},
118 	[REPOS_DIR] = {
119 		PKG_CONFIG_LIST,
120 		"REPOS_DIR",
121 		NULL,
122 		NULL,
123 		NULL,
124 		false,
125 		true,
126 	},
127 	[PUBKEY] = {
128 		PKG_CONFIG_STRING,
129 		"PUBKEY",
130 		NULL,
131 		NULL,
132 		NULL,
133 		false,
134 		false
135 	},
136 	[PKG_ENV] = {
137 		PKG_CONFIG_OBJECT,
138 		"PKG_ENV",
139 		NULL,
140 		NULL,
141 		NULL,
142 		false,
143 		false,
144 	}
145 };
146 
147 static char *
148 pkg_get_myabi(void)
149 {
150 	struct utsname uts;
151 	char machine_arch[255];
152 	char *abi;
153 	size_t len;
154 	int error;
155 
156 	error = uname(&uts);
157 	if (error)
158 		return (NULL);
159 
160 	len = sizeof(machine_arch);
161 	error = sysctlbyname("hw.machine_arch", machine_arch, &len, NULL, 0);
162 	if (error)
163 		return (NULL);
164 	machine_arch[len] = '\0';
165 
166 	/*
167 	 * Use __FreeBSD_version rather than kernel version (uts.release) for
168 	 * use in jails. This is equivalent to the value of uname -U.
169 	 */
170 	error = asprintf(&abi, "%s:%d:%s", uts.sysname, __FreeBSD_version/100000,
171 	    machine_arch);
172 	if (error < 0)
173 		return (NULL);
174 
175 	return (abi);
176 }
177 
178 static void
179 subst_packagesite(const char *abi)
180 {
181 	char *newval;
182 	const char *variable_string;
183 	const char *oldval;
184 
185 	if (c[PACKAGESITE].value != NULL)
186 		oldval = c[PACKAGESITE].value;
187 	else
188 		oldval = c[PACKAGESITE].val;
189 
190 	if ((variable_string = strstr(oldval, "${ABI}")) == NULL)
191 		return;
192 
193 	asprintf(&newval, "%.*s%s%s",
194 	    (int)(variable_string - oldval), oldval, abi,
195 	    variable_string + strlen("${ABI}"));
196 	if (newval == NULL)
197 		errx(EXIT_FAILURE, "asprintf");
198 
199 	free(c[PACKAGESITE].value);
200 	c[PACKAGESITE].value = newval;
201 }
202 
203 static int
204 boolstr_to_bool(const char *str)
205 {
206 	if (str != NULL && (strcasecmp(str, "true") == 0 ||
207 	    strcasecmp(str, "yes") == 0 || strcasecmp(str, "on") == 0 ||
208 	    str[0] == '1'))
209 		return (true);
210 
211 	return (false);
212 }
213 
214 static void
215 config_parse(const ucl_object_t *obj)
216 {
217 	FILE *buffp;
218 	char *buf = NULL;
219 	size_t bufsz = 0;
220 	const ucl_object_t *cur, *seq, *tmp;
221 	ucl_object_iter_t it = NULL, itseq = NULL, it_obj = NULL;
222 	struct config_entry *temp_config;
223 	struct config_value *cv;
224 	const char *key, *evkey;
225 	int i;
226 	size_t j;
227 
228 	/* Temporary config for configs that may be disabled. */
229 	temp_config = calloc(CONFIG_SIZE, sizeof(struct config_entry));
230 	buffp = open_memstream(&buf, &bufsz);
231 	if (buffp == NULL)
232 		err(EXIT_FAILURE, "open_memstream()");
233 
234 	while ((cur = ucl_iterate_object(obj, &it, true))) {
235 		key = ucl_object_key(cur);
236 		if (key == NULL)
237 			continue;
238 		if (buf != NULL)
239 			memset(buf, 0, bufsz);
240 		rewind(buffp);
241 
242 			for (j = 0; j < strlen(key); ++j)
243 				fputc(toupper(key[j]), buffp);
244 			fflush(buffp);
245 
246 		for (i = 0; i < CONFIG_SIZE; i++) {
247 			if (strcmp(buf, c[i].key) == 0)
248 				break;
249 		}
250 
251 		/* Silently skip unknown keys to be future compatible. */
252 		if (i == CONFIG_SIZE)
253 			continue;
254 
255 		/* env has priority over config file */
256 		if (c[i].envset)
257 			continue;
258 
259 		/* Parse sequence value ["item1", "item2"] */
260 		switch (c[i].type) {
261 		case PKG_CONFIG_LIST:
262 			if (cur->type != UCL_ARRAY) {
263 				warnx("Skipping invalid array "
264 				    "value for %s.\n", c[i].key);
265 				continue;
266 			}
267 			temp_config[i].list =
268 			    malloc(sizeof(*temp_config[i].list));
269 			STAILQ_INIT(temp_config[i].list);
270 
271 			while ((seq = ucl_iterate_object(cur, &itseq, true))) {
272 				if (seq->type != UCL_STRING)
273 					continue;
274 				cv = malloc(sizeof(struct config_value));
275 				cv->value =
276 				    strdup(ucl_object_tostring(seq));
277 				STAILQ_INSERT_TAIL(temp_config[i].list, cv,
278 				    next);
279 			}
280 			break;
281 		case PKG_CONFIG_BOOL:
282 			temp_config[i].value =
283 			    strdup(ucl_object_toboolean(cur) ? "yes" : "no");
284 			break;
285 		case PKG_CONFIG_OBJECT:
286 			if (strcmp(c[i].key, "PKG_ENV") == 0) {
287 				while ((tmp =
288 				    ucl_iterate_object(cur, &it_obj, true))) {
289 					evkey = ucl_object_key(tmp);
290 					if (evkey != NULL && *evkey != '\0') {
291 						setenv(evkey, ucl_object_tostring_forced(tmp), 1);
292 					}
293 				}
294 			}
295 			break;
296 		default:
297 			/* Normal string value. */
298 			temp_config[i].value = strdup(ucl_object_tostring(cur));
299 			break;
300 		}
301 	}
302 
303 	/* Repo is enabled, copy over all settings from temp_config. */
304 	for (i = 0; i < CONFIG_SIZE; i++) {
305 		if (c[i].envset)
306 			continue;
307 		/* Prevent overriding ABI, ASSUME_ALWAYS_YES, etc. */
308 		if (c[i].main_only == true)
309 			continue;
310 		switch (c[i].type) {
311 		case PKG_CONFIG_LIST:
312 			c[i].list = temp_config[i].list;
313 			break;
314 		default:
315 			c[i].value = temp_config[i].value;
316 			break;
317 		}
318 	}
319 
320 	free(temp_config);
321 	fclose(buffp);
322 	free(buf);
323 }
324 
325 
326 static void
327 parse_mirror_type(struct repository *r, const char *mt)
328 {
329 	if (strcasecmp(mt, "srv") == 0)
330 		r->mirror_type = MIRROR_SRV;
331 	r->mirror_type = MIRROR_NONE;
332 }
333 
334 static void
335 repo_free(struct repository *r)
336 {
337 	free(r->name);
338 	free(r->url);
339 	free(r->fingerprints);
340 	free(r->pubkey);
341 	free(r);
342 }
343 
344 static bool
345 parse_signature_type(struct repository *repo, const char *st)
346 {
347 	if (strcasecmp(st, "FINGERPRINTS") == 0)
348 		repo->signature_type = SIGNATURE_FINGERPRINT;
349 	else if (strcasecmp(st, "PUBKEY") == 0)
350 		repo->signature_type = SIGNATURE_PUBKEY;
351 	else if (strcasecmp(st, "NONE") == 0)
352 		repo->signature_type = SIGNATURE_NONE;
353 	else {
354 		warnx("Signature type %s is not supported for bootstrapping,"
355 		    " ignoring repository %s", st, repo->name);
356 		return (false);
357 	}
358 	return (true);
359 }
360 
361 static struct repository *
362 find_repository(const char *name)
363 {
364 	struct repository *repo;
365 	STAILQ_FOREACH(repo, &repositories, next) {
366 		if (strcmp(repo->name, name) == 0)
367 			return (repo);
368 	}
369 	return (NULL);
370 }
371 
372 static void
373 parse_repo(const ucl_object_t *o)
374 {
375 	const ucl_object_t *cur;
376 	const char *key, *reponame;
377 	ucl_object_iter_t it = NULL;
378 	bool newrepo = false;
379 	struct repository *repo;
380 
381 	reponame = ucl_object_key(o);
382 	repo = find_repository(reponame);
383 	if (repo == NULL) {
384 		repo = calloc(1, sizeof(struct repository));
385 		if (repo == NULL)
386 			err(EXIT_FAILURE, "calloc");
387 
388 		repo->name = strdup(reponame);
389 		if (repo->name == NULL)
390 			err(EXIT_FAILURE, "strdup");
391 		newrepo = true;
392 	}
393 	while ((cur = ucl_iterate_object(o, &it, true))) {
394 		key = ucl_object_key(cur);
395 		if (key == NULL)
396 			continue;
397 		if (strcasecmp(key, "url") == 0) {
398 			free(repo->url);
399 			repo->url = strdup(ucl_object_tostring(cur));
400 			if (repo->url == NULL)
401 				err(EXIT_FAILURE, "strdup");
402 		} else if (strcasecmp(key, "mirror_type") == 0) {
403 			parse_mirror_type(repo, ucl_object_tostring(cur));
404 		} else if (strcasecmp(key, "signature_type") == 0) {
405 			if (!parse_signature_type(repo, ucl_object_tostring(cur))) {
406 				if (newrepo)
407 					repo_free(repo);
408 				else
409 					STAILQ_REMOVE(&repositories, repo, repository, next);
410 				return;
411 			}
412 		} else if (strcasecmp(key, "fingerprints") == 0) {
413 			free(repo->fingerprints);
414 			repo->fingerprints = strdup(ucl_object_tostring(cur));
415 			if (repo->fingerprints == NULL)
416 				err(EXIT_FAILURE, "strdup");
417 		} else if (strcasecmp(key, "pubkey") == 0) {
418 			free(repo->pubkey);
419 			repo->pubkey = strdup(ucl_object_tostring(cur));
420 			if (repo->pubkey == NULL)
421 				err(EXIT_FAILURE, "strdup");
422 		} else if (strcasecmp(key, "enabled") == 0) {
423 			if ((cur->type != UCL_BOOLEAN) ||
424 			    !ucl_object_toboolean(cur)) {
425 				if (newrepo)
426 					repo_free(repo);
427 				else
428 					STAILQ_REMOVE(&repositories, repo, repository, next);
429 				return;
430 			}
431 		}
432 	}
433 	/* At least we need an url */
434 	if (repo->url == NULL) {
435 		repo_free(repo);
436 		return;
437 	}
438 	if (newrepo)
439 		STAILQ_INSERT_TAIL(&repositories, repo, next);
440 	return;
441 }
442 
443 /*-
444  * Parse new repo style configs in style:
445  * Name:
446  *   URL:
447  *   MIRROR_TYPE:
448  * etc...
449  */
450 static void
451 parse_repo_file(ucl_object_t *obj, const char *requested_repo)
452 {
453 	ucl_object_iter_t it = NULL;
454 	const ucl_object_t *cur;
455 	const char *key;
456 
457 	while ((cur = ucl_iterate_object(obj, &it, true))) {
458 		key = ucl_object_key(cur);
459 
460 		if (key == NULL)
461 			continue;
462 
463 		if (cur->type != UCL_OBJECT)
464 			continue;
465 
466 		if (requested_repo != NULL && strcmp(requested_repo, key) != 0)
467 			continue;
468 		parse_repo(cur);
469 	}
470 }
471 
472 
473 static int
474 read_conf_file(const char *confpath, const char *requested_repo,
475     pkg_conf_file_t conftype)
476 {
477 	struct ucl_parser *p;
478 	ucl_object_t *obj = NULL;
479 	char *abi = pkg_get_myabi(), *major, *minor;
480 	struct utsname uts;
481 	int ret;
482 
483 	if (uname(&uts))
484 		err(EXIT_FAILURE, "uname");
485 	if (abi == NULL)
486 		errx(EXIT_FAILURE, "Failed to determine ABI");
487 
488 	p = ucl_parser_new(0);
489 	asprintf(&major, "%d",  __FreeBSD_version/100000);
490 	if (major == NULL)
491 		err(EXIT_FAILURE, "asprintf");
492 	asprintf(&minor, "%d",  (__FreeBSD_version / 1000) % 100);
493 	if (minor == NULL)
494 		err(EXIT_FAILURE, "asprintf");
495 	ucl_parser_register_variable(p, "ABI", abi);
496 	ucl_parser_register_variable(p, "OSNAME", uts.sysname);
497 	ucl_parser_register_variable(p, "RELEASE", major);
498 	ucl_parser_register_variable(p, "VERSION_MAJOR", major);
499 	ucl_parser_register_variable(p, "VERSION_MINOR", minor);
500 
501 	if (!ucl_parser_add_file(p, confpath)) {
502 		if (errno != ENOENT)
503 			errx(EXIT_FAILURE, "Unable to parse configuration "
504 			    "file %s: %s", confpath, ucl_parser_get_error(p));
505 		/* no configuration present */
506 		ret = 1;
507 		goto out;
508 	}
509 
510 	obj = ucl_parser_get_object(p);
511 	if (obj->type != UCL_OBJECT)
512 		warnx("Invalid configuration format, ignoring the "
513 		    "configuration file %s", confpath);
514 	else {
515 		if (conftype == CONFFILE_PKG)
516 			config_parse(obj);
517 		else if (conftype == CONFFILE_REPO)
518 			parse_repo_file(obj, requested_repo);
519 	}
520 	ucl_object_unref(obj);
521 
522 	ret = 0;
523 out:
524 	ucl_parser_free(p);
525 	free(abi);
526 	free(major);
527 	free(minor);
528 
529 	return (ret);
530 }
531 
532 static void
533 load_repositories(const char *repodir, const char *requested_repo)
534 {
535 	struct dirent *ent;
536 	DIR *d;
537 	char *p;
538 	size_t n;
539 	char path[MAXPATHLEN];
540 
541 	if ((d = opendir(repodir)) == NULL)
542 		return;
543 
544 	while ((ent = readdir(d))) {
545 		/* Trim out 'repos'. */
546 		if ((n = strlen(ent->d_name)) <= 5)
547 			continue;
548 		p = &ent->d_name[n - 5];
549 		if (strcmp(p, ".conf") == 0) {
550 			snprintf(path, sizeof(path), "%s%s%s",
551 			    repodir,
552 			    repodir[strlen(repodir) - 1] == '/' ? "" : "/",
553 			    ent->d_name);
554 			if (access(path, F_OK) != 0)
555 				continue;
556 			if (read_conf_file(path, requested_repo,
557 			    CONFFILE_REPO)) {
558 				goto cleanup;
559 			}
560 		}
561 	}
562 
563 cleanup:
564 	closedir(d);
565 }
566 
567 int
568 config_init(const char *requested_repo)
569 {
570 	char *val;
571 	int i;
572 	const char *localbase;
573 	char *abi, *env_list_item;
574 	char confpath[MAXPATHLEN];
575 	struct config_value *cv;
576 
577 	for (i = 0; i < CONFIG_SIZE; i++) {
578 		val = getenv(c[i].key);
579 		if (val != NULL) {
580 			c[i].envset = true;
581 			switch (c[i].type) {
582 			case PKG_CONFIG_LIST:
583 				/* Split up comma-separated items from env. */
584 				c[i].list = malloc(sizeof(*c[i].list));
585 				STAILQ_INIT(c[i].list);
586 				for (env_list_item = strtok(val, ",");
587 				    env_list_item != NULL;
588 				    env_list_item = strtok(NULL, ",")) {
589 					cv =
590 					    malloc(sizeof(struct config_value));
591 					cv->value =
592 					    strdup(env_list_item);
593 					STAILQ_INSERT_TAIL(c[i].list, cv,
594 					    next);
595 				}
596 				break;
597 			default:
598 				c[i].val = val;
599 				break;
600 			}
601 		}
602 	}
603 
604 	/* Read LOCALBASE/etc/pkg.conf first. */
605 	localbase = getlocalbase();
606 	snprintf(confpath, sizeof(confpath), "%s/etc/pkg.conf", localbase);
607 
608 	if (access(confpath, F_OK) == 0 && read_conf_file(confpath, NULL,
609 	    CONFFILE_PKG))
610 		goto finalize;
611 
612 	/* Then read in all repos from REPOS_DIR list of directories. */
613 	if (c[REPOS_DIR].list == NULL) {
614 		c[REPOS_DIR].list = malloc(sizeof(*c[REPOS_DIR].list));
615 		STAILQ_INIT(c[REPOS_DIR].list);
616 		cv = malloc(sizeof(struct config_value));
617 		cv->value = strdup("/etc/pkg");
618 		STAILQ_INSERT_TAIL(c[REPOS_DIR].list, cv, next);
619 		cv = malloc(sizeof(struct config_value));
620 		if (asprintf(&cv->value, "%s/etc/pkg/repos", localbase) < 0)
621 			goto finalize;
622 		STAILQ_INSERT_TAIL(c[REPOS_DIR].list, cv, next);
623 	}
624 
625 	STAILQ_FOREACH(cv, c[REPOS_DIR].list, next)
626 		load_repositories(cv->value, requested_repo);
627 
628 finalize:
629 	if (c[ABI].val == NULL && c[ABI].value == NULL) {
630 		abi = pkg_get_myabi();
631 		if (abi == NULL)
632 			errx(EXIT_FAILURE, "Failed to determine the system "
633 			    "ABI");
634 		c[ABI].val = abi;
635 	}
636 
637 	return (0);
638 }
639 
640 int
641 config_string(pkg_config_key k, const char **val)
642 {
643 	if (c[k].type != PKG_CONFIG_STRING)
644 		return (-1);
645 
646 	if (c[k].value != NULL)
647 		*val = c[k].value;
648 	else
649 		*val = c[k].val;
650 
651 	return (0);
652 }
653 
654 int
655 config_bool(pkg_config_key k, bool *val)
656 {
657 	const char *value;
658 
659 	if (c[k].type != PKG_CONFIG_BOOL)
660 		return (-1);
661 
662 	*val = false;
663 
664 	if (c[k].value != NULL)
665 		value = c[k].value;
666 	else
667 		value = c[k].val;
668 
669 	if (boolstr_to_bool(value))
670 		*val = true;
671 
672 	return (0);
673 }
674 
675 struct repositories *
676 config_get_repositories(void)
677 {
678 	if (STAILQ_EMPTY(&repositories)) {
679 		/* Fall back to PACKAGESITE - deprecated - */
680 		struct repository *r = calloc(1, sizeof(*r));
681 		if (r == NULL)
682 			err(EXIT_FAILURE, "calloc");
683 		r->name = strdup("fallback");
684 		if (r->name == NULL)
685 			err(EXIT_FAILURE, "strdup");
686 		subst_packagesite(c[ABI].value != NULL ? c[ABI].value : c[ABI].val);
687 		r->url = c[PACKAGESITE].value;
688 		if (c[SIGNATURE_TYPE].value != NULL)
689 			if (!parse_signature_type(r, c[SIGNATURE_TYPE].value))
690 				exit(EXIT_FAILURE);
691 		if (c[MIRROR_TYPE].value != NULL)
692 			parse_mirror_type(r, c[MIRROR_TYPE].value);
693 		if (c[PUBKEY].value != NULL)
694 			r->pubkey = c[PUBKEY].value;
695 		if (c[FINGERPRINTS].value != NULL)
696 			r->fingerprints = c[FINGERPRINTS].value;
697 		STAILQ_INSERT_TAIL(&repositories, r, next);
698 	}
699 	return (&repositories);
700 }
701 
702 void
703 config_finish(void) {
704 	int i;
705 
706 	for (i = 0; i < CONFIG_SIZE; i++)
707 		free(c[i].value);
708 }
709