helpers.c 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. /*
  2. * Helper functions used by other modules
  3. */
  4. #ifndef _CRT_SECURE_NO_WARNINGS
  5. #define _CRT_SECURE_NO_WARNINGS
  6. #endif
  7. #ifndef CONFIG
  8. #define CONFIG "config.h"
  9. #endif // CONFIG
  10. #include CONFIG
  11. #ifndef _WIN32
  12. #include <errno.h>
  13. #endif // _WIN32
  14. #ifndef _MSC_VER
  15. #include <getopt.h>
  16. #else
  17. #include "wingetopt.h"
  18. #endif
  19. #include <string.h>
  20. #include <stdlib.h>
  21. #include <ctype.h>
  22. #include "helpers.h"
  23. #include "output.h"
  24. #include "endian.h"
  25. #include "shared_globals.h"
  26. /*
  27. * UCS2 <-> UTF-8 functions
  28. * All functions use little endian UCS2 since we only need it to communicate with Windows via RPC
  29. */
  30. // Convert one character from UTF-8 to UCS2
  31. // Returns 0xffff, if utf-8 evaluates to > 0xfffe (outside basic multilingual pane)
  32. WCHAR utf8_to_ucs2_char (const unsigned char *input, const unsigned char **end_ptr)
  33. {
  34. *end_ptr = input;
  35. if (input[0] == 0)
  36. return ~0;
  37. if (input[0] < 0x80) {
  38. *end_ptr = input + 1;
  39. return LE16(input[0]);
  40. }
  41. if ((input[0] & 0xE0) == 0xE0) {
  42. if (input[1] == 0 || input[2] == 0)
  43. return ~0;
  44. *end_ptr = input + 3;
  45. return
  46. LE16((input[0] & 0x0F)<<12 |
  47. (input[1] & 0x3F)<<6 |
  48. (input[2] & 0x3F));
  49. }
  50. if ((input[0] & 0xC0) == 0xC0) {
  51. if (input[1] == 0)
  52. return ~0;
  53. *end_ptr = input + 2;
  54. return
  55. LE16((input[0] & 0x1F)<<6 |
  56. (input[1] & 0x3F));
  57. }
  58. return ~0;
  59. }
  60. // Convert one character from UCS2 to UTF-8
  61. // Returns length of UTF-8 char (1, 2 or 3) or -1 on error (UTF-16 outside UCS2)
  62. // char *utf8 must be large enough to hold 3 bytes
  63. int ucs2_to_utf8_char (const WCHAR ucs2_le, char *utf8)
  64. {
  65. const WCHAR ucs2 = LE16(ucs2_le);
  66. if (ucs2 < 0x80) {
  67. utf8[0] = (char)ucs2;
  68. utf8[1] = '\0';
  69. return 1;
  70. }
  71. if (ucs2 >= 0x80 && ucs2 < 0x800) {
  72. utf8[0] = (ucs2 >> 6) | 0xC0;
  73. utf8[1] = (ucs2 & 0x3F) | 0x80;
  74. utf8[2] = '\0';
  75. return 2;
  76. }
  77. if (ucs2 >= 0x800 && ucs2 < 0xFFFF) {
  78. if (ucs2 >= 0xD800 && ucs2 <= 0xDFFF) {
  79. /* Ill-formed (UTF-16 ouside of BMP) */
  80. return -1;
  81. }
  82. utf8[0] = ((ucs2 >> 12) ) | 0xE0;
  83. utf8[1] = ((ucs2 >> 6 ) & 0x3F) | 0x80;
  84. utf8[2] = ((ucs2 ) & 0x3F) | 0x80;
  85. utf8[3] = '\0';
  86. return 3;
  87. }
  88. return -1;
  89. }
  90. // Converts UTF8 to UCS2. Returns size in bytes of the converted string or -1 on error
  91. size_t utf8_to_ucs2(WCHAR* const ucs2_le, const char* const utf8, const size_t maxucs2, const size_t maxutf8)
  92. {
  93. const unsigned char* current_utf8 = (unsigned char*)utf8;
  94. WCHAR* current_ucs2_le = ucs2_le;
  95. for (; *current_utf8; current_ucs2_le++)
  96. {
  97. size_t size = (char*)current_utf8 - utf8;
  98. if (size >= maxutf8) return (size_t)-1;
  99. if (((*current_utf8 & 0xc0) == 0xc0) && (size >= maxutf8 - 1)) return (size_t)-1;
  100. if (((*current_utf8 & 0xe0) == 0xe0) && (size >= maxutf8 - 2)) return (size_t)-1;
  101. if (current_ucs2_le - ucs2_le >= (intptr_t)maxucs2 - 1) return (size_t)-1;
  102. *current_ucs2_le = utf8_to_ucs2_char(current_utf8, &current_utf8);
  103. current_ucs2_le[1] = 0;
  104. if (*current_ucs2_le == (WCHAR)-1) return (size_t)-1;
  105. }
  106. return current_ucs2_le - ucs2_le;
  107. }
  108. // Converts UCS2 to UTF-8. Return TRUE or FALSE
  109. BOOL ucs2_to_utf8(const WCHAR* const ucs2_le, char* utf8, size_t maxucs2, size_t maxutf8)
  110. {
  111. char utf8_char[4];
  112. const WCHAR* current_ucs2 = ucs2_le;
  113. unsigned int index_utf8 = 0;
  114. for(*utf8 = 0; *current_ucs2; current_ucs2++)
  115. {
  116. if (current_ucs2 - ucs2_le > (intptr_t)maxucs2) return FALSE;
  117. int len = ucs2_to_utf8_char(*current_ucs2, utf8_char);
  118. if (index_utf8 + len > maxutf8) return FALSE;
  119. strncat(utf8, utf8_char, len);
  120. index_utf8+=len;
  121. }
  122. return TRUE;
  123. }
  124. /* End of UTF-8 <-> UCS2 conversion */
  125. // Checks, whether a string is a valid integer number between min and max. Returns TRUE or FALSE. Puts int value in *value
  126. BOOL stringToInt(const char *const szValue, const unsigned int min, const unsigned int max, unsigned int *const value)
  127. {
  128. char *nextchar;
  129. errno = 0;
  130. long long result = vlmcsd_strtoll(szValue, &nextchar, 10);
  131. if (errno || result < (long long)min || result > (long long)max || *nextchar)
  132. {
  133. return FALSE;
  134. }
  135. *value = (unsigned int)result;
  136. return TRUE;
  137. }
  138. //Converts a String Guid to a host binary guid in host endianess
  139. int_fast8_t string2Uuid(const char *const restrict input, GUID *const restrict guid)
  140. {
  141. int i;
  142. if (strlen(input) < GUID_STRING_LENGTH) return FALSE;
  143. if (input[8] != '-' || input[13] != '-' || input[18] != '-' || input[23] != '-') return FALSE;
  144. for (i = 0; i < GUID_STRING_LENGTH; i++)
  145. {
  146. if (i == 8 || i == 13 || i == 18 || i == 23) continue;
  147. const char c = (char)toupper((int)input[i]);
  148. if (c < '0' || c > 'F' || (c > '9' && c < 'A')) return FALSE;
  149. }
  150. char inputCopy[GUID_STRING_LENGTH + 1];
  151. strncpy(inputCopy, input, GUID_STRING_LENGTH + 1);
  152. inputCopy[8] = inputCopy[13] = inputCopy[18] = 0;
  153. hex2bin((BYTE*)&guid->Data1, inputCopy, 8);
  154. hex2bin((BYTE*)&guid->Data2, inputCopy + 9, 4);
  155. hex2bin((BYTE*)&guid->Data3, inputCopy + 14, 4);
  156. hex2bin(guid->Data4, input + 19, 16);
  157. guid->Data1 = BE32(guid->Data1);
  158. guid->Data2 = BE16(guid->Data2);
  159. guid->Data3 = BE16(guid->Data3);
  160. return TRUE;
  161. }
  162. // convert GUID to little-endian
  163. void LEGUID(GUID *const restrict out, const GUID* const restrict in)
  164. {
  165. #if __BYTE_ORDER != __LITTLE_ENDIAN
  166. out->Data1 = LE32(in->Data1);
  167. out->Data2 = LE16(in->Data2);
  168. out->Data3 = LE16(in->Data3);
  169. memcpy(out->Data4, in->Data4, sizeof(out->Data4));
  170. #else
  171. memcpy(out, in, sizeof(GUID));
  172. #endif
  173. }
  174. #if !IS_LIBRARY
  175. //Checks a command line argument if it is numeric and between min and max. Returns the numeric value or exits on error
  176. __pure unsigned int getOptionArgumentInt(const char o, const unsigned int min, const unsigned int max)
  177. {
  178. unsigned int result;
  179. if (!stringToInt(optarg, min, max, &result))
  180. {
  181. printerrorf("Fatal: Option \"-%c\" must be numeric between %u and %u.\n", o, min, max);
  182. exit(!0);
  183. }
  184. return result;
  185. }
  186. // Resets getopt() to start parsing from the beginning
  187. void optReset(void)
  188. {
  189. #if __minix__ || defined(__BSD__) || defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__) || defined(__OpenBSD__)
  190. optind = 1;
  191. optreset = 1; // Makes newer BSD getopt happy
  192. #elif defined(__UCLIBC__) // uClibc headers also define __GLIBC__ so be careful here
  193. optind = 0; // uClibc seeks compatibility with GLIBC
  194. #elif defined(__GLIBC__)
  195. optind = 0; // Makes GLIBC getopt happy
  196. #else // Standard for most systems
  197. optind = 1;
  198. #endif
  199. }
  200. #endif // !IS_LIBRARY
  201. #if defined(_WIN32) || defined(USE_MSRPC)
  202. // Returns a static message buffer containing text for a given Win32 error. Not thread safe (same as strerror)
  203. char* win_strerror(const int message)
  204. {
  205. #define STRERROR_BUFFER_SIZE 256
  206. static char buffer[STRERROR_BUFFER_SIZE];
  207. FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK, NULL, message, 0, buffer, STRERROR_BUFFER_SIZE, NULL);
  208. return buffer;
  209. }
  210. #endif // defined(_WIN32) || defined(USE_MSRPC)
  211. /*
  212. * parses an address in the form host:[port] in addr
  213. * returns host and port in seperate strings
  214. */
  215. void parseAddress(char *const addr, char** szHost, char** szPort)
  216. {
  217. *szHost = addr;
  218. # ifndef NO_SOCKETS
  219. *szPort = (char*)defaultport;
  220. # else // NO_SOCKETS
  221. *szPort = "1688";
  222. # endif // NO_SOCKETS
  223. char *lastcolon = strrchr(addr, ':');
  224. char *firstcolon = strchr(addr, ':');
  225. char *closingbracket = strrchr(addr, ']');
  226. if (*addr == '[' && closingbracket) //Address in brackets
  227. {
  228. *closingbracket = 0;
  229. (*szHost)++;
  230. if (closingbracket[1] == ':')
  231. *szPort = closingbracket + 2;
  232. }
  233. else if (firstcolon && firstcolon == lastcolon) //IPv4 address or hostname with port
  234. {
  235. *firstcolon = 0;
  236. *szPort = firstcolon + 1;
  237. }
  238. }
  239. // Initialize random generator (needs to be done in each thread)
  240. void randomNumberInit()
  241. {
  242. # if _MSC_VER
  243. srand(GetTickCount());
  244. # else
  245. struct timeval tv;
  246. gettimeofday(&tv, NULL);
  247. srand((unsigned int)(tv.tv_sec ^ tv.tv_usec));
  248. # endif
  249. }
  250. // We always exit immediately if any OOM condition occurs
  251. __noreturn void OutOfMemory(void)
  252. {
  253. errorout("Fatal: Out of memory");
  254. exit(!0);
  255. }
  256. void* vlmcsd_malloc(size_t len)
  257. {
  258. void* buf = malloc(len);
  259. if (!buf) OutOfMemory();
  260. return buf;
  261. }
  262. /*
  263. * Converts hex digits to bytes in big-endian order.
  264. * Ignores any non-hex characters
  265. */
  266. void hex2bin(BYTE *const bin, const char *hex, const size_t maxbin)
  267. {
  268. static const char *const hexdigits = "0123456789ABCDEF";
  269. char* nextchar;
  270. size_t i;
  271. for (i = 0; (i < 16) && utf8_to_ucs2_char((const unsigned char*)hex, (const unsigned char**)&nextchar) != (WCHAR)-1; hex = nextchar)
  272. {
  273. const char* pos = strchr(hexdigits, toupper((int)*hex));
  274. if (!pos) continue;
  275. if (!(i & 1)) bin[i >> 1] = 0;
  276. bin[i >> 1] |= (char)(pos - hexdigits);
  277. if (!(i & 1)) bin[i >> 1] <<= 4;
  278. i++;
  279. if (i >> 1 > maxbin) break;
  280. }
  281. }
  282. __pure BOOL getArgumentBool(int_fast8_t *result, const char *const argument)
  283. {
  284. if (
  285. !strncasecmp(argument, "true", 4) ||
  286. !strncasecmp(argument, "on", 2) ||
  287. !strncasecmp(argument, "yes", 3) ||
  288. !strncasecmp(argument, "1", 1)
  289. )
  290. {
  291. *result = TRUE;
  292. return TRUE;
  293. }
  294. else if (
  295. !strncasecmp(argument, "false", 5) ||
  296. !strncasecmp(argument, "off", 3) ||
  297. !strncasecmp(argument, "no", 2) ||
  298. !strncasecmp(argument, "0", 1)
  299. )
  300. {
  301. *result = FALSE;
  302. return TRUE;
  303. }
  304. return FALSE;
  305. }