helpers.c 9.0 KB

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