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