tool_doswin.c 22 KB

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