posix.c revision 4ee47af0e535676100380034dbc5e05c2f1b1642
1/* This file contains functions which implement those POSIX and Linux functions
2 * that MinGW and Microsoft don't provide. The implementations contain just enough
3 * functionality to support fio.
4 */
5
6#include <arpa/inet.h>
7#include <netinet/in.h>
8#include <windows.h>
9#include <stddef.h>
10#include <string.h>
11#include <stdlib.h>
12#include <unistd.h>
13#include <dirent.h>
14#include <pthread.h>
15#include <semaphore.h>
16#include <sys/shm.h>
17#include <sys/mman.h>
18#include <sys/uio.h>
19#include <sys/resource.h>
20#include <sys/poll.h>
21
22#include "../os-windows.h"
23#include "../../lib/hweight.h"
24
25extern unsigned long mtime_since_now(struct timeval *);
26extern void fio_gettime(struct timeval *, void *);
27
28/* These aren't defined in the MinGW headers */
29HRESULT WINAPI StringCchCopyA(
30  char *pszDest,
31  size_t cchDest,
32  const char *pszSrc);
33
34HRESULT WINAPI StringCchPrintfA(
35  char *pszDest,
36  size_t cchDest,
37  const char *pszFormat,
38  ...);
39
40int vsprintf_s(
41  char *buffer,
42  size_t numberOfElements,
43  const char *format,
44  va_list argptr);
45
46int GetNumLogicalProcessors(void)
47{
48	SYSTEM_LOGICAL_PROCESSOR_INFORMATION *processor_info = NULL;
49	DWORD len = 0;
50	DWORD num_processors = 0;
51	DWORD error = 0;
52	DWORD i;
53
54	while (!GetLogicalProcessorInformation(processor_info, &len)) {
55		error = GetLastError();
56		if (error == ERROR_INSUFFICIENT_BUFFER)
57			processor_info = malloc(len);
58		else {
59			log_err("Error: GetLogicalProcessorInformation failed: %d\n", error);
60			return -1;
61		}
62
63		if (processor_info == NULL) {
64			log_err("Error: failed to allocate memory for GetLogicalProcessorInformation");
65			return -1;
66		}
67	}
68
69	for (i = 0; i < len / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION); i++)
70	{
71		if (processor_info[i].Relationship == RelationProcessorCore)
72			num_processors += hweight64(processor_info[i].ProcessorMask);
73	}
74
75	free(processor_info);
76	return num_processors;
77}
78
79long sysconf(int name)
80{
81	long val = -1;
82	SYSTEM_INFO sysInfo;
83	MEMORYSTATUSEX status;
84
85	switch (name)
86	{
87	case _SC_NPROCESSORS_ONLN:
88		val = GetNumLogicalProcessors();
89		if (val == -1)
90			log_err("_SC_NPROCESSORS_ONLN failed\n");
91
92		break;
93
94	case _SC_PAGESIZE:
95		GetSystemInfo(&sysInfo);
96		val = sysInfo.dwPageSize;
97		break;
98
99	case _SC_PHYS_PAGES:
100		status.dwLength = sizeof(status);
101		GlobalMemoryStatusEx(&status);
102		val = status.ullTotalPhys;
103		break;
104	default:
105		log_err("sysconf(%d) is not implemented\n", name);
106		break;
107	}
108
109	return val;
110}
111
112char *dl_error = NULL;
113
114int dlclose(void *handle)
115{
116	return !FreeLibrary((HMODULE)handle);
117}
118
119void *dlopen(const char *file, int mode)
120{
121	HMODULE hMod;
122
123	hMod = LoadLibrary(file);
124	if (hMod == INVALID_HANDLE_VALUE)
125		dl_error = (char*)"LoadLibrary failed";
126	else
127		dl_error = NULL;
128
129	return hMod;
130}
131
132void *dlsym(void *handle, const char *name)
133{
134	FARPROC fnPtr;
135
136	fnPtr = GetProcAddress((HMODULE)handle, name);
137	if (fnPtr == NULL)
138		dl_error = (char*)"GetProcAddress failed";
139	else
140		dl_error = NULL;
141
142	return fnPtr;
143}
144
145char *dlerror(void)
146{
147	return dl_error;
148}
149
150int gettimeofday(struct timeval *restrict tp, void *restrict tzp)
151{
152	FILETIME fileTime;
153	uint64_t unix_time, windows_time;
154	const uint64_t MILLISECONDS_BETWEEN_1601_AND_1970 = 11644473600000;
155
156	/* Ignore the timezone parameter */
157	(void)tzp;
158
159	/*
160	 * Windows time is stored as the number 100 ns intervals since January 1 1601.
161	 * Conversion details from http://www.informit.com/articles/article.aspx?p=102236&seqNum=3
162	 * Its precision is 100 ns but accuracy is only one clock tick, or normally around 15 ms.
163	 */
164	GetSystemTimeAsFileTime(&fileTime);
165	windows_time = ((uint64_t)fileTime.dwHighDateTime << 32) + fileTime.dwLowDateTime;
166	/* Divide by 10,000 to convert to ms and subtract the time between 1601 and 1970 */
167	unix_time = (((windows_time)/10000) - MILLISECONDS_BETWEEN_1601_AND_1970);
168	/* unix_time is now the number of milliseconds since 1970 (the Unix epoch) */
169	tp->tv_sec = unix_time / 1000;
170	tp->tv_usec = (unix_time % 1000) * 1000;
171	return 0;
172}
173
174int sigaction(int sig, const struct sigaction *act,
175		struct sigaction *oact)
176{
177	int rc = 0;
178	void (*prev_handler)(int);
179
180	prev_handler = signal(sig, act->sa_handler);
181	if (oact != NULL)
182		oact->sa_handler = prev_handler;
183
184	if (prev_handler == SIG_ERR)
185		rc = -1;
186
187	return rc;
188}
189
190int lstat(const char * path, struct stat * buf)
191{
192	return stat(path, buf);
193}
194
195void *mmap(void *addr, size_t len, int prot, int flags,
196		int fildes, off_t off)
197{
198	DWORD vaProt = 0;
199	void* allocAddr = NULL;
200
201	if (prot & PROT_NONE)
202		vaProt |= PAGE_NOACCESS;
203
204	if ((prot & PROT_READ) && !(prot & PROT_WRITE))
205		vaProt |= PAGE_READONLY;
206
207	if (prot & PROT_WRITE)
208		vaProt |= PAGE_READWRITE;
209
210	if ((flags & MAP_ANON) | (flags & MAP_ANONYMOUS))
211	{
212		allocAddr = VirtualAlloc(addr, len, MEM_COMMIT, vaProt);
213	}
214
215	return allocAddr;
216}
217
218int munmap(void *addr, size_t len)
219{
220	return !VirtualFree(addr, 0, MEM_RELEASE);
221}
222
223int fork(void)
224{
225	log_err("%s is not implemented\n", __func__);
226	errno = ENOSYS;
227	return (-1);
228}
229
230pid_t setsid(void)
231{
232	log_err("%s is not implemented\n", __func__);
233	errno = ENOSYS;
234	return (-1);
235}
236
237static HANDLE log_file = INVALID_HANDLE_VALUE;
238
239void openlog(const char *ident, int logopt, int facility)
240{
241	if (log_file == INVALID_HANDLE_VALUE)
242		log_file = CreateFileA("syslog.txt", GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, 0, NULL);
243}
244
245void closelog(void)
246{
247	CloseHandle(log_file);
248	log_file = INVALID_HANDLE_VALUE;
249}
250
251void syslog(int priority, const char *message, ... /* argument */)
252{
253	va_list v;
254	int len;
255	char *output;
256	DWORD bytes_written;
257
258	if (log_file == INVALID_HANDLE_VALUE) {
259		log_file = CreateFileA("syslog.txt", GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, 0, NULL);
260	}
261
262	if (log_file == INVALID_HANDLE_VALUE) {
263		log_err("syslog: failed to open log file\n");
264		return;
265	}
266
267	va_start(v, message);
268	len = _vscprintf(message, v);
269	output = malloc(len + sizeof(char));
270	vsprintf(output, message, v);
271	WriteFile(log_file, output, len, &bytes_written, NULL);
272	va_end(v);
273	free(output);
274}
275
276int kill(pid_t pid, int sig)
277{
278	errno = ESRCH;
279	return (-1);
280}
281
282/*
283 * This is assumed to be used only by the network code,
284 * and so doesn't try and handle any of the other cases
285 */
286int fcntl(int fildes, int cmd, ...)
287{
288	/*
289	 * non-blocking mode doesn't work the same as in BSD sockets,
290	 * so ignore it.
291	 */
292#if 0
293	va_list ap;
294	int val, opt, status;
295
296	if (cmd == F_GETFL)
297		return 0;
298	else if (cmd != F_SETFL) {
299		errno = EINVAL;
300		return (-1);
301	}
302
303	va_start(ap, 1);
304
305	opt = va_arg(ap, int);
306	if (opt & O_NONBLOCK)
307		val = 1;
308	else
309		val = 0;
310
311	status = ioctlsocket((SOCKET)fildes, opt, &val);
312
313	if (status == SOCKET_ERROR) {
314		errno = EINVAL;
315		val = -1;
316	}
317
318	va_end(ap);
319
320	return val;
321#endif
322return 0;
323}
324
325/*
326 * Get the value of a local clock source.
327 * This implementation supports 2 clocks: CLOCK_MONOTONIC provides high-accuracy
328 * relative time, while CLOCK_REALTIME provides a low-accuracy wall time.
329 */
330int clock_gettime(clockid_t clock_id, struct timespec *tp)
331{
332	int rc = 0;
333
334	if (clock_id == CLOCK_MONOTONIC)
335	{
336		static LARGE_INTEGER freq = {{0,0}};
337		LARGE_INTEGER counts;
338
339		QueryPerformanceCounter(&counts);
340		if (freq.QuadPart == 0)
341			QueryPerformanceFrequency(&freq);
342
343		tp->tv_sec = counts.QuadPart / freq.QuadPart;
344		/* Get the difference between the number of ns stored
345		 * in 'tv_sec' and that stored in 'counts' */
346		uint64_t t = tp->tv_sec * freq.QuadPart;
347		t = counts.QuadPart - t;
348		/* 't' now contains the number of cycles since the last second.
349		 * We want the number of nanoseconds, so multiply out by 1,000,000,000
350		 * and then divide by the frequency. */
351		t *= 1000000000;
352		tp->tv_nsec = t / freq.QuadPart;
353	}
354	else if (clock_id == CLOCK_REALTIME)
355	{
356		/* clock_gettime(CLOCK_REALTIME,...) is just an alias for gettimeofday with a
357		 * higher-precision field. */
358		struct timeval tv;
359		gettimeofday(&tv, NULL);
360		tp->tv_sec = tv.tv_sec;
361		tp->tv_nsec = tv.tv_usec * 1000;
362	} else {
363		errno = EINVAL;
364		rc = -1;
365	}
366
367	return rc;
368}
369
370int mlock(const void * addr, size_t len)
371{
372	return !VirtualLock((LPVOID)addr, len);
373}
374
375int munlock(const void * addr, size_t len)
376{
377	return !VirtualUnlock((LPVOID)addr, len);
378}
379
380pid_t waitpid(pid_t pid, int *stat_loc, int options)
381{
382	log_err("%s is not implemented\n", __func__);
383	errno = ENOSYS;
384	return -1;
385}
386
387int usleep(useconds_t useconds)
388{
389	Sleep(useconds / 1000);
390	return 0;
391}
392
393char *basename(char *path)
394{
395	static char name[MAX_PATH];
396	int i;
397
398	if (path == NULL || strlen(path) == 0)
399		return (char*)".";
400
401	i = strlen(path) - 1;
402
403	while (path[i] != '\\' && path[i] != '/' && i >= 0)
404		i--;
405
406	strncpy(name, path + i + 1, MAX_PATH);
407
408	return name;
409}
410
411int posix_fallocate(int fd, off_t offset, off_t len)
412{
413	const int BUFFER_SIZE = 256 * 1024;
414	int rc = 0;
415	char *buf;
416	unsigned int write_len;
417	unsigned int bytes_written;
418	off_t bytes_remaining = len;
419
420	if (len == 0 || offset < 0)
421		return EINVAL;
422
423	buf = malloc(BUFFER_SIZE);
424
425	if (buf == NULL)
426		return ENOMEM;
427
428	memset(buf, 0, BUFFER_SIZE);
429
430	int64_t prev_pos = _telli64(fd);
431
432	if (_lseeki64(fd, offset, SEEK_SET) == -1)
433		return errno;
434
435	while (bytes_remaining > 0) {
436		if (bytes_remaining < BUFFER_SIZE)
437			write_len = (unsigned int)bytes_remaining;
438		else
439			write_len = BUFFER_SIZE;
440
441		bytes_written = _write(fd, buf, write_len);
442		if (bytes_written == -1) {
443			rc = errno;
444			break;
445		}
446
447		/* Don't allow Windows to cache the write: flush it to disk */
448		_commit(fd);
449
450		bytes_remaining -= bytes_written;
451	}
452
453	free(buf);
454	_lseeki64(fd, prev_pos, SEEK_SET);
455	return rc;
456}
457
458int ftruncate(int fildes, off_t length)
459{
460	BOOL bSuccess;
461	int64_t prev_pos = _telli64(fildes);
462	_lseeki64(fildes, length, SEEK_SET);
463	HANDLE hFile = (HANDLE)_get_osfhandle(fildes);
464	bSuccess = SetEndOfFile(hFile);
465	_lseeki64(fildes, prev_pos, SEEK_SET);
466	return !bSuccess;
467}
468
469int fsync(int fildes)
470{
471	HANDLE hFile = (HANDLE)_get_osfhandle(fildes);
472	return !FlushFileBuffers(hFile);
473}
474
475int nFileMappings = 0;
476HANDLE fileMappings[1024];
477
478int shmget(key_t key, size_t size, int shmflg)
479{
480	int mapid = -1;
481	uint32_t size_low = size & 0xFFFFFFFF;
482	uint32_t size_high = ((uint64_t)size) >> 32;
483	HANDLE hMapping = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, (PAGE_EXECUTE_READWRITE | SEC_RESERVE), size_high, size_low, NULL);
484	if (hMapping != NULL) {
485		fileMappings[nFileMappings] = hMapping;
486		mapid = nFileMappings;
487		nFileMappings++;
488	} else {
489		errno = ENOSYS;
490	}
491
492	return mapid;
493}
494
495void *shmat(int shmid, const void *shmaddr, int shmflg)
496{
497	void* mapAddr;
498	MEMORY_BASIC_INFORMATION memInfo;
499	mapAddr = MapViewOfFile(fileMappings[shmid], FILE_MAP_ALL_ACCESS, 0, 0, 0);
500	VirtualQuery(mapAddr, &memInfo, sizeof(memInfo));
501	mapAddr = VirtualAlloc(mapAddr, memInfo.RegionSize, MEM_COMMIT, PAGE_READWRITE);
502	return mapAddr;
503}
504
505int shmdt(const void *shmaddr)
506{
507	return !UnmapViewOfFile(shmaddr);
508}
509
510int shmctl(int shmid, int cmd, struct shmid_ds *buf)
511{
512	if (cmd == IPC_RMID) {
513		fileMappings[shmid] = INVALID_HANDLE_VALUE;
514		return 0;
515	} else {
516		log_err("%s is not implemented\n", __func__);
517	}
518	return (-1);
519}
520
521int setuid(uid_t uid)
522{
523	log_err("%s is not implemented\n", __func__);
524	errno = ENOSYS;
525	return (-1);
526}
527
528int setgid(gid_t gid)
529{
530	log_err("%s is not implemented\n", __func__);
531	errno = ENOSYS;
532	return (-1);
533}
534
535int nice(int incr)
536{
537	if (incr != 0) {
538		errno = EINVAL;
539		return -1;
540	}
541
542	return 0;
543}
544
545int getrusage(int who, struct rusage *r_usage)
546{
547	const uint64_t SECONDS_BETWEEN_1601_AND_1970 = 11644473600;
548	FILETIME cTime, eTime, kTime, uTime;
549	time_t time;
550
551	memset(r_usage, 0, sizeof(*r_usage));
552
553	HANDLE hProcess = GetCurrentProcess();
554	GetProcessTimes(hProcess, &cTime, &eTime, &kTime, &uTime);
555	time = ((uint64_t)uTime.dwHighDateTime << 32) + uTime.dwLowDateTime;
556	/* Divide by 10,000,000 to get the number of seconds and move the epoch from
557	 * 1601 to 1970 */
558	time = (time_t)(((time)/10000000) - SECONDS_BETWEEN_1601_AND_1970);
559	r_usage->ru_utime.tv_sec = time;
560	/* getrusage() doesn't care about anything other than seconds, so set tv_usec to 0 */
561	r_usage->ru_utime.tv_usec = 0;
562	time = ((uint64_t)kTime.dwHighDateTime << 32) + kTime.dwLowDateTime;
563	/* Divide by 10,000,000 to get the number of seconds and move the epoch from
564	 * 1601 to 1970 */
565	time = (time_t)(((time)/10000000) - SECONDS_BETWEEN_1601_AND_1970);
566	r_usage->ru_stime.tv_sec = time;
567	r_usage->ru_stime.tv_usec = 0;
568	return 0;
569}
570
571int posix_fadvise(int fd, off_t offset, off_t len, int advice)
572{
573	return 0;
574}
575
576int posix_madvise(void *addr, size_t len, int advice)
577{
578	log_err("%s is not implemented\n", __func__);
579	return ENOSYS;
580}
581
582/* Windows doesn't support advice for memory pages. Just ignore it. */
583int msync(void *addr, size_t len, int flags)
584{
585	errno = ENOSYS;
586	return -1;
587}
588
589int fdatasync(int fildes)
590{
591	return fsync(fildes);
592}
593
594ssize_t pwrite(int fildes, const void *buf, size_t nbyte,
595		off_t offset)
596{
597	int64_t pos = _telli64(fildes);
598	ssize_t len = _write(fildes, buf, nbyte);
599	_lseeki64(fildes, pos, SEEK_SET);
600	return len;
601}
602
603ssize_t pread(int fildes, void *buf, size_t nbyte, off_t offset)
604{
605	int64_t pos = _telli64(fildes);
606	ssize_t len = read(fildes, buf, nbyte);
607	_lseeki64(fildes, pos, SEEK_SET);
608	return len;
609}
610
611ssize_t readv(int fildes, const struct iovec *iov, int iovcnt)
612{
613	log_err("%s is not implemented\n", __func__);
614	errno = ENOSYS;
615	return (-1);
616}
617
618ssize_t writev(int fildes, const struct iovec *iov, int iovcnt)
619{
620	log_err("%s is not implemented\n", __func__);
621	errno = ENOSYS;
622	return (-1);
623}
624
625long long strtoll(const char *restrict str, char **restrict endptr,
626		int base)
627{
628	return _strtoi64(str, endptr, base);
629}
630
631char *strsep(char **stringp, const char *delim)
632{
633	char *orig = *stringp;
634	BOOL gotMatch = FALSE;
635	int i = 0;
636	int j = 0;
637
638	if (*stringp == NULL)
639		return NULL;
640
641	while ((*stringp)[i] != '\0') {
642		j = 0;
643		while (delim[j] != '\0') {
644			if ((*stringp)[i] == delim[j]) {
645				gotMatch = TRUE;
646				(*stringp)[i] = '\0';
647				*stringp = *stringp + i + 1;
648				break;
649			}
650			j++;
651		}
652		if (gotMatch)
653			break;
654
655		i++;
656	}
657
658	if (!gotMatch)
659		*stringp = NULL;
660
661	return orig;
662}
663
664int poll(struct pollfd fds[], nfds_t nfds, int timeout)
665{
666	struct timeval tv;
667	struct timeval *to = NULL;
668	fd_set readfds, writefds, exceptfds;
669	int i;
670	int rc;
671
672	if (timeout != -1) {
673		to = &tv;
674		to->tv_sec = timeout / 1000;
675		to->tv_usec = (timeout % 1000) * 1000;
676	}
677
678	FD_ZERO(&readfds);
679	FD_ZERO(&writefds);
680	FD_ZERO(&exceptfds);
681
682	for (i = 0; i < nfds; i++)
683	{
684		if (fds[i].fd < 0) {
685			fds[i].revents = 0;
686			continue;
687		}
688
689		if (fds[i].events & POLLIN)
690			FD_SET(fds[i].fd, &readfds);
691
692		if (fds[i].events & POLLOUT)
693			FD_SET(fds[i].fd, &writefds);
694
695		FD_SET(fds[i].fd, &exceptfds);
696	}
697
698	rc = select(nfds, &readfds, &writefds, &exceptfds, to);
699
700	if (rc != SOCKET_ERROR) {
701		for (i = 0; i < nfds; i++)
702		{
703			if (fds[i].fd < 0) {
704				continue;
705			}
706
707			if ((fds[i].events & POLLIN) && FD_ISSET(fds[i].fd, &readfds))
708				fds[i].revents |= POLLIN;
709
710			if ((fds[i].events & POLLOUT) && FD_ISSET(fds[i].fd, &writefds))
711				fds[i].revents |= POLLOUT;
712
713			if (FD_ISSET(fds[i].fd, &exceptfds))
714				fds[i].revents |= POLLHUP;
715		}
716	}
717
718	return rc;
719}
720
721int nanosleep(const struct timespec *rqtp, struct timespec *rmtp)
722{
723	struct timeval tv;
724	DWORD ms_remaining;
725	DWORD ms_total = (rqtp->tv_sec * 1000) + (rqtp->tv_nsec / 1000000.0);
726
727	if (ms_total == 0)
728		ms_total = 1;
729
730	ms_remaining = ms_total;
731
732	/* Since Sleep() can sleep for less than the requested time, add a loop to
733	   ensure we only return after the requested length of time has elapsed */
734	do {
735		fio_gettime(&tv, NULL);
736		Sleep(ms_remaining);
737		ms_remaining = ms_total - mtime_since_now(&tv);
738	} while (ms_remaining > 0 && ms_remaining < ms_total);
739
740	/* this implementation will never sleep for less than the requested time */
741	if (rmtp != NULL) {
742		rmtp->tv_sec = 0;
743		rmtp->tv_nsec = 0;
744	}
745
746	return 0;
747}
748
749DIR *opendir(const char *dirname)
750{
751    struct dirent_ctx *dc = NULL;
752
753    /* See if we can open it. If not, we'll return an error here */
754    HANDLE file = CreateFileA(dirname, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
755    if (file != INVALID_HANDLE_VALUE) {
756        CloseHandle(file);
757        dc = (struct dirent_ctx*)malloc(sizeof(struct dirent_ctx));
758        StringCchCopyA(dc->dirname, MAX_PATH, dirname);
759        dc->find_handle = INVALID_HANDLE_VALUE;
760    } else {
761        DWORD error = GetLastError();
762        if (error == ERROR_FILE_NOT_FOUND)
763            errno = ENOENT;
764
765        else if (error == ERROR_PATH_NOT_FOUND)
766            errno = ENOTDIR;
767        else if (error == ERROR_TOO_MANY_OPEN_FILES)
768            errno = ENFILE;
769        else if (error == ERROR_ACCESS_DENIED)
770            errno = EACCES;
771        else
772            errno = error;
773    }
774
775    return dc;
776}
777
778int closedir(DIR *dirp)
779{
780    if (dirp != NULL && dirp->find_handle != INVALID_HANDLE_VALUE)
781        FindClose(dirp->find_handle);
782
783    free(dirp);
784    return 0;
785}
786
787struct dirent *readdir(DIR *dirp)
788{
789	static struct dirent de;
790	WIN32_FIND_DATA find_data;
791
792	if (dirp == NULL)
793		return NULL;
794
795	if (dirp->find_handle == INVALID_HANDLE_VALUE) {
796		char search_pattern[MAX_PATH];
797		StringCchPrintfA(search_pattern, MAX_PATH, "%s\\*", dirp->dirname);
798		dirp->find_handle = FindFirstFileA(search_pattern, &find_data);
799		if (dirp->find_handle == INVALID_HANDLE_VALUE)
800			return NULL;
801	} else {
802		if (!FindNextFile(dirp->find_handle, &find_data))
803			return NULL;
804	}
805
806	StringCchCopyA(de.d_name, MAX_PATH, find_data.cFileName);
807	de.d_ino = 0;
808
809	return &de;
810}
811
812uid_t geteuid(void)
813{
814	log_err("%s is not implemented\n", __func__);
815	errno = ENOSYS;
816	return -1;
817}
818
819const char* inet_ntop(int af, const void *restrict src,
820		char *restrict dst, socklen_t size)
821{
822	INT status = SOCKET_ERROR;
823	WSADATA wsd;
824	char *ret = NULL;
825
826	if (af != AF_INET && af != AF_INET6) {
827		errno = EAFNOSUPPORT;
828		return NULL;
829	}
830
831	WSAStartup(MAKEWORD(2,2), &wsd);
832
833	if (af == AF_INET) {
834		struct sockaddr_in si;
835		DWORD len = size;
836		memset(&si, 0, sizeof(si));
837		si.sin_family = af;
838		memcpy(&si.sin_addr, src, sizeof(si.sin_addr));
839		status = WSAAddressToString((struct sockaddr*)&si, sizeof(si), NULL, dst, &len);
840	} else if (af == AF_INET6) {
841		struct sockaddr_in6 si6;
842		DWORD len = size;
843		memset(&si6, 0, sizeof(si6));
844		si6.sin6_family = af;
845		memcpy(&si6.sin6_addr, src, sizeof(si6.sin6_addr));
846		status = WSAAddressToString((struct sockaddr*)&si6, sizeof(si6), NULL, dst, &len);
847	}
848
849	if (status != SOCKET_ERROR)
850		ret = dst;
851	else
852		errno = ENOSPC;
853
854	WSACleanup();
855
856	return ret;
857}
858
859int inet_pton(int af, const char *restrict src, void *restrict dst)
860{
861	INT status = SOCKET_ERROR;
862	WSADATA wsd;
863	int ret = 1;
864
865	if (af != AF_INET && af != AF_INET6) {
866		errno = EAFNOSUPPORT;
867		return -1;
868	}
869
870	WSAStartup(MAKEWORD(2,2), &wsd);
871
872	if (af == AF_INET) {
873		struct sockaddr_in si;
874		INT len = sizeof(si);
875		memset(&si, 0, sizeof(si));
876		si.sin_family = af;
877		status = WSAStringToAddressA((char*)src, af, NULL, (struct sockaddr*)&si, &len);
878		if (status != SOCKET_ERROR)
879			memcpy(dst, &si.sin_addr, sizeof(si.sin_addr));
880	} else if (af == AF_INET6) {
881		struct sockaddr_in6 si6;
882		INT len = sizeof(si6);
883		memset(&si6, 0, sizeof(si6));
884		si6.sin6_family = af;
885		status = WSAStringToAddressA((char*)src, af, NULL, (struct sockaddr*)&si6, &len);
886		if (status != SOCKET_ERROR)
887			memcpy(dst, &si6.sin6_addr, sizeof(si6.sin6_addr));
888	}
889
890	if (status == SOCKET_ERROR) {
891		errno = ENOSPC;
892		ret = 0;
893	}
894
895	WSACleanup();
896
897	return ret;
898}
899