]> git.proxmox.com Git - systemd.git/blame - src/basic/replace-var.c
New upstream version 236
[systemd.git] / src / basic / replace-var.c
CommitLineData
52ad194e 1/* SPDX-License-Identifier: LGPL-2.1+ */
663996b3
MS
2/***
3 This file is part of systemd.
4
5 Copyright 2012 Lennart Poettering
6
7 systemd is free software; you can redistribute it and/or modify it
8 under the terms of the GNU Lesser General Public License as published by
9 the Free Software Foundation; either version 2.1 of the License, or
10 (at your option) any later version.
11
12 systemd is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 Lesser General Public License for more details.
16
17 You should have received a copy of the GNU Lesser General Public License
18 along with systemd; If not, see <http://www.gnu.org/licenses/>.
19***/
20
4c89c718
MP
21#include <errno.h>
22#include <stddef.h>
23#include <stdlib.h>
663996b3
MS
24#include <string.h>
25
db2df898 26#include "alloc-util.h"
663996b3 27#include "macro.h"
663996b3 28#include "replace-var.h"
db2df898 29#include "string-util.h"
663996b3
MS
30
31/*
32 * Generic infrastructure for replacing @FOO@ style variables in
33 * strings. Will call a callback for each replacement.
34 */
35
36static int get_variable(const char *b, char **r) {
37 size_t k;
38 char *t;
39
40 assert(b);
41 assert(r);
42
43 if (*b != '@')
44 return 0;
45
14228c0d 46 k = strspn(b + 1, UPPERCASE_LETTERS "_");
663996b3
MS
47 if (k <= 0 || b[k+1] != '@')
48 return 0;
49
50 t = strndup(b + 1, k);
51 if (!t)
52 return -ENOMEM;
53
54 *r = t;
55 return 1;
56}
57
f5e65279 58char *replace_var(const char *text, char *(*lookup)(const char *variable, void *userdata), void *userdata) {
663996b3
MS
59 char *r, *t;
60 const char *f;
61 size_t l;
62
63 assert(text);
64 assert(lookup);
65
66 l = strlen(text);
67 r = new(char, l+1);
68 if (!r)
69 return NULL;
70
71 f = text;
72 t = r;
73 while (*f) {
74 _cleanup_free_ char *v = NULL, *n = NULL;
75 char *a;
76 int k;
77 size_t skip, d, nl;
78
79 k = get_variable(f, &v);
80 if (k < 0)
81 goto oom;
82 if (k == 0) {
83 *(t++) = *(f++);
84 continue;
85 }
86
87 n = lookup(v, userdata);
88 if (!n)
89 goto oom;
90
91 skip = strlen(v) + 2;
92
93 d = t - r;
94 nl = l - skip + strlen(n);
95 a = realloc(r, nl + 1);
96 if (!a)
97 goto oom;
98
99 l = nl;
100 r = a;
101 t = r + d;
102
103 t = stpcpy(t, n);
104 f += skip;
105 }
106
107 *t = 0;
108 return r;
109
110oom:
8a584da2 111 return mfree(r);
663996b3 112}