1 /**
2 	Utility definitions for socket handling.
3 
4 	Copyright: © 2013 RejectedSoftware e.K.
5 	Authors: Sönke Ludwig
6 	License: Subject to the terms of the MIT license, as written in the included LICENSE.txt file.
7 */
8 module vibe.core.drivers.utils;
9 
10 import std.exception;
11 
12 version (Windows) {
13 	import core.sys.windows.windows;
14 	import core.sys.windows.winsock2;
15 
16 	alias EWOULDBLOCK = WSAEWOULDBLOCK;
17 
18 	extern(System) DWORD FormatMessageW(DWORD dwFlags, const(void)* lpSource, DWORD dwMessageId, DWORD dwLanguageId, LPWSTR lpBuffer, DWORD nSize, void* Arguments);
19 
20 	class WSAErrorException : Exception {
21 		int error;
22 
23 		this(string message, string file = __FILE__, size_t line = __LINE__)
24 		{
25 			error = WSAGetLastError();
26 			this(message, error, file, line);
27 		}
28 
29 		this(string message, int error, string file = __FILE__, size_t line = __LINE__)
30 		{
31 			import std.string : format;
32 			ushort* errmsg;
33 			FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,
34 						   null, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), cast(LPWSTR)&errmsg, 0, null);
35 			size_t len = 0;
36 			while (errmsg[len]) len++;
37 			auto errmsgd = (cast(wchar[])errmsg[0 .. len]).idup;
38 			LocalFree(errmsg);
39 			super(format("%s: %s (%s)", message, errmsgd, error), file, line);
40 		}
41 	}
42 
43 	alias SystemSocketException = WSAErrorException;
44 } else alias SystemSocketException = ErrnoException;
45 
46 version (linux) {
47 	import core.sys.posix.sys.socket;
48 	static if (!is(typeof(SO_REUSEPORT))) {
49 		enum { SO_REUSEPORT = 15 }
50 	}
51 }
52 
53 T socketEnforce(T)(T value, lazy string msg = null, string file = __FILE__, size_t line = __LINE__)
54 @trusted {
55 	return enforceEx!SystemSocketException(value, msg, file, line);
56 }