tool_doswin.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
  9. *
  10. * This software is licensed as described in the file COPYING, which
  11. * you should have received as part of this distribution. The terms
  12. * are also available at https://curl.se/docs/copyright.html.
  13. *
  14. * You may opt to use, copy, modify, merge, publish, distribute and/or sell
  15. * copies of the Software, and permit persons to whom the Software is
  16. * furnished to do so, under the terms of the COPYING file.
  17. *
  18. * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  19. * KIND, either express or implied.
  20. *
  21. * SPDX-License-Identifier: curl
  22. *
  23. ***************************************************************************/
  24. #include "tool_setup.h"
  25. #if defined(_WIN32) || defined(MSDOS)
  26. #if defined(HAVE_LIBGEN_H) && defined(HAVE_BASENAME)
  27. # include <libgen.h>
  28. #endif
  29. #ifdef _WIN32
  30. # include <stdlib.h>
  31. # include <tlhelp32.h>
  32. # include "tool_cfgable.h"
  33. # include "tool_libinfo.h"
  34. #endif
  35. #include "tool_bname.h"
  36. #include "tool_doswin.h"
  37. #include "curlx.h"
  38. #include "memdebug.h" /* keep this as LAST include */
  39. #ifdef _WIN32
  40. # undef PATH_MAX
  41. # define PATH_MAX MAX_PATH
  42. #endif
  43. #ifndef S_ISCHR
  44. # ifdef S_IFCHR
  45. # define S_ISCHR(m) (((m) & S_IFMT) == S_IFCHR)
  46. # else
  47. # define S_ISCHR(m) (0) /* cannot tell if file is a device */
  48. # endif
  49. #endif
  50. #ifdef _WIN32
  51. # define _use_lfn(f) (1) /* long file names always available */
  52. #elif !defined(__DJGPP__) || (__DJGPP__ < 2) /* DJGPP 2.0 has _use_lfn() */
  53. # define _use_lfn(f) (0) /* long file names never available */
  54. #elif defined(__DJGPP__)
  55. # include <fcntl.h> /* _use_lfn(f) prototype */
  56. #endif
  57. #ifndef UNITTESTS
  58. static SANITIZEcode truncate_dryrun(const char *path,
  59. const size_t truncate_pos);
  60. #ifdef MSDOS
  61. static SANITIZEcode msdosify(char **const sanitized, const char *file_name,
  62. int flags);
  63. #endif
  64. static SANITIZEcode rename_if_reserved_dos_device_name(char **const sanitized,
  65. const char *file_name,
  66. int flags);
  67. #endif /* !UNITTESTS (static declarations used if no unit tests) */
  68. /*
  69. Sanitize a file or path name.
  70. All banned characters are replaced by underscores, for example:
  71. f?*foo => f__foo
  72. f:foo::$DATA => f_foo__$DATA
  73. f:\foo:bar => f__foo_bar
  74. f:\foo:bar => f:\foo:bar (flag SANITIZE_ALLOW_PATH)
  75. This function was implemented according to the guidelines in 'Naming Files,
  76. Paths, and Namespaces' section 'Naming Conventions'.
  77. https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247.aspx
  78. Flags
  79. -----
  80. SANITIZE_ALLOW_COLONS: Allow colons.
  81. Without this flag colons are sanitized.
  82. SANITIZE_ALLOW_PATH: Allow path separators and colons.
  83. Without this flag path separators and colons are sanitized.
  84. SANITIZE_ALLOW_RESERVED: Allow reserved device names.
  85. Without this flag a reserved device name is renamed (COM1 => _COM1) unless it's
  86. in a UNC prefixed path.
  87. SANITIZE_ALLOW_TRUNCATE: Allow truncating a long filename.
  88. Without this flag if the sanitized filename or path will be too long an error
  89. occurs. With this flag the filename --and not any other parts of the path-- may
  90. be truncated to at least a single character. A filename followed by an
  91. alternate data stream (ADS) cannot be truncated in any case.
  92. Success: (SANITIZE_ERR_OK) *sanitized points to a sanitized copy of file_name.
  93. Failure: (!= SANITIZE_ERR_OK) *sanitized is NULL.
  94. */
  95. SANITIZEcode sanitize_file_name(char **const sanitized, const char *file_name,
  96. int flags)
  97. {
  98. char *p, *target;
  99. size_t len;
  100. SANITIZEcode sc;
  101. size_t max_sanitized_len;
  102. if(!sanitized)
  103. return SANITIZE_ERR_BAD_ARGUMENT;
  104. *sanitized = NULL;
  105. if(!file_name)
  106. return SANITIZE_ERR_BAD_ARGUMENT;
  107. if((flags & SANITIZE_ALLOW_PATH)) {
  108. #ifndef MSDOS
  109. if(file_name[0] == '\\' && file_name[1] == '\\')
  110. /* UNC prefixed path \\ (eg \\?\C:\foo) */
  111. max_sanitized_len = 32767-1;
  112. else
  113. #endif
  114. max_sanitized_len = PATH_MAX-1;
  115. }
  116. else
  117. /* The maximum length of a filename.
  118. FILENAME_MAX is often the same as PATH_MAX, in other words it is 260 and
  119. does not discount the path information therefore we shouldn't use it. */
  120. max_sanitized_len = (PATH_MAX-1 > 255) ? 255 : PATH_MAX-1;
  121. len = strlen(file_name);
  122. if(len > max_sanitized_len) {
  123. if(!(flags & SANITIZE_ALLOW_TRUNCATE) ||
  124. truncate_dryrun(file_name, max_sanitized_len))
  125. return SANITIZE_ERR_INVALID_PATH;
  126. len = max_sanitized_len;
  127. }
  128. target = malloc(len + 1);
  129. if(!target)
  130. return SANITIZE_ERR_OUT_OF_MEMORY;
  131. strncpy(target, file_name, len);
  132. target[len] = '\0';
  133. #ifndef MSDOS
  134. if((flags & SANITIZE_ALLOW_PATH) && !strncmp(target, "\\\\?\\", 4))
  135. /* Skip the literal path prefix \\?\ */
  136. p = target + 4;
  137. else
  138. #endif
  139. p = target;
  140. /* replace control characters and other banned characters */
  141. for(; *p; ++p) {
  142. const char *banned;
  143. if((1 <= *p && *p <= 31) ||
  144. (!(flags & (SANITIZE_ALLOW_COLONS|SANITIZE_ALLOW_PATH)) && *p == ':') ||
  145. (!(flags & SANITIZE_ALLOW_PATH) && (*p == '/' || *p == '\\'))) {
  146. *p = '_';
  147. continue;
  148. }
  149. for(banned = "|<>\"?*"; *banned; ++banned) {
  150. if(*p == *banned) {
  151. *p = '_';
  152. break;
  153. }
  154. }
  155. }
  156. /* remove trailing spaces and periods if not allowing paths */
  157. if(!(flags & SANITIZE_ALLOW_PATH) && len) {
  158. char *clip = NULL;
  159. p = &target[len];
  160. do {
  161. --p;
  162. if(*p != ' ' && *p != '.')
  163. break;
  164. clip = p;
  165. } while(p != target);
  166. if(clip) {
  167. *clip = '\0';
  168. len = clip - target;
  169. }
  170. }
  171. #ifdef MSDOS
  172. sc = msdosify(&p, target, flags);
  173. free(target);
  174. if(sc)
  175. return sc;
  176. target = p;
  177. len = strlen(target);
  178. if(len > max_sanitized_len) {
  179. free(target);
  180. return SANITIZE_ERR_INVALID_PATH;
  181. }
  182. #endif
  183. if(!(flags & SANITIZE_ALLOW_RESERVED)) {
  184. sc = rename_if_reserved_dos_device_name(&p, target, flags);
  185. free(target);
  186. if(sc)
  187. return sc;
  188. target = p;
  189. len = strlen(target);
  190. if(len > max_sanitized_len) {
  191. free(target);
  192. return SANITIZE_ERR_INVALID_PATH;
  193. }
  194. }
  195. *sanitized = target;
  196. return SANITIZE_ERR_OK;
  197. }
  198. /*
  199. Test if truncating a path to a file will leave at least a single character in
  200. the filename. Filenames suffixed by an alternate data stream can't be
  201. truncated. This performs a dry run, nothing is modified.
  202. Good truncate_pos 9: C:\foo\bar => C:\foo\ba
  203. Good truncate_pos 6: C:\foo => C:\foo
  204. Good truncate_pos 5: C:\foo => C:\fo
  205. Bad* truncate_pos 5: C:foo => C:foo
  206. Bad truncate_pos 5: C:\foo:ads => C:\fo
  207. Bad truncate_pos 9: C:\foo:ads => C:\foo:ad
  208. Bad truncate_pos 5: C:\foo\bar => C:\fo
  209. Bad truncate_pos 5: C:\foo\ => C:\fo
  210. Bad truncate_pos 7: C:\foo\ => C:\foo\
  211. Error truncate_pos 7: C:\foo => (pos out of range)
  212. Bad truncate_pos 1: C:\foo\ => C
  213. * C:foo is ambiguous, C could end up being a drive or file therefore something
  214. like C:superlongfilename can't be truncated.
  215. Returns
  216. SANITIZE_ERR_OK: Good -- 'path' can be truncated
  217. SANITIZE_ERR_INVALID_PATH: Bad -- 'path' cannot be truncated
  218. != SANITIZE_ERR_OK && != SANITIZE_ERR_INVALID_PATH: Error
  219. */
  220. SANITIZEcode truncate_dryrun(const char *path, const size_t truncate_pos)
  221. {
  222. size_t len;
  223. if(!path)
  224. return SANITIZE_ERR_BAD_ARGUMENT;
  225. len = strlen(path);
  226. if(truncate_pos > len)
  227. return SANITIZE_ERR_BAD_ARGUMENT;
  228. if(!len || !truncate_pos)
  229. return SANITIZE_ERR_INVALID_PATH;
  230. if(strpbrk(&path[truncate_pos - 1], "\\/:"))
  231. return SANITIZE_ERR_INVALID_PATH;
  232. /* C:\foo can be truncated but C:\foo:ads can't */
  233. if(truncate_pos > 1) {
  234. const char *p = &path[truncate_pos - 1];
  235. do {
  236. --p;
  237. if(*p == ':')
  238. return SANITIZE_ERR_INVALID_PATH;
  239. } while(p != path && *p != '\\' && *p != '/');
  240. }
  241. return SANITIZE_ERR_OK;
  242. }
  243. /* The functions msdosify, rename_if_dos_device_name and __crt0_glob_function
  244. * were taken with modification from the DJGPP port of tar 1.12. They use
  245. * algorithms originally from DJTAR.
  246. */
  247. /*
  248. Extra sanitization MSDOS for file_name.
  249. This is a supporting function for sanitize_file_name.
  250. Warning: This is an MSDOS legacy function and was purposely written in a way
  251. that some path information may pass through. For example drive letter names
  252. (C:, D:, etc) are allowed to pass through. For sanitizing a filename use
  253. sanitize_file_name.
  254. Success: (SANITIZE_ERR_OK) *sanitized points to a sanitized copy of file_name.
  255. Failure: (!= SANITIZE_ERR_OK) *sanitized is NULL.
  256. */
  257. #if defined(MSDOS) || defined(UNITTESTS)
  258. SANITIZEcode msdosify(char **const sanitized, const char *file_name,
  259. int flags)
  260. {
  261. char dos_name[PATH_MAX];
  262. static const char illegal_chars_dos[] = ".+, ;=[]" /* illegal in DOS */
  263. "|<>/\\\":?*"; /* illegal in DOS & W95 */
  264. static const char *illegal_chars_w95 = &illegal_chars_dos[8];
  265. int idx, dot_idx;
  266. const char *s = file_name;
  267. char *d = dos_name;
  268. const char *const dlimit = dos_name + sizeof(dos_name) - 1;
  269. const char *illegal_aliens = illegal_chars_dos;
  270. size_t len = sizeof(illegal_chars_dos) - 1;
  271. if(!sanitized)
  272. return SANITIZE_ERR_BAD_ARGUMENT;
  273. *sanitized = NULL;
  274. if(!file_name)
  275. return SANITIZE_ERR_BAD_ARGUMENT;
  276. if(strlen(file_name) > PATH_MAX-1 &&
  277. (!(flags & SANITIZE_ALLOW_TRUNCATE) ||
  278. truncate_dryrun(file_name, PATH_MAX-1)))
  279. return SANITIZE_ERR_INVALID_PATH;
  280. /* Support for Windows 9X VFAT systems, when available. */
  281. if(_use_lfn(file_name)) {
  282. illegal_aliens = illegal_chars_w95;
  283. len -= (illegal_chars_w95 - illegal_chars_dos);
  284. }
  285. /* Get past the drive letter, if any. */
  286. if(s[0] >= 'A' && s[0] <= 'z' && s[1] == ':') {
  287. *d++ = *s++;
  288. *d = ((flags & (SANITIZE_ALLOW_COLONS|SANITIZE_ALLOW_PATH))) ? ':' : '_';
  289. ++d; ++s;
  290. }
  291. for(idx = 0, dot_idx = -1; *s && d < dlimit; s++, d++) {
  292. if(memchr(illegal_aliens, *s, len)) {
  293. if((flags & (SANITIZE_ALLOW_COLONS|SANITIZE_ALLOW_PATH)) && *s == ':')
  294. *d = ':';
  295. else if((flags & SANITIZE_ALLOW_PATH) && (*s == '/' || *s == '\\'))
  296. *d = *s;
  297. /* Dots are special: DOS doesn't allow them as the leading character,
  298. and a file name cannot have more than a single dot. We leave the
  299. first non-leading dot alone, unless it comes too close to the
  300. beginning of the name: we want sh.lex.c to become sh_lex.c, not
  301. sh.lex-c. */
  302. else if(*s == '.') {
  303. if((flags & SANITIZE_ALLOW_PATH) && idx == 0 &&
  304. (s[1] == '/' || s[1] == '\\' ||
  305. (s[1] == '.' && (s[2] == '/' || s[2] == '\\')))) {
  306. /* Copy "./" and "../" verbatim. */
  307. *d++ = *s++;
  308. if(d == dlimit)
  309. break;
  310. if(*s == '.') {
  311. *d++ = *s++;
  312. if(d == dlimit)
  313. break;
  314. }
  315. *d = *s;
  316. }
  317. else if(idx == 0)
  318. *d = '_';
  319. else if(dot_idx >= 0) {
  320. if(dot_idx < 5) { /* 5 is a heuristic ad-hoc'ery */
  321. d[dot_idx - idx] = '_'; /* replace previous dot */
  322. *d = '.';
  323. }
  324. else
  325. *d = '-';
  326. }
  327. else
  328. *d = '.';
  329. if(*s == '.')
  330. dot_idx = idx;
  331. }
  332. else if(*s == '+' && s[1] == '+') {
  333. if(idx - 2 == dot_idx) { /* .c++, .h++ etc. */
  334. *d++ = 'x';
  335. if(d == dlimit)
  336. break;
  337. *d = 'x';
  338. }
  339. else {
  340. /* libg++ etc. */
  341. if(dlimit - d < 4) {
  342. *d++ = 'x';
  343. if(d == dlimit)
  344. break;
  345. *d = 'x';
  346. }
  347. else {
  348. memcpy(d, "plus", 4);
  349. d += 3;
  350. }
  351. }
  352. s++;
  353. idx++;
  354. }
  355. else
  356. *d = '_';
  357. }
  358. else
  359. *d = *s;
  360. if(*s == '/' || *s == '\\') {
  361. idx = 0;
  362. dot_idx = -1;
  363. }
  364. else
  365. idx++;
  366. }
  367. *d = '\0';
  368. if(*s) {
  369. /* dos_name is truncated, check that truncation requirements are met,
  370. specifically truncating a filename suffixed by an alternate data stream
  371. or truncating the entire filename is not allowed. */
  372. if(!(flags & SANITIZE_ALLOW_TRUNCATE) || strpbrk(s, "\\/:") ||
  373. truncate_dryrun(dos_name, d - dos_name))
  374. return SANITIZE_ERR_INVALID_PATH;
  375. }
  376. *sanitized = strdup(dos_name);
  377. return (*sanitized ? SANITIZE_ERR_OK : SANITIZE_ERR_OUT_OF_MEMORY);
  378. }
  379. #endif /* MSDOS || UNITTESTS */
  380. /*
  381. Rename file_name if it's a reserved dos device name.
  382. This is a supporting function for sanitize_file_name.
  383. Warning: This is an MSDOS legacy function and was purposely written in a way
  384. that some path information may pass through. For example drive letter names
  385. (C:, D:, etc) are allowed to pass through. For sanitizing a filename use
  386. sanitize_file_name.
  387. Success: (SANITIZE_ERR_OK) *sanitized points to a sanitized copy of file_name.
  388. Failure: (!= SANITIZE_ERR_OK) *sanitized is NULL.
  389. */
  390. SANITIZEcode rename_if_reserved_dos_device_name(char **const sanitized,
  391. const char *file_name,
  392. int flags)
  393. {
  394. /* We could have a file whose name is a device on MS-DOS. Trying to
  395. * retrieve such a file would fail at best and wedge us at worst. We need
  396. * to rename such files. */
  397. char *p, *base;
  398. char fname[PATH_MAX];
  399. #ifdef MSDOS
  400. struct_stat st_buf;
  401. #endif
  402. if(!sanitized)
  403. return SANITIZE_ERR_BAD_ARGUMENT;
  404. *sanitized = NULL;
  405. if(!file_name)
  406. return SANITIZE_ERR_BAD_ARGUMENT;
  407. /* Ignore UNC prefixed paths, they are allowed to contain a reserved name. */
  408. #ifndef MSDOS
  409. if((flags & SANITIZE_ALLOW_PATH) &&
  410. file_name[0] == '\\' && file_name[1] == '\\') {
  411. size_t len = strlen(file_name);
  412. *sanitized = malloc(len + 1);
  413. if(!*sanitized)
  414. return SANITIZE_ERR_OUT_OF_MEMORY;
  415. strncpy(*sanitized, file_name, len + 1);
  416. return SANITIZE_ERR_OK;
  417. }
  418. #endif
  419. if(strlen(file_name) > PATH_MAX-1 &&
  420. (!(flags & SANITIZE_ALLOW_TRUNCATE) ||
  421. truncate_dryrun(file_name, PATH_MAX-1)))
  422. return SANITIZE_ERR_INVALID_PATH;
  423. strncpy(fname, file_name, PATH_MAX-1);
  424. fname[PATH_MAX-1] = '\0';
  425. base = basename(fname);
  426. /* Rename reserved device names that are known to be accessible without \\.\
  427. Examples: CON => _CON, CON.EXT => CON_EXT, CON:ADS => CON_ADS
  428. https://support.microsoft.com/en-us/kb/74496
  429. https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247.aspx
  430. */
  431. for(p = fname; p; p = (p == fname && fname != base ? base : NULL)) {
  432. size_t p_len;
  433. int x = (curl_strnequal(p, "CON", 3) ||
  434. curl_strnequal(p, "PRN", 3) ||
  435. curl_strnequal(p, "AUX", 3) ||
  436. curl_strnequal(p, "NUL", 3)) ? 3 :
  437. (curl_strnequal(p, "CLOCK$", 6)) ? 6 :
  438. (curl_strnequal(p, "COM", 3) || curl_strnequal(p, "LPT", 3)) ?
  439. (('1' <= p[3] && p[3] <= '9') ? 4 : 3) : 0;
  440. if(!x)
  441. continue;
  442. /* the devices may be accessible with an extension or ADS, for
  443. example CON.AIR and 'CON . AIR' and CON:AIR access console */
  444. for(; p[x] == ' '; ++x)
  445. ;
  446. if(p[x] == '.') {
  447. p[x] = '_';
  448. continue;
  449. }
  450. else if(p[x] == ':') {
  451. if(!(flags & (SANITIZE_ALLOW_COLONS|SANITIZE_ALLOW_PATH))) {
  452. p[x] = '_';
  453. continue;
  454. }
  455. ++x;
  456. }
  457. else if(p[x]) /* no match */
  458. continue;
  459. /* p points to 'CON' or 'CON ' or 'CON:', etc */
  460. p_len = strlen(p);
  461. /* Prepend a '_' */
  462. if(strlen(fname) == PATH_MAX-1) {
  463. --p_len;
  464. if(!(flags & SANITIZE_ALLOW_TRUNCATE) || truncate_dryrun(p, p_len))
  465. return SANITIZE_ERR_INVALID_PATH;
  466. p[p_len] = '\0';
  467. }
  468. memmove(p + 1, p, p_len + 1);
  469. p[0] = '_';
  470. ++p_len;
  471. /* if fname was just modified then the basename pointer must be updated */
  472. if(p == fname)
  473. base = basename(fname);
  474. }
  475. /* This is the legacy portion from rename_if_dos_device_name that checks for
  476. reserved device names. It only works on MSDOS. On Windows XP the stat
  477. check errors with EINVAL if the device name is reserved. On Windows
  478. Vista/7/8 it sets mode S_IFREG (regular file or device). According to MSDN
  479. stat doc the latter behavior is correct, but that doesn't help us identify
  480. whether it's a reserved device name and not a regular file name. */
  481. #ifdef MSDOS
  482. if(base && ((stat(base, &st_buf)) == 0) && (S_ISCHR(st_buf.st_mode))) {
  483. /* Prepend a '_' */
  484. size_t blen = strlen(base);
  485. if(blen) {
  486. if(strlen(fname) == PATH_MAX-1) {
  487. --blen;
  488. if(!(flags & SANITIZE_ALLOW_TRUNCATE) || truncate_dryrun(base, blen))
  489. return SANITIZE_ERR_INVALID_PATH;
  490. base[blen] = '\0';
  491. }
  492. memmove(base + 1, base, blen + 1);
  493. base[0] = '_';
  494. }
  495. }
  496. #endif
  497. *sanitized = strdup(fname);
  498. return (*sanitized ? SANITIZE_ERR_OK : SANITIZE_ERR_OUT_OF_MEMORY);
  499. }
  500. #if defined(MSDOS) && (defined(__DJGPP__) || defined(__GO32__))
  501. /*
  502. * Disable program default argument globbing. We do it on our own.
  503. */
  504. char **__crt0_glob_function(char *arg)
  505. {
  506. (void)arg;
  507. return (char **)0;
  508. }
  509. #endif /* MSDOS && (__DJGPP__ || __GO32__) */
  510. #ifdef _WIN32
  511. /*
  512. * Function to find CACert bundle on a Win32 platform using SearchPath.
  513. * (SearchPath is already declared via inclusions done in setup header file)
  514. * (Use the ASCII version instead of the unicode one!)
  515. * The order of the directories it searches is:
  516. * 1. application's directory
  517. * 2. current working directory
  518. * 3. Windows System directory (e.g. C:\windows\system32)
  519. * 4. Windows Directory (e.g. C:\windows)
  520. * 5. all directories along %PATH%
  521. *
  522. * For WinXP and later search order actually depends on registry value:
  523. * HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\SafeProcessSearchMode
  524. */
  525. CURLcode FindWin32CACert(struct OperationConfig *config,
  526. curl_sslbackend backend,
  527. const TCHAR *bundle_file)
  528. {
  529. CURLcode result = CURLE_OK;
  530. /* Search and set cert file only if libcurl supports SSL.
  531. *
  532. * If Schannel is the selected SSL backend then these locations are
  533. * ignored. We allow setting CA location for schannel only when explicitly
  534. * specified by the user via CURLOPT_CAINFO / --cacert.
  535. */
  536. if(feature_ssl && backend != CURLSSLBACKEND_SCHANNEL) {
  537. DWORD res_len;
  538. TCHAR buf[PATH_MAX];
  539. TCHAR *ptr = NULL;
  540. buf[0] = TEXT('\0');
  541. res_len = SearchPath(NULL, bundle_file, NULL, PATH_MAX, buf, &ptr);
  542. if(res_len > 0) {
  543. char *mstr = curlx_convert_tchar_to_UTF8(buf);
  544. Curl_safefree(config->cacert);
  545. if(mstr)
  546. config->cacert = strdup(mstr);
  547. curlx_unicodefree(mstr);
  548. if(!config->cacert)
  549. result = CURLE_OUT_OF_MEMORY;
  550. }
  551. }
  552. return result;
  553. }
  554. /* Get a list of all loaded modules with full paths.
  555. * Returns slist on success or NULL on error.
  556. */
  557. struct curl_slist *GetLoadedModulePaths(void)
  558. {
  559. HANDLE hnd = INVALID_HANDLE_VALUE;
  560. MODULEENTRY32 mod = {0};
  561. struct curl_slist *slist = NULL;
  562. mod.dwSize = sizeof(MODULEENTRY32);
  563. do {
  564. hnd = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, 0);
  565. } while(hnd == INVALID_HANDLE_VALUE && GetLastError() == ERROR_BAD_LENGTH);
  566. if(hnd == INVALID_HANDLE_VALUE)
  567. goto error;
  568. if(!Module32First(hnd, &mod))
  569. goto error;
  570. do {
  571. char *path; /* points to stack allocated buffer */
  572. struct curl_slist *temp;
  573. #ifdef UNICODE
  574. /* sizeof(mod.szExePath) is the max total bytes of wchars. the max total
  575. bytes of multibyte chars won't be more than twice that. */
  576. char buffer[sizeof(mod.szExePath) * 2];
  577. if(!WideCharToMultiByte(CP_ACP, 0, mod.szExePath, -1,
  578. buffer, sizeof(buffer), NULL, NULL))
  579. goto error;
  580. path = buffer;
  581. #else
  582. path = mod.szExePath;
  583. #endif
  584. temp = curl_slist_append(slist, path);
  585. if(!temp)
  586. goto error;
  587. slist = temp;
  588. } while(Module32Next(hnd, &mod));
  589. goto cleanup;
  590. error:
  591. curl_slist_free_all(slist);
  592. slist = NULL;
  593. cleanup:
  594. if(hnd != INVALID_HANDLE_VALUE)
  595. CloseHandle(hnd);
  596. return slist;
  597. }
  598. /* The terminal settings to restore on exit */
  599. static struct TerminalSettings {
  600. HANDLE hStdOut;
  601. DWORD dwOutputMode;
  602. LONG valid;
  603. } TerminalSettings;
  604. #ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
  605. #define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
  606. #endif
  607. bool tool_term_has_bold;
  608. static void restore_terminal(void)
  609. {
  610. if(InterlockedExchange(&TerminalSettings.valid, (LONG)FALSE))
  611. SetConsoleMode(TerminalSettings.hStdOut, TerminalSettings.dwOutputMode);
  612. }
  613. /* This is the console signal handler.
  614. * The system calls it in a separate thread.
  615. */
  616. static BOOL WINAPI signal_handler(DWORD type)
  617. {
  618. if(type == CTRL_C_EVENT || type == CTRL_BREAK_EVENT)
  619. restore_terminal();
  620. return FALSE;
  621. }
  622. static void init_terminal(void)
  623. {
  624. TerminalSettings.hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
  625. /*
  626. * Enable VT (Virtual Terminal) output.
  627. * Note: VT mode flag can be set on any version of Windows, but VT
  628. * processing only performed on Win10 >= version 1709 (OS build 16299)
  629. * Creator's Update. Also, ANSI bold on/off supported since then.
  630. */
  631. if(TerminalSettings.hStdOut == INVALID_HANDLE_VALUE ||
  632. !GetConsoleMode(TerminalSettings.hStdOut,
  633. &TerminalSettings.dwOutputMode) ||
  634. !curlx_verify_windows_version(10, 0, 16299, PLATFORM_WINNT,
  635. VERSION_GREATER_THAN_EQUAL))
  636. return;
  637. if((TerminalSettings.dwOutputMode & ENABLE_VIRTUAL_TERMINAL_PROCESSING))
  638. tool_term_has_bold = true;
  639. else {
  640. /* The signal handler is set before attempting to change the console mode
  641. because otherwise a signal would not be caught after the change but
  642. before the handler was installed. */
  643. (void)InterlockedExchange(&TerminalSettings.valid, (LONG)TRUE);
  644. if(SetConsoleCtrlHandler(signal_handler, TRUE)) {
  645. if(SetConsoleMode(TerminalSettings.hStdOut,
  646. (TerminalSettings.dwOutputMode |
  647. ENABLE_VIRTUAL_TERMINAL_PROCESSING))) {
  648. tool_term_has_bold = true;
  649. atexit(restore_terminal);
  650. }
  651. else {
  652. SetConsoleCtrlHandler(signal_handler, FALSE);
  653. (void)InterlockedExchange(&TerminalSettings.valid, (LONG)FALSE);
  654. }
  655. }
  656. }
  657. }
  658. LARGE_INTEGER tool_freq;
  659. bool tool_isVistaOrGreater;
  660. CURLcode win32_init(void)
  661. {
  662. /* curlx_verify_windows_version must be called during init at least once
  663. because it has its own initialization routine. */
  664. if(curlx_verify_windows_version(6, 0, 0, PLATFORM_WINNT,
  665. VERSION_GREATER_THAN_EQUAL))
  666. tool_isVistaOrGreater = true;
  667. else
  668. tool_isVistaOrGreater = false;
  669. QueryPerformanceFrequency(&tool_freq);
  670. init_terminal();
  671. return CURLE_OK;
  672. }
  673. #endif /* _WIN32 */
  674. #endif /* _WIN32 || MSDOS */