1/*
2 * OS specific functions for UNIX/POSIX systems
3 * Copyright (c) 2005-2019, Jouni Malinen <j@w1.fi>
4 *
5 * This software may be distributed under the terms of the BSD license.
6 * See README for more details.
7 */
8
9#include "includes.h"
10
11#include <time.h>
12#include <sys/wait.h>
13
14#ifdef ANDROID
15#include <sys/capability.h>
16#include <sys/prctl.h>
17#include <private/android_filesystem_config.h>
18#endif /* ANDROID */
19
20#ifdef __MACH__
21#include <CoreServices/CoreServices.h>
22#include <mach/mach.h>
23#include <mach/mach_time.h>
24#endif /* __MACH__ */
25
26#include "os.h"
27#include "common.h"
28
29#ifdef WPA_TRACE
30
31#include "wpa_debug.h"
32#include "trace.h"
33#include "list.h"
34
35static struct dl_list alloc_list = DL_LIST_HEAD_INIT(alloc_list);
36
37#define ALLOC_MAGIC 0xa84ef1b2
38#define FREED_MAGIC 0x67fd487a
39
40struct os_alloc_trace {
41	unsigned int magic;
42	struct dl_list list;
43	size_t len;
44	WPA_TRACE_INFO
45} __attribute__((aligned(16)));
46
47#endif /* WPA_TRACE */
48
49
50void os_sleep(os_time_t sec, os_time_t usec)
51{
52	if (sec)
53		sleep(sec);
54	if (usec)
55		usleep(usec);
56}
57
58
59int os_get_time(struct os_time *t)
60{
61	int res;
62	struct timeval tv;
63	res = gettimeofday(&tv, NULL);
64	t->sec = tv.tv_sec;
65	t->usec = tv.tv_usec;
66	return res;
67}
68
69
70int os_get_reltime(struct os_reltime *t)
71{
72#ifndef __MACH__
73#if defined(CLOCK_BOOTTIME)
74	static clockid_t clock_id = CLOCK_BOOTTIME;
75#elif defined(CLOCK_MONOTONIC)
76	static clockid_t clock_id = CLOCK_MONOTONIC;
77#else
78	static clockid_t clock_id = CLOCK_REALTIME;
79#endif
80	struct timespec ts;
81	int res;
82
83	if (TEST_FAIL())
84		return -1;
85
86	while (1) {
87		res = clock_gettime(clock_id, &ts);
88		if (res == 0) {
89			t->sec = ts.tv_sec;
90			t->usec = ts.tv_nsec / 1000;
91			return 0;
92		}
93		switch (clock_id) {
94#ifdef CLOCK_BOOTTIME
95		case CLOCK_BOOTTIME:
96			clock_id = CLOCK_MONOTONIC;
97			break;
98#endif
99#ifdef CLOCK_MONOTONIC
100		case CLOCK_MONOTONIC:
101			clock_id = CLOCK_REALTIME;
102			break;
103#endif
104		case CLOCK_REALTIME:
105			return -1;
106		}
107	}
108#else /* __MACH__ */
109	uint64_t abstime, nano;
110	static mach_timebase_info_data_t info = { 0, 0 };
111
112	if (!info.denom) {
113		if (mach_timebase_info(&info) != KERN_SUCCESS)
114			return -1;
115	}
116
117	abstime = mach_absolute_time();
118	nano = (abstime * info.numer) / info.denom;
119
120	t->sec = nano / NSEC_PER_SEC;
121	t->usec = (nano - (((uint64_t) t->sec) * NSEC_PER_SEC)) / NSEC_PER_USEC;
122
123	return 0;
124#endif /* __MACH__ */
125}
126
127
128int os_mktime(int year, int month, int day, int hour, int min, int sec,
129	      os_time_t *t)
130{
131	struct tm tm, *tm1;
132	time_t t_local, t1, t2;
133	os_time_t tz_offset;
134
135	if (year < 1970 || month < 1 || month > 12 || day < 1 || day > 31 ||
136	    hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 ||
137	    sec > 60)
138		return -1;
139
140	memset(&tm, 0, sizeof(tm));
141	tm.tm_year = year - 1900;
142	tm.tm_mon = month - 1;
143	tm.tm_mday = day;
144	tm.tm_hour = hour;
145	tm.tm_min = min;
146	tm.tm_sec = sec;
147
148	t_local = mktime(&tm);
149
150	/* figure out offset to UTC */
151	tm1 = localtime(&t_local);
152	if (tm1) {
153		t1 = mktime(tm1);
154		tm1 = gmtime(&t_local);
155		if (tm1) {
156			t2 = mktime(tm1);
157			tz_offset = t2 - t1;
158		} else
159			tz_offset = 0;
160	} else
161		tz_offset = 0;
162
163	*t = (os_time_t) t_local - tz_offset;
164	return 0;
165}
166
167
168int os_gmtime(os_time_t t, struct os_tm *tm)
169{
170	struct tm *tm2;
171	time_t t2 = t;
172
173	tm2 = gmtime(&t2);
174	if (tm2 == NULL)
175		return -1;
176	tm->sec = tm2->tm_sec;
177	tm->min = tm2->tm_min;
178	tm->hour = tm2->tm_hour;
179	tm->day = tm2->tm_mday;
180	tm->month = tm2->tm_mon + 1;
181	tm->year = tm2->tm_year + 1900;
182	return 0;
183}
184
185
186#ifdef __APPLE__
187#include <fcntl.h>
188static int os_daemon(int nochdir, int noclose)
189{
190	int devnull;
191
192	if (chdir("/") < 0)
193		return -1;
194
195	devnull = open("/dev/null", O_RDWR);
196	if (devnull < 0)
197		return -1;
198
199	if (dup2(devnull, STDIN_FILENO) < 0) {
200		close(devnull);
201		return -1;
202	}
203
204	if (dup2(devnull, STDOUT_FILENO) < 0) {
205		close(devnull);
206		return -1;
207	}
208
209	if (dup2(devnull, STDERR_FILENO) < 0) {
210		close(devnull);
211		return -1;
212	}
213
214	return 0;
215}
216#else /* __APPLE__ */
217#define os_daemon daemon
218#endif /* __APPLE__ */
219
220
221int os_daemonize(const char *pid_file)
222{
223#if defined(__uClinux__) || defined(__sun__)
224	return -1;
225#else /* defined(__uClinux__) || defined(__sun__) */
226	if (os_daemon(0, 0)) {
227		perror("daemon");
228		return -1;
229	}
230
231	if (pid_file) {
232		FILE *f = fopen(pid_file, "w");
233		if (f) {
234			fprintf(f, "%u\n", getpid());
235			fclose(f);
236		}
237	}
238
239	return -0;
240#endif /* defined(__uClinux__) || defined(__sun__) */
241}
242
243
244void os_daemonize_terminate(const char *pid_file)
245{
246	if (pid_file)
247		unlink(pid_file);
248}
249
250
251int os_get_random(unsigned char *buf, size_t len)
252{
253#ifdef TEST_FUZZ
254	size_t i;
255
256	for (i = 0; i < len; i++)
257		buf[i] = i & 0xff;
258	return 0;
259#else /* TEST_FUZZ */
260	FILE *f;
261	size_t rc;
262
263	if (TEST_FAIL())
264		return -1;
265
266	f = fopen("/dev/urandom", "rb");
267	if (f == NULL) {
268		printf("Could not open /dev/urandom.\n");
269		return -1;
270	}
271
272	rc = fread(buf, 1, len, f);
273	fclose(f);
274
275	return rc != len ? -1 : 0;
276#endif /* TEST_FUZZ */
277}
278
279
280unsigned long os_random(void)
281{
282	return random();
283}
284
285
286char * os_rel2abs_path(const char *rel_path)
287{
288	char *buf = NULL, *cwd, *ret;
289	size_t len = 128, cwd_len, rel_len, ret_len;
290	int last_errno;
291
292	if (!rel_path)
293		return NULL;
294
295	if (rel_path[0] == '/')
296		return os_strdup(rel_path);
297
298	for (;;) {
299		buf = os_malloc(len);
300		if (buf == NULL)
301			return NULL;
302		cwd = getcwd(buf, len);
303		if (cwd == NULL) {
304			last_errno = errno;
305			os_free(buf);
306			if (last_errno != ERANGE)
307				return NULL;
308			len *= 2;
309			if (len > 2000)
310				return NULL;
311		} else {
312			buf[len - 1] = '\0';
313			break;
314		}
315	}
316
317	cwd_len = os_strlen(cwd);
318	rel_len = os_strlen(rel_path);
319	ret_len = cwd_len + 1 + rel_len + 1;
320	ret = os_malloc(ret_len);
321	if (ret) {
322		os_memcpy(ret, cwd, cwd_len);
323		ret[cwd_len] = '/';
324		os_memcpy(ret + cwd_len + 1, rel_path, rel_len);
325		ret[ret_len - 1] = '\0';
326	}
327	os_free(buf);
328	return ret;
329}
330
331
332int os_program_init(void)
333{
334#ifdef ANDROID
335	/*
336	 * We ignore errors here since errors are normal if we
337	 * are already running as non-root.
338	 */
339#ifdef ANDROID_SETGROUPS_OVERRIDE
340	gid_t groups[] = { ANDROID_SETGROUPS_OVERRIDE };
341#else /* ANDROID_SETGROUPS_OVERRIDE */
342	gid_t groups[] = { AID_INET, AID_WIFI, AID_KEYSTORE };
343#endif /* ANDROID_SETGROUPS_OVERRIDE */
344	struct __user_cap_header_struct header;
345	struct __user_cap_data_struct cap;
346
347	setgroups(ARRAY_SIZE(groups), groups);
348
349	prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0);
350
351	setgid(AID_WIFI);
352	setuid(AID_WIFI);
353
354	header.version = _LINUX_CAPABILITY_VERSION;
355	header.pid = 0;
356	cap.effective = cap.permitted =
357		(1 << CAP_NET_ADMIN) | (1 << CAP_NET_RAW);
358	cap.inheritable = 0;
359	capset(&header, &cap);
360#endif /* ANDROID */
361
362	return 0;
363}
364
365
366void os_program_deinit(void)
367{
368#ifdef WPA_TRACE
369	struct os_alloc_trace *a;
370	unsigned long total = 0;
371	dl_list_for_each(a, &alloc_list, struct os_alloc_trace, list) {
372		total += a->len;
373		if (a->magic != ALLOC_MAGIC) {
374			wpa_printf(MSG_INFO, "MEMLEAK[%p]: invalid magic 0x%x "
375				   "len %lu",
376				   a, a->magic, (unsigned long) a->len);
377			continue;
378		}
379		wpa_printf(MSG_INFO, "MEMLEAK[%p]: len %lu",
380			   a, (unsigned long) a->len);
381		wpa_trace_dump("memleak", a);
382	}
383	if (total)
384		wpa_printf(MSG_INFO, "MEMLEAK: total %lu bytes",
385			   (unsigned long) total);
386	wpa_trace_deinit();
387#endif /* WPA_TRACE */
388}
389
390
391int os_setenv(const char *name, const char *value, int overwrite)
392{
393	return setenv(name, value, overwrite);
394}
395
396
397int os_unsetenv(const char *name)
398{
399#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__APPLE__) || \
400    defined(__OpenBSD__)
401	unsetenv(name);
402	return 0;
403#else
404	return unsetenv(name);
405#endif
406}
407
408
409char * os_readfile(const char *name, size_t *len)
410{
411	FILE *f;
412	char *buf;
413	long pos;
414
415	f = fopen(name, "rb");
416	if (f == NULL)
417		return NULL;
418
419	if (fseek(f, 0, SEEK_END) < 0 || (pos = ftell(f)) < 0) {
420		fclose(f);
421		return NULL;
422	}
423	*len = pos;
424	if (fseek(f, 0, SEEK_SET) < 0) {
425		fclose(f);
426		return NULL;
427	}
428
429	buf = os_malloc(*len);
430	if (buf == NULL) {
431		fclose(f);
432		return NULL;
433	}
434
435	if (fread(buf, 1, *len, f) != *len) {
436		fclose(f);
437		os_free(buf);
438		return NULL;
439	}
440
441	fclose(f);
442
443	return buf;
444}
445
446
447int os_file_exists(const char *fname)
448{
449	return access(fname, F_OK) == 0;
450}
451
452
453int os_fdatasync(FILE *stream)
454{
455	if (!fflush(stream)) {
456#ifdef __linux__
457		return fdatasync(fileno(stream));
458#else /* !__linux__ */
459#ifdef F_FULLFSYNC
460		/* OS X does not implement fdatasync(). */
461		return fcntl(fileno(stream), F_FULLFSYNC);
462#else /* F_FULLFSYNC */
463		return fsync(fileno(stream));
464#endif /* F_FULLFSYNC */
465#endif /* __linux__ */
466	}
467
468	return -1;
469}
470
471
472#ifndef WPA_TRACE
473void * os_zalloc(size_t size)
474{
475	return calloc(1, size);
476}
477#endif /* WPA_TRACE */
478
479
480size_t os_strlcpy(char *dest, const char *src, size_t siz)
481{
482	const char *s = src;
483	size_t left = siz;
484
485	if (left) {
486		/* Copy string up to the maximum size of the dest buffer */
487		while (--left != 0) {
488			if ((*dest++ = *s++) == '\0')
489				break;
490		}
491	}
492
493	if (left == 0) {
494		/* Not enough room for the string; force NUL-termination */
495		if (siz != 0)
496			*dest = '\0';
497		while (*s++)
498			; /* determine total src string length */
499	}
500
501	return s - src - 1;
502}
503
504
505int os_memcmp_const(const void *a, const void *b, size_t len)
506{
507	const u8 *aa = a;
508	const u8 *bb = b;
509	size_t i;
510	u8 res;
511
512	for (res = 0, i = 0; i < len; i++)
513		res |= aa[i] ^ bb[i];
514
515	return res;
516}
517
518
519void * os_memdup(const void *src, size_t len)
520{
521	void *r = os_malloc(len);
522
523	if (r && src)
524		os_memcpy(r, src, len);
525	return r;
526}
527
528
529#ifdef WPA_TRACE
530
531#if defined(WPA_TRACE_BFD) && defined(CONFIG_TESTING_OPTIONS)
532char wpa_trace_fail_func[256] = { 0 };
533unsigned int wpa_trace_fail_after;
534
535static int testing_fail_alloc(void)
536{
537	const char *func[WPA_TRACE_LEN];
538	size_t i, res, len;
539	char *pos, *next;
540	int match;
541
542	if (!wpa_trace_fail_after)
543		return 0;
544
545	res = wpa_trace_calling_func(func, WPA_TRACE_LEN);
546	i = 0;
547	if (i < res && os_strcmp(func[i], __func__) == 0)
548		i++;
549	if (i < res && os_strcmp(func[i], "os_malloc") == 0)
550		i++;
551	if (i < res && os_strcmp(func[i], "os_zalloc") == 0)
552		i++;
553	if (i < res && os_strcmp(func[i], "os_calloc") == 0)
554		i++;
555	if (i < res && os_strcmp(func[i], "os_realloc") == 0)
556		i++;
557	if (i < res && os_strcmp(func[i], "os_realloc_array") == 0)
558		i++;
559	if (i < res && os_strcmp(func[i], "os_strdup") == 0)
560		i++;
561	if (i < res && os_strcmp(func[i], "os_memdup") == 0)
562		i++;
563
564	pos = wpa_trace_fail_func;
565
566	match = 0;
567	while (i < res) {
568		int allow_skip = 1;
569		int maybe = 0;
570
571		if (*pos == '=') {
572			allow_skip = 0;
573			pos++;
574		} else if (*pos == '?') {
575			maybe = 1;
576			pos++;
577		}
578		next = os_strchr(pos, ';');
579		if (next)
580			len = next - pos;
581		else
582			len = os_strlen(pos);
583		if (os_memcmp(pos, func[i], len) != 0) {
584			if (maybe && next) {
585				pos = next + 1;
586				continue;
587			}
588			if (allow_skip) {
589				i++;
590				continue;
591			}
592			return 0;
593		}
594		if (!next) {
595			match = 1;
596			break;
597		}
598		pos = next + 1;
599		i++;
600	}
601	if (!match)
602		return 0;
603
604	wpa_trace_fail_after--;
605	if (wpa_trace_fail_after == 0) {
606		wpa_printf(MSG_INFO, "TESTING: fail allocation at %s",
607			   wpa_trace_fail_func);
608		for (i = 0; i < res; i++)
609			wpa_printf(MSG_INFO, "backtrace[%d] = %s",
610				   (int) i, func[i]);
611		return 1;
612	}
613
614	return 0;
615}
616
617
618char wpa_trace_test_fail_func[256] = { 0 };
619unsigned int wpa_trace_test_fail_after;
620
621int testing_test_fail(void)
622{
623	const char *func[WPA_TRACE_LEN];
624	size_t i, res, len;
625	char *pos, *next;
626	int match;
627
628	if (!wpa_trace_test_fail_after)
629		return 0;
630
631	res = wpa_trace_calling_func(func, WPA_TRACE_LEN);
632	i = 0;
633	if (i < res && os_strcmp(func[i], __func__) == 0)
634		i++;
635
636	pos = wpa_trace_test_fail_func;
637
638	match = 0;
639	while (i < res) {
640		int allow_skip = 1;
641		int maybe = 0;
642
643		if (*pos == '=') {
644			allow_skip = 0;
645			pos++;
646		} else if (*pos == '?') {
647			maybe = 1;
648			pos++;
649		}
650		next = os_strchr(pos, ';');
651		if (next)
652			len = next - pos;
653		else
654			len = os_strlen(pos);
655		if (os_memcmp(pos, func[i], len) != 0) {
656			if (maybe && next) {
657				pos = next + 1;
658				continue;
659			}
660			if (allow_skip) {
661				i++;
662				continue;
663			}
664			return 0;
665		}
666		if (!next) {
667			match = 1;
668			break;
669		}
670		pos = next + 1;
671		i++;
672	}
673	if (!match)
674		return 0;
675
676	wpa_trace_test_fail_after--;
677	if (wpa_trace_test_fail_after == 0) {
678		wpa_printf(MSG_INFO, "TESTING: fail at %s",
679			   wpa_trace_test_fail_func);
680		for (i = 0; i < res; i++)
681			wpa_printf(MSG_INFO, "backtrace[%d] = %s",
682				   (int) i, func[i]);
683		return 1;
684	}
685
686	return 0;
687}
688
689#else
690
691static inline int testing_fail_alloc(void)
692{
693	return 0;
694}
695#endif
696
697void * os_malloc(size_t size)
698{
699	struct os_alloc_trace *a;
700
701	if (testing_fail_alloc())
702		return NULL;
703
704	a = malloc(sizeof(*a) + size);
705	if (a == NULL)
706		return NULL;
707	a->magic = ALLOC_MAGIC;
708	dl_list_add(&alloc_list, &a->list);
709	a->len = size;
710	wpa_trace_record(a);
711	return a + 1;
712}
713
714
715void * os_realloc(void *ptr, size_t size)
716{
717	struct os_alloc_trace *a;
718	size_t copy_len;
719	void *n;
720
721	if (ptr == NULL)
722		return os_malloc(size);
723
724	a = (struct os_alloc_trace *) ptr - 1;
725	if (a->magic != ALLOC_MAGIC) {
726		wpa_printf(MSG_INFO, "REALLOC[%p]: invalid magic 0x%x%s",
727			   a, a->magic,
728			   a->magic == FREED_MAGIC ? " (already freed)" : "");
729		wpa_trace_show("Invalid os_realloc() call");
730		abort();
731	}
732	n = os_malloc(size);
733	if (n == NULL)
734		return NULL;
735	copy_len = a->len;
736	if (copy_len > size)
737		copy_len = size;
738	os_memcpy(n, a + 1, copy_len);
739	os_free(ptr);
740	return n;
741}
742
743
744void os_free(void *ptr)
745{
746	struct os_alloc_trace *a;
747
748	if (ptr == NULL)
749		return;
750	a = (struct os_alloc_trace *) ptr - 1;
751	if (a->magic != ALLOC_MAGIC) {
752		wpa_printf(MSG_INFO, "FREE[%p]: invalid magic 0x%x%s",
753			   a, a->magic,
754			   a->magic == FREED_MAGIC ? " (already freed)" : "");
755		wpa_trace_show("Invalid os_free() call");
756		abort();
757	}
758	dl_list_del(&a->list);
759	a->magic = FREED_MAGIC;
760
761	wpa_trace_check_ref(ptr);
762	free(a);
763}
764
765
766void * os_zalloc(size_t size)
767{
768	void *ptr = os_malloc(size);
769	if (ptr)
770		os_memset(ptr, 0, size);
771	return ptr;
772}
773
774
775char * os_strdup(const char *s)
776{
777	size_t len;
778	char *d;
779	len = os_strlen(s);
780	d = os_malloc(len + 1);
781	if (d == NULL)
782		return NULL;
783	os_memcpy(d, s, len);
784	d[len] = '\0';
785	return d;
786}
787
788#endif /* WPA_TRACE */
789
790
791int os_exec(const char *program, const char *arg, int wait_completion)
792{
793	pid_t pid;
794	int pid_status;
795
796	pid = fork();
797	if (pid < 0) {
798		perror("fork");
799		return -1;
800	}
801
802	if (pid == 0) {
803		/* run the external command in the child process */
804#define MAX_ARG 30
805		char *_program, *_arg, *pos;
806		char *argv[MAX_ARG + 1];
807		int i;
808
809		_program = os_strdup(program);
810		_arg = os_strdup(arg);
811
812		argv[0] = _program;
813
814		i = 1;
815		pos = _arg;
816		while (i < MAX_ARG && pos && *pos) {
817			while (*pos == ' ')
818				pos++;
819			if (*pos == '\0')
820				break;
821			argv[i++] = pos;
822			pos = os_strchr(pos, ' ');
823			if (pos)
824				*pos++ = '\0';
825		}
826		argv[i] = NULL;
827
828		execv(program, argv);
829		perror("execv");
830		os_free(_program);
831		os_free(_arg);
832		exit(0);
833		return -1;
834	}
835
836	if (wait_completion) {
837		/* wait for the child process to complete in the parent */
838		waitpid(pid, &pid_status, 0);
839	}
840
841	return 0;
842}
843