Add basic pledge/unveil sandbox on OpenBSD
[tinc] / src / utils.c
1 /*
2     utils.c -- gathering of some stupid small functions
3     Copyright (C) 1999-2005 Ivo Timmermans
4                   2000-2013 Guus Sliepen <guus@tinc-vpn.org>
5
6     This program is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     This program is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License along
17     with this program; if not, write to the Free Software Foundation, Inc.,
18     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 */
20
21 #include <assert.h>
22
23 #include "logger.h"
24 #include "system.h"
25 #include "utils.h"
26 #include "xalloc.h"
27
28 static const char hexadecimals[] = "0123456789ABCDEF";
29 static const char base64_original[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
30 static const char base64_urlsafe[] =  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
31 static const char base64_decode[256] = {
32         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
33                 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
34                 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, 62, -1, 63,
35                 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
36                 -1,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
37                 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, 63,
38                 -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
39                 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1,
40                 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
41                 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
42                 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
43                 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
44                 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
45                 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
46                 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
47                 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
48         };
49
50 static uint8_t charhex2bin(char c) {
51         uint8_t cu = (uint8_t) c;
52
53         if(isdigit(cu)) {
54                 return cu - '0';
55         } else {
56                 return toupper(cu) - 'A' + 10;
57         }
58 }
59
60 size_t hex2bin(const char *src, void *vdst, size_t length) {
61         uint8_t *dst = vdst;
62         size_t i;
63
64         for(i = 0; i < length && isxdigit((uint8_t) src[i * 2]) && isxdigit((uint8_t) src[i * 2 + 1]); i++) {
65                 dst[i] = charhex2bin(src[i * 2]) * 16 + charhex2bin(src[i * 2 + 1]);
66         }
67
68         return i;
69 }
70
71 size_t bin2hex(const void *vsrc, char *dst, size_t length) {
72         const char *src = vsrc;
73
74         for(size_t i = length; i > 0;) {
75                 --i;
76                 dst[i * 2 + 1] = hexadecimals[(unsigned char) src[i] & 15];
77                 dst[i * 2] = hexadecimals[(unsigned char) src[i] >> 4];
78         }
79
80         dst[length * 2] = 0;
81         return length * 2;
82 }
83
84 char *absolute_path(const char *path) {
85 #ifdef HAVE_WINDOWS
86         // Works for nonexistent paths
87         return _fullpath(NULL, path, 0);
88 #else
89
90         if(!path || !*path) {
91                 return NULL;
92         }
93
94         // If an absolute path was passed, return its copy
95         if(*path == '/') {
96                 return xstrdup(path);
97         }
98
99         // Try using realpath. If it fails for any reason
100         // other than that the file was not found, bail out.
101         char *abs = realpath(path, NULL);
102
103         if(abs || errno != ENOENT) {
104                 return abs;
105         }
106
107         // Since the file does not exist, we're forced to use a fallback.
108         // Get current working directory and concatenate it with the argument.
109         char cwd[PATH_MAX];
110
111         if(!getcwd(cwd, sizeof(cwd))) {
112                 return NULL;
113         }
114
115         // Remove trailing slash if present since we'll be adding our own
116         size_t cwdlen = strlen(cwd);
117
118         if(cwdlen && cwd[cwdlen - 1] == '/') {
119                 cwd[cwdlen - 1] = '\0';
120         }
121
122         // We don't do any normalization because it's complicated, and the payoff is small.
123         // If user passed something like '.././../foo' — that's their choice; fopen works either way.
124         xasprintf(&abs, "%s/%s", cwd, path);
125
126         if(strlen(abs) >= PATH_MAX) {
127                 free(abs);
128                 abs = NULL;
129         }
130
131         return abs;
132 #endif
133 }
134
135 size_t b64decode_tinc(const char *src, void *dst, size_t length) {
136         size_t i;
137         uint32_t triplet = 0;
138         unsigned char *udst = (unsigned char *)dst;
139
140         for(i = 0; i < length && src[i]; i++) {
141                 triplet |= base64_decode[src[i] & 0xff] << (6 * (i & 3));
142
143                 if((i & 3) == 3) {
144                         if(triplet & 0xff000000U) {
145                                 return 0;
146                         }
147
148                         udst[0] = triplet & 0xff;
149                         triplet >>= 8;
150                         udst[1] = triplet & 0xff;
151                         triplet >>= 8;
152                         udst[2] = triplet;
153                         triplet = 0;
154                         udst += 3;
155                 }
156         }
157
158         if(triplet & 0xff000000U) {
159                 return 0;
160         }
161
162         if((i & 3) == 3) {
163                 udst[0] = triplet & 0xff;
164                 triplet >>= 8;
165                 udst[1] = triplet & 0xff;
166                 return i / 4 * 3 + 2;
167         } else if((i & 3) == 2) {
168                 udst[0] = triplet & 0xff;
169                 return i / 4 * 3 + 1;
170         } else {
171                 return i / 4 * 3;
172         }
173 }
174
175 bool is_decimal(const char *str) {
176         if(!str) {
177                 return false;
178         }
179
180         errno = 0;
181         char *badchar = NULL;
182         strtol(str, &badchar, 10);
183         return !errno && badchar != str && !*badchar;
184 }
185
186 // itoa() conflicts with a similarly named function under MinGW.
187 char *int_to_str(int num) {
188         char *str = NULL;
189         xasprintf(&str, "%d", num);
190         return str;
191 }
192
193 static size_t b64encode_tinc_internal(const void *src, char *dst, size_t length, const char *alphabet) {
194         uint32_t triplet;
195         const unsigned char *usrc = (unsigned char *)src;
196         size_t si = length / 3 * 3;
197         size_t di = length / 3 * 4;
198
199         switch(length % 3) {
200         case 2:
201                 triplet = usrc[si] | usrc[si + 1] << 8;
202                 dst[di] = alphabet[triplet & 63];
203                 triplet >>= 6;
204                 dst[di + 1] = alphabet[triplet & 63];
205                 triplet >>= 6;
206                 dst[di + 2] = alphabet[triplet];
207                 dst[di + 3] = 0;
208                 length = di + 3;
209                 break;
210
211         case 1:
212                 triplet = usrc[si];
213                 dst[di] = alphabet[triplet & 63];
214                 triplet >>= 6;
215                 dst[di + 1] = alphabet[triplet];
216                 dst[di + 2] = 0;
217                 length = di + 2;
218                 break;
219
220         default:
221                 dst[di] = 0;
222                 length = di;
223                 break;
224         }
225
226         while(si > 0) {
227                 di -= 4;
228                 si -= 3;
229                 triplet = usrc[si] | usrc[si + 1] << 8 | usrc[si + 2] << 16;
230                 dst[di] = alphabet[triplet & 63];
231                 triplet >>= 6;
232                 dst[di + 1] = alphabet[triplet & 63];
233                 triplet >>= 6;
234                 dst[di + 2] = alphabet[triplet & 63];
235                 triplet >>= 6;
236                 dst[di + 3] = alphabet[triplet];
237         }
238
239         return length;
240 }
241
242 size_t b64encode_tinc(const void *src, char *dst, size_t length) {
243         return b64encode_tinc_internal(src, dst, length, base64_original);
244 }
245
246 size_t b64encode_tinc_urlsafe(const void *src, char *dst, size_t length) {
247         return b64encode_tinc_internal(src, dst, length, base64_urlsafe);
248 }
249
250 #ifdef HAVE_WINDOWS
251 const char *winerror(int err) {
252         static char buf[1024], *ptr;
253
254         ptr = buf + snprintf(buf, sizeof(buf), "(%d) ", err);
255
256         if(!FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
257                           NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), ptr, sizeof(buf) - (ptr - buf), NULL)) {
258                 strncpy(buf, "(unable to format errormessage)", sizeof(buf));
259         };
260
261         if((ptr = strchr(buf, '\r'))) {
262                 *ptr = '\0';
263         }
264
265         return buf;
266 }
267 #endif
268
269 bool check_id(const char *id) {
270         if(!id || !*id) {
271                 return false;
272         }
273
274         for(; *id; id++)
275                 if(!isalnum((uint8_t) *id) && *id != '_') {
276                         return false;
277                 }
278
279         return true;
280 }
281
282 bool check_netname(const char *netname, bool strict) {
283         if(!netname || !*netname || *netname == '.') {
284                 return false;
285         }
286
287         for(const char *c = netname; *c; c++) {
288                 if(iscntrl((uint8_t) *c)) {
289                         return false;
290                 }
291
292                 if(*c == '/' || *c == '\\') {
293                         return false;
294                 }
295
296                 if(strict && strchr(" $%<>:`\"|?*", *c)) {
297                         return false;
298                 }
299         }
300
301         return true;
302 }
303
304 /* Windows doesn't define HOST_NAME_MAX. */
305 #ifndef HOST_NAME_MAX
306 #define HOST_NAME_MAX 255
307 #endif
308
309 char *replace_name(const char *name) {
310         char *ret_name;
311
312         if(name[0] == '$') {
313                 char *envname = getenv(name + 1);
314                 char hostname[HOST_NAME_MAX + 1];
315
316                 if(!envname) {
317                         if(strcmp(name + 1, "HOST")) {
318                                 logger(DEBUG_ALWAYS, LOG_ERR, "Invalid Name: environment variable %s does not exist\n", name + 1);
319                                 return NULL;
320                         }
321
322                         if(gethostname(hostname, sizeof(hostname)) || !*hostname) {
323                                 logger(DEBUG_ALWAYS, LOG_ERR, "Could not get hostname: %s\n", sockstrerror(sockerrno));
324                                 return NULL;
325                         }
326
327                         hostname[HOST_NAME_MAX] = 0;
328                         envname = hostname;
329                 }
330
331                 ret_name = xstrdup(envname);
332
333                 for(char *c = ret_name; *c; c++)
334                         if(!isalnum((uint8_t) *c)) {
335                                 *c = '_';
336                         }
337         } else {
338                 ret_name = xstrdup(name);
339         }
340
341         if(!check_id(ret_name)) {
342                 logger(DEBUG_ALWAYS, LOG_ERR, "Invalid name for myself!");
343                 free(ret_name);
344                 return NULL;
345         }
346
347         return ret_name;
348 }
349
350 /* Open a file with the desired permissions, minus the umask.
351    Also, if we want to create an executable file, we call fchmod()
352    to set the executable bits. */
353
354 FILE *fopenmask(const char *filename, const char *mode, mode_t perms) {
355         mode_t mask = umask(0);
356         perms &= ~mask;
357         umask(~perms & 0777);
358         FILE *f = fopen(filename, mode);
359
360         if(!f) {
361                 fprintf(stderr, "Could not open %s: %s\n", filename, strerror(errno));
362                 return NULL;
363         }
364
365 #ifdef HAVE_FCHMOD
366
367         if(perms & 0444) {
368                 fchmod(fileno(f), perms);
369         }
370
371 #endif
372         umask(mask);
373         return f;
374 }
375
376 bool string_eq(const char *first, const char *second) {
377         return !first == !second &&
378                !(first && second && strcmp(first, second));
379 }