#include <9pm/windows.h>
#include <9pm/u.h>
#include <9pm/libc.h>

/*
 * Windows socket error messages
 * There must be a way to get these strings out of the library.
 * This table is derived from the MSDN online help.
 */
static struct {
	int e;
	char *s;
} tab[] = {
	{ 10004, "interrupted function call" },
	{ 10013, "permission denied" },
	{ 10014, "bad address" },
	{ 10022, "invalid argument" },
	{ 10024, "too many open files" },
	{ 10035, "resource temporarily unavailable" },
	{ 10036, "operation now in progress" },
	{ 10037, "operation already in progress" },
	{ 10038, "socket operation on nonsocket" },
	{ 10039, "destination address required" },
	{ 10040, "message too long" },
	{ 10041, "protocol wrong type for socket" },
	{ 10042, "bad protocol option" },
	{ 10043, "protocol not supported" },
	{ 10044, "socket type not supported" },
	{ 10045, "operation not supported" },
	{ 10046, "protocol family not supported" },
	{ 10047, "address family not supported by protocol family" },
	{ 10048, "address already in use" },
	{ 10049, "cannot assign requested address" },
	{ 10050, "network is down" },
	{ 10051, "network is unreachable" },
	{ 10052, "network dropped connection on reset" },
	{ 10053, "software caused connection abort" },
	{ 10054, "connection reset by peer" },
	{ 10055, "no buffer space available" },
	{ 10056, "socket is already connected" },
	{ 10057, "socket is not connected" },
	{ 10058, "cannot send after socket shutdown" },
	{ 10060, "connection timed out" },
	{ 10061, "connection refused" },
	{ 10064, "host is down" },
	{ 10065, "no route to host" },
	{ 10067, "too many processes" },
	{ 10091, "network subsystem is unavailable" },
	{ 10092, "winsock.dll version out of range" },
	{ 10093, "wsastartup not called" },
	{ 10101, "graceful shutdown in progress" },
	{ 10109, "class type not found" },
	{ 11001, "host name not found" },
	{ 11002, "host not found (non-authoritative)" },
	{ 11003, "nonrecoverable error" },
	{ 11004, "valid name, but no data record of requested type" },
};

void
pm_osrerrstr(char *buf, uint nbuf)
{
	char *p, *q;
	int e, i, r;

	e = GetLastError();
	r = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM,
		0, e, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
		buf, nbuf, 0);
	if(r == 0){
		for(i=0; i<nelem(tab); i++)
			if(tab[i].e == e){
				strecpy(buf, buf+nbuf, tab[i].s);
				break;
			}
		if(i==nelem(tab))
			snprint(buf, nbuf, "windows error %d", e);
	}

	for(p=q=buf; *p; p++) {
		if(*p == '\r')
			continue;
		if(*p == '\n')
			*q++ = ' ';
		else
			*q++ = *p;
	}
	*q = '\0';
}


syntax highlighted by Code2HTML, v. 0.9.1