master
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"
26#if defined(_WIN32) || defined(MSDOS)
28#include "curlx/basename.h" /* for curlx_basename() */
29#include "curlx/version_win32.h" /* for curlx_verify_windows_version() */
31#ifdef _WIN32
32# include "curlx/winapi.h" /* for curlx_win32_random() */
33# include "curlx/nonblock.h" /* for curlx_nonblock() */
34#elif !defined(__DJGPP__) || (__DJGPP__ < 2) /* DJGPP 2.0 has _use_lfn() */
35# define CURL_USE_LFN(f) 0 /* long filenames never available */
36#elif defined(__DJGPP__)
37# include <fcntl.h> /* for _use_lfn(f) prototype */
38# define CURL_USE_LFN(f) _use_lfn(f)
39#endif
41#include "tool_cfgable.h"
42#include "tool_doswin.h"
43#include "tool_msgs.h"
45#ifdef MSDOS
47#ifndef S_ISCHR
48# ifdef S_IFCHR
49# define S_ISCHR(m) (((m) & S_IFMT) == S_IFCHR)
50# else
51# define S_ISCHR(m) 0 /* cannot tell if file is a device */
52# endif
53#endif
55/* The functions msdosify, rename_if_dos_device_name and __crt0_glob_function
56 * were taken with modification from the DJGPP port of tar 1.12. They use
57 * algorithms originally from DJTAR.
58 */
60#ifdef __DJGPP__
61/*
62 * Disable program default argument globbing. We do it on our own.
63 */
64char **__crt0_glob_function(char *arg)
65{
66 (void)arg;
67 return (char **)0;
68}
69#endif
71/*
72 * Test if truncating a path to a file leaves at least a single character
73 * in the filename. Filenames suffixed by an alternate data stream cannot be
74 * truncated. This performs a dry run, nothing is modified.
75 *
76 * Good truncate_pos 9: C:\foo\bar => C:\foo\ba
77 * Good truncate_pos 6: C:\foo => C:\foo
78 * Good truncate_pos 5: C:\foo => C:\fo
79 * Bad* truncate_pos 5: C:foo => C:foo
80 * Bad truncate_pos 5: C:\foo:ads => C:\fo
81 * Bad truncate_pos 9: C:\foo:ads => C:\foo:ad
82 * Bad truncate_pos 5: C:\foo\bar => C:\fo
83 * Bad truncate_pos 5: C:\foo\ => C:\fo
84 * Bad truncate_pos 7: C:\foo\ => C:\foo\
85 * Error truncate_pos 7: C:\foo => (pos out of range)
86 * Bad truncate_pos 1: C:\foo\ => C
87 *
88 * * C:foo is ambiguous, C could end up being a drive or file therefore
89 * something like C:superlongfilename cannot be truncated.
90 *
91 * Returns
92 * SANITIZE_ERR_OK: Good -- 'path' can be truncated
93 * SANITIZE_ERR_INVALID_PATH: Bad -- 'path' cannot be truncated
94 * != SANITIZE_ERR_OK && != SANITIZE_ERR_INVALID_PATH: Error
95 */
96static SANITIZEcode truncate_dryrun(const char *path,
97 const size_t truncate_pos)
98{
99 size_t len;
101 if(!path)
102 return SANITIZE_ERR_BAD_ARGUMENT;
104 len = strlen(path);
106 if(truncate_pos > len)
107 return SANITIZE_ERR_BAD_ARGUMENT;
109 if(!len || !truncate_pos)
110 return SANITIZE_ERR_INVALID_PATH;
112 if(strpbrk(&path[truncate_pos - 1], "\\/:"))
113 return SANITIZE_ERR_INVALID_PATH;
115 /* C:\foo can be truncated but C:\foo:ads cannot */
116 if(truncate_pos > 1) {
117 const char *p = &path[truncate_pos - 1];
118 do {
119 --p;
120 if(*p == ':')
121 return SANITIZE_ERR_INVALID_PATH;
122 } while(p != path && *p != '\\' && *p != '/');
123 }
125 return SANITIZE_ERR_OK;
126}
128/*
129 * Extra sanitization MS-DOS for file_name.
130 *
131 * This is a supporting function for sanitize_file_name.
132 *
133 * Warning: This is an MS-DOS legacy function and was purposely written in
134 * a way that some path information may pass through. For example drive letter
135 * names (C:, D:, etc) are allowed to pass through. For sanitizing a filename
136 * use sanitize_file_name.
137 *
138 * Success: SANITIZE_ERR_OK *sanitized points to a sanitized copy of file_name.
139 * Failure: != SANITIZE_ERR_OK *sanitized is NULL.
140 */
141static SANITIZEcode msdosify(char ** const sanitized, const char *file_name,
142 int flags)
143{
144 char dos_name[PATH_MAX];
145 static const char illegal_chars_dos[] =
146 ".+, ;=[]" /* illegal in DOS */
147 "|<>/\\\":?*"; /* illegal in DOS & W95 */
148 static const char * const illegal_chars_w95 = &illegal_chars_dos[8];
149 int idx, dot_idx;
150 const char *s = file_name;
151 char *d = dos_name;
152 const char * const dlimit = dos_name + CURL_CSTRLEN(dos_name);
153 const char *illegal_aliens = illegal_chars_dos;
154 size_t len = CURL_CSTRLEN(illegal_chars_dos);
156 if(!sanitized)
157 return SANITIZE_ERR_BAD_ARGUMENT;
159 *sanitized = NULL;
161 if(!file_name)
162 return SANITIZE_ERR_BAD_ARGUMENT;
164 if(strlen(file_name) > PATH_MAX - 1)
165 return SANITIZE_ERR_INVALID_PATH;
167 /* Support for Windows 9X VFAT systems, when available. */
168 if(CURL_USE_LFN(file_name)) {
169 illegal_aliens = illegal_chars_w95;
170 len -= (illegal_chars_w95 - illegal_chars_dos);
171 }
173 /* Get past the drive letter, if any. */
174 if(s[0] >= 'A' && s[0] <= 'z' && s[1] == ':') {
175 *d++ = *s++;
176 *d = (flags & SANITIZE_ALLOW_PATH) ? ':' : '_';
177 ++d;
178 ++s;
179 }
181 for(idx = 0, dot_idx = -1; *s && d < dlimit; s++, d++) {
182 if(memchr(illegal_aliens, *s, len)) {
184 if((flags & SANITIZE_ALLOW_PATH) && *s == ':')
185 *d = ':';
186 else if((flags & SANITIZE_ALLOW_PATH) && (*s == '/' || *s == '\\'))
187 *d = *s;
188 /* Dots are special: DOS does not allow them as the leading character,
189 and a filename cannot have more than a single dot. We leave the
190 first non-leading dot alone, unless it comes too close to the
191 beginning of the name: we want sh.lex.c to become sh_lex.c, not
192 sh.lex-c. */
193 else if(*s == '.') {
194 if((flags & SANITIZE_ALLOW_PATH) && idx == 0 &&
195 (s[1] == '/' || s[1] == '\\' ||
196 (s[1] == '.' && (s[2] == '/' || s[2] == '\\')))) {
197 /* Copy "./" and "../" verbatim. */
198 *d++ = *s++;
199 if(d == dlimit)
200 break;
201 if(*s == '.') {
202 *d++ = *s++;
203 if(d == dlimit)
204 break;
205 }
206 *d = *s;
207 }
208 else if(idx == 0)
209 *d = '_';
210 else if(dot_idx >= 0) {
211 if(dot_idx < 5) { /* 5 is a heuristic ad-hoc'ery */
212 d[dot_idx - idx] = '_'; /* replace previous dot */
213 *d = '.';
214 }
215 else
216 *d = '-';
217 }
218 else
219 *d = '.';
221 if(*s == '.')
222 dot_idx = idx;
223 }
224 else if(*s == '+' && s[1] == '+') {
225 if(idx - 2 == dot_idx) { /* .c++, .h++ etc. */
226 *d++ = 'x';
227 if(d == dlimit)
228 break;
229 *d = 'x';
230 }
231 else {
232 /* libg++ etc. */
233 if(dlimit - d < 4) {
234 *d++ = 'x';
235 if(d == dlimit)
236 break;
237 *d = 'x';
238 }
239 else {
240 memcpy(d, "plus", 4);
241 d += 3;
242 }
243 }
244 s++;
245 idx++;
246 }
247 else
248 *d = '_';
249 }
250 else
251 *d = *s;
252 if(*s == '/' || *s == '\\') {
253 idx = 0;
254 dot_idx = -1;
255 }
256 else
257 idx++;
258 }
259 *d = '\0';
261 if(*s) {
262 /* dos_name is truncated, check that truncation requirements are met,
263 specifically truncating a filename suffixed by an alternate data stream
264 or truncating the entire filename is not allowed. */
265 if(strpbrk(s, "\\/:") || truncate_dryrun(dos_name, d - dos_name))
266 return SANITIZE_ERR_INVALID_PATH;
267 }
269 *sanitized = curlx_strdup(dos_name);
270 return *sanitized ? SANITIZE_ERR_OK : SANITIZE_ERR_OUT_OF_MEMORY;
271}
272#endif /* MSDOS */
274/* return the number of bytes of the reserved prefix, zero if none exists */
275static int prefix_reserved(const char *p)
276{
277 if(curl_strnequal(p, "COM", 3) || curl_strnequal(p, "LPT", 3)) {
278 const uint8_t *up = (const uint8_t *)p;
279 uint8_t super;
280 int len;
281 if(('1' <= p[3]) && (p[3] <= '9'))
282 return 4;
284 /* to complicate things, Windows considers superscript 1, 2, 3 to be valid
285 numbers and they can be provided in ISO8859-1 or UTF-8. Avoid either
286 version. */
287 len = (up[3] == 0xc2) ? /* UTF-8 */ 4 : 3;
288 super = up[len];
290 switch(super) {
291 case 0xb9: /* superscript '1' */
292 case 0xb2: /* superscript '2' */
293 case 0xb3: /* superscript '3' */
294 return len + 1;
295 }
296 return 0;
297 }
298 else if(curl_strnequal(p, "CON", 3) ||
299 curl_strnequal(p, "PRN", 3) ||
300 curl_strnequal(p, "AUX", 3) ||
301 curl_strnequal(p, "NUL", 3))
302 return 3;
303 else if(curl_strnequal(p, "CLOCK$", 6))
304 return 6;
305 return 0;
306}
308/*
309 * Rename file_name if it is a reserved dos device name.
310 *
311 * This is a supporting function for sanitize_file_name.
312 *
313 * Warning: This is an MS-DOS legacy function and was purposely written in
314 * a way that some path information may pass through. For example drive letter
315 * names (C:, D:, etc) are allowed to pass through. For sanitizing a filename
316 * use sanitize_file_name.
317 *
318 * Success: SANITIZE_ERR_OK *sanitized points to a sanitized copy of file_name.
319 * Failure: != SANITIZE_ERR_OK *sanitized is NULL.
320 */
321static SANITIZEcode rename_if_reserved_dos(char ** const sanitized,
322 const char *file_name,
323 int flags)
324{
325 /* We could have a file whose name is a device on MS-DOS. Trying to
326 retrieve such a file would fail at best and wedge us at worst. We need
327 to rename such files. */
328 char *p, *base, *buffer;
329#ifdef MSDOS
330 curlx_struct_stat st_buf;
331#endif
332 size_t len, bufsize;
334 if(!sanitized || !file_name)
335 return SANITIZE_ERR_BAD_ARGUMENT;
337 *sanitized = NULL;
339 /* Ignore "\\" prefixed paths, they are allowed to use reserved names. */
340#ifndef MSDOS
341 if((flags & SANITIZE_ALLOW_PATH) &&
342 file_name[0] == '\\' && file_name[1] == '\\') {
343 *sanitized = curlx_strdup(file_name);
344 if(!*sanitized)
345 return SANITIZE_ERR_OUT_OF_MEMORY;
346 return SANITIZE_ERR_OK;
347 }
348#endif
350 /* The buffer contains two extra bytes to allow for path expansion that
351 occurs if reserved name(s) need an underscore prepended. */
352 len = strlen(file_name);
353 bufsize = len + 2 + 1;
355 buffer = curlx_malloc(bufsize);
356 if(!buffer)
357 return SANITIZE_ERR_OUT_OF_MEMORY;
359 memcpy(buffer, file_name, len + 1);
361 base = curlx_basename(buffer);
363 /* Rename reserved device names that are known to be accessible without \\.\
364 Examples: CON => _CON, CON.EXT => CON_EXT, CON:ADS => CON_ADS
365 https://web.archive.org/web/20160314141551/support.microsoft.com/en-us/kb/74496
366 https://learn.microsoft.com/windows/win32/fileio/naming-a-file
367 */
368 for(p = buffer; p; p = (p == buffer && buffer != base ? base : NULL)) {
369 size_t p_len;
370 int x = prefix_reserved(p);
372 if(!x)
373 continue;
375 /* the devices may be accessible with an extension or ADS, for
376 example CON.AIR and 'CON . AIR' and CON:AIR access console */
378 for(; p[x] == ' '; ++x)
379 ;
381 if(p[x] == '.') {
382 p[x] = '_';
383 continue;
384 }
385 else if(p[x] == ':') {
386 if(!(flags & SANITIZE_ALLOW_PATH)) {
387 p[x] = '_';
388 continue;
389 }
390 ++x;
391 }
392 else if(p[x]) /* no match */
393 continue;
395 /* p points to 'CON' or 'CON ' or 'CON:', etc */
396 p_len = strlen(p);
398 /* Prepend a '_' */
399 memmove(p + 1, p, p_len + 1);
400 p[0] = '_';
401 ++p_len;
402 ++len;
404 /* the basename pointer must be updated since the path has expanded */
405 if(p == buffer)
406 base = curlx_basename(buffer);
407 }
409 /* This is the legacy portion from rename_if_dos_device_name that checks for
410 reserved device names. It only works on MS-DOS. On Windows XP the stat
411 check errors with EINVAL if the device name is reserved. On Windows
412 Vista/7/8 it sets mode S_IFREG (regular file or device). According to
413 MSDN stat doc the latter behavior is correct, but that does not help us
414 identify whether it is a reserved device name and not a regular
415 filename. */
416#ifdef MSDOS
417 if(base && (curlx_stat(base, &st_buf) == 0) && S_ISCHR(st_buf.st_mode)) {
418 /* Prepend a '_' */
419 size_t blen = strlen(base);
420 if(blen) {
421 if(len == bufsize - 1) {
422 curlx_free(buffer);
423 return SANITIZE_ERR_INVALID_PATH;
424 }
425 memmove(base + 1, base, blen + 1);
426 base[0] = '_';
427 ++len;
428 }
429 }
430#endif
432 *sanitized = buffer;
433 return SANITIZE_ERR_OK;
434}
436/*
437 * Sanitize a file or path name.
438 *
439 * All banned characters are replaced by underscores, for example:
440 * f?*foo => f__foo
441 * f:foo::$DATA => f_foo__$DATA
442 * f:\foo:bar => f__foo_bar
443 * f:\foo:bar => f:\foo:bar (flag SANITIZE_ALLOW_PATH)
444 *
445 * This function was implemented according to the guidelines in 'Naming Files,
446 * Paths, and Namespaces' section 'Naming Conventions'.
447 * https://learn.microsoft.com/windows/win32/fileio/naming-a-file
448 *
449 * Flags
450 * -----
451 * SANITIZE_ALLOW_PATH: Allow path separators and colons.
452 * Without this flag path separators and colons are sanitized.
453 *
454 * SANITIZE_ALLOW_RESERVED: Allow reserved device names.
455 * Without this flag a reserved device name is renamed (COM1 => _COM1).
456 *
457 * To fully block reserved device names requires not passing either flag.
458 * Some less common path styles are allowed to use reserved device names.
459 * For example, a "\\" prefixed path may use reserved device names if paths
460 * are allowed.
461 *
462 * Success: SANITIZE_ERR_OK *sanitized points to a sanitized copy of file_name.
463 * Failure: != SANITIZE_ERR_OK *sanitized is NULL.
464 */
465SANITIZEcode sanitize_file_name(char ** const sanitized, const char *file_name,
466 int flags)
467{
468 char *p, *target;
469 size_t len;
470 SANITIZEcode sc;
472 if(!sanitized)
473 return SANITIZE_ERR_BAD_ARGUMENT;
475 *sanitized = NULL;
477 if(!file_name)
478 return SANITIZE_ERR_BAD_ARGUMENT;
480 len = strlen(file_name);
482 target = curlx_strdup(file_name);
483 if(!target)
484 return SANITIZE_ERR_OUT_OF_MEMORY;
486#ifndef MSDOS
487 if((flags & SANITIZE_ALLOW_PATH) && !strncmp(target, "\\\\?\\", 4))
488 /* Skip the literal-path prefix \\?\ */
489 p = target + 4;
490 else
491#endif
492 p = target;
494 /* replace control characters and other banned characters */
495 for(; *p; ++p) {
496 const char *banned;
498 if((1 <= *p && *p <= 31) ||
499 (!(flags & SANITIZE_ALLOW_PATH) && *p == ':') ||
500 (!(flags & SANITIZE_ALLOW_PATH) && (*p == '/' || *p == '\\'))) {
501 *p = '_';
502 continue;
503 }
505 for(banned = "|<>\"?*"; *banned; ++banned) {
506 if(*p == *banned) {
507 *p = '_';
508 break;
509 }
510 }
511 }
513 /* remove trailing spaces and periods if not allowing paths */
514 if(!(flags & SANITIZE_ALLOW_PATH) && len) {
515 char *clip = NULL;
517 p = &target[len];
518 do {
519 --p;
520 if(*p != ' ' && *p != '.')
521 break;
522 clip = p;
523 } while(p != target);
525 if(clip) {
526 *clip = '\0';
527 }
528 }
530#ifdef MSDOS
531 sc = msdosify(&p, target, flags);
532 curlx_free(target);
533 if(sc)
534 return sc;
535 target = p;
536#endif
538 if(!(flags & SANITIZE_ALLOW_RESERVED)) {
539 sc = rename_if_reserved_dos(&p, target, flags);
540 curlx_free(target);
541 if(sc)
542 return sc;
543 target = p;
544 }
546#ifdef DEBUGBUILD
547 if(getenv("CURL_FN_SANITIZE_BAD")) {
548 curlx_free(target);
549 return SANITIZE_ERR_INVALID_PATH;
550 }
551 if(getenv("CURL_FN_SANITIZE_OOM")) {
552 curlx_free(target);
553 return SANITIZE_ERR_OUT_OF_MEMORY;
554 }
555#endif
557 *sanitized = target;
558 return SANITIZE_ERR_OK;
559}
561#ifdef _WIN32
563#if !defined(CURL_WINDOWS_UWP) && \
564 !defined(CURL_DISABLE_CA_SEARCH) && !defined(CURL_CA_SEARCH_SAFE)
565/* Search and set the CA cert file for Windows.
566 *
567 * Do not call this function if Schannel is the selected SSL backend. We allow
568 * setting CA location for Schannel only when explicitly specified by the user
569 * via CURLOPT_CAINFO / --cacert.
570 *
571 * Function to find CACert bundle on a Win32 platform using SearchPath.
572 * (SearchPath is already declared via inclusions done in setup header file)
573 * (Use the ASCII version instead of the Unicode one!)
574 * The order of the directories it searches is:
575 * 1. application's directory
576 * 2. current working directory
577 * 3. Windows System directory (e.g. C:\Windows\System32)
578 * 4. Windows Directory (e.g. C:\Windows)
579 * 5. all directories along %PATH%
580 *
581 * For Windows XP and later search order actually depends on registry value:
582 * HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\SafeProcessSearchMode
583 */
584CURLcode FindWin32CACert(struct OperationConfig *config,
585 const TCHAR *bundle_file)
586{
587 CURLcode result = CURLE_OK;
588 DWORD res_len;
589 TCHAR buf[MAX_PATH];
590 TCHAR *ptr = NULL;
592 buf[0] = TEXT('\0');
594 res_len = SearchPath(NULL, bundle_file, NULL, MAX_PATH, buf, &ptr);
595 if(res_len > 0) {
596 curlx_free(config->cacert);
597 config->cacert = curlx_convert_tchar_to_UTF8(buf);
598 if(!config->cacert)
599 result = CURLE_OUT_OF_MEMORY;
600 }
602 return result;
603}
604#endif
606bool tool_term_has_bold;
608#ifndef CURL_WINDOWS_UWP
609/* The terminal settings to restore on exit */
610static struct TerminalSettings {
611 HANDLE hStdOut;
612 DWORD dwOutputMode;
613 LONG valid;
614} TerminalSettings;
616/* Offered by mingw-w64 v7+, MS SDK 10.0.10586.0/VS2015 Update 1+ */
617#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
618#define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
619#endif
621static void restore_terminal(void)
622{
623 if(InterlockedExchange(&TerminalSettings.valid, (LONG)FALSE))
624 SetConsoleMode(TerminalSettings.hStdOut, TerminalSettings.dwOutputMode);
625}
627/* This is the console signal handler.
628 * The system calls it in a separate thread.
629 */
630static BOOL WINAPI signal_handler(DWORD type)
631{
632 if(type == CTRL_C_EVENT || type == CTRL_BREAK_EVENT)
633 restore_terminal();
634 return FALSE;
635}
637static void init_terminal(void)
638{
639 TerminalSettings.hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
641 /*
642 * Enable VT (Virtual Terminal) output.
643 * Note: VT mode flag can be set on any version of Windows, but VT
644 * processing only performed on Win10 >= version 1709 (OS build 16299)
645 * Creator's Update. Also, ANSI bold on/off supported since then.
646 */
647 if(TerminalSettings.hStdOut == INVALID_HANDLE_VALUE ||
648 !GetConsoleMode(TerminalSettings.hStdOut,
649 &TerminalSettings.dwOutputMode) ||
650 !curlx_verify_windows_version(10, 0, 16299, PLATFORM_WINNT,
651 VERSION_GREATER_THAN_EQUAL))
652 return;
654 if((TerminalSettings.dwOutputMode & ENABLE_VIRTUAL_TERMINAL_PROCESSING))
655 tool_term_has_bold = TRUE;
656 else {
657 /* The signal handler is set before attempting to change the console mode
658 because otherwise a signal would not be caught after the change but
659 before the handler was installed. */
660 (void)InterlockedExchange(&TerminalSettings.valid, (LONG)TRUE);
661 if(SetConsoleCtrlHandler(signal_handler, TRUE)) {
662 if(SetConsoleMode(TerminalSettings.hStdOut,
663 (TerminalSettings.dwOutputMode |
664 ENABLE_VIRTUAL_TERMINAL_PROCESSING))) {
665 tool_term_has_bold = TRUE;
666 atexit(restore_terminal);
667 }
668 else {
669 SetConsoleCtrlHandler(signal_handler, FALSE);
670 (void)InterlockedExchange(&TerminalSettings.valid, (LONG)FALSE);
671 }
672 }
673 }
674}
676#ifdef USE_WINSOCK
677/* The following STDIN non - blocking read techniques are heavily inspired
678 by nmap and ncat (https://nmap.org/ncat/) */
679static struct win_thread_data {
680 /* This is a copy of the true stdin file handle before any redirection. It is
681 read by the thread. */
682 HANDLE stdin_handle;
683 /* This is the socket the thread will forward stdin to. It is connected to
684 the socket which replaces the stdin handle. */
685 curl_socket_t socket_w;
686 /* This is a mutex-like object which we use to synchronize
687 * cleanup_tdata_sync() */
688 CRITICAL_SECTION crit_sect;
689} tdata = { NULL, CURL_SOCKET_BAD, {0}};
691static void cleanup_tdata_sync(void)
692{
693 EnterCriticalSection(&tdata.crit_sect);
694 if(tdata.stdin_handle) {
695 CloseHandle(tdata.stdin_handle);
696 tdata.stdin_handle = NULL;
697 }
699 if(tdata.socket_w != CURL_SOCKET_BAD) {
700 sclose(tdata.socket_w);
701 tdata.socket_w = CURL_SOCKET_BAD;
702 }
703 LeaveCriticalSection(&tdata.crit_sect);
704}
706static DWORD WINAPI win_stdin_thread_func(void *thread_data)
707{
708 (void)thread_data;
710 for(;;) {
711 DWORD n;
712 ssize_t nwritten;
713 char buffer[BUFSIZ];
715 /* If stdin is a pipe then end-of-data signaling may differ depending on
716 how curl was built, the shell and the input. Two ways have been
717 observed:
718 - ReadFile fails with GetLastError ERROR_BROKEN_PIPE
719 - ReadFile succeeds with 0 bytes read (seen on mingw) */
721 if(!ReadFile(tdata.stdin_handle, buffer, sizeof(buffer), &n, NULL))
722 break;
723 if(n == 0)
724 break;
725 nwritten = swrite(tdata.socket_w, buffer, n);
726 if(nwritten == -1)
727 break;
728 if((DWORD)nwritten != n)
729 break;
730 }
732 /* wait for all data to be received by the main thread:
733 shut down the write side of our socket so that a FIN is sent "after all
734 data is sent and acknowledged by the receiver". recv is called to wait for
735 this to happen. the wait time includes time of up to 2 min (OS typical)
736 since it's possible the receiver will not reply to the FIN.
737 */
738 if(shutdown(tdata.socket_w, SHUT_WR) == 0) {
739 char buf[1024];
740 /* read until close or error while ignoring all incoming */
741 while(sread(tdata.socket_w, buf, sizeof(buf)) > 0)
742 ;
743 }
745 cleanup_tdata_sync();
747 return 0;
748}
750static int swrite_blocking_on_nonblock(curl_socket_t nonblock_sock,
751 const unsigned char *data,
752 size_t nbytes)
753{
754 fd_set fdwrite;
755 fd_set fdexcep;
756 size_t nwritten = 0;
758 FD_ZERO(&fdwrite);
759 FD_ZERO(&fdexcep);
761 FD_SET(nonblock_sock, &fdwrite);
763 do {
764 ssize_t ret;
766 FD_SET(nonblock_sock, &fdexcep);
768 if(select(0, NULL, &fdwrite, &fdexcep, NULL) <= 0) {
769 errorf("select error: %d", SOCKERRNO);
770 return -1;
771 }
773 if(FD_ISSET(nonblock_sock, &fdexcep)) {
774 int sock_err = 0;
775 int sock_err_size = sizeof(sock_err);
776 getsockopt(nonblock_sock, SOL_SOCKET, SO_ERROR,
777 (char *)&sock_err, &sock_err_size);
778 errorf("connect failure: %d", sock_err);
779 return -1;
780 }
782 ret = swrite(nonblock_sock, data + nwritten, nbytes - nwritten);
783 if(ret <= 0) {
784 if(SOCK_EAGAIN(SOCKERRNO))
785 continue;
787 errorf("socket write error: %d", SOCKERRNO);
788 return -1;
789 }
791 nwritten += ret;
792 } while(nwritten < nbytes);
794 return 0;
795}
797static int read_auth_val(curl_socket_t sock, uint64_t* auth_val_ptr)
798{
799 size_t nread = 0;
801 do {
802 ssize_t ret = sread(sock, (unsigned char *)auth_val_ptr + nread,
803 sizeof(*auth_val_ptr) - nread);
804 if(ret <= 0) {
805 if(!ret)
806 errorf("stdin relay peer disconnected");
807 else
808 errorf("read error: %d", SOCKERRNO);
810 return -1;
811 }
812 nread += ret;
813 } while(nread < sizeof(*auth_val_ptr));
815 return 0;
816}
818/* The background thread that reads and buffers the true stdin. */
819curl_socket_t win32_stdin_read_thread(void)
820{
821 int rc = 0;
822 HANDLE stdin_thread = NULL;
823 static curl_socket_t socket_r = CURL_SOCKET_BAD;
824 curl_socket_t socket_l = CURL_SOCKET_BAD;
825 uint64_t auth_rnd = 0;
826 uint64_t recvd_val = 1;
828 if(socket_r != CURL_SOCKET_BAD) {
829 return socket_r;
830 }
832 do {
833 curl_socklen_t socksize = 0;
834 struct sockaddr_in selfaddr;
836 InitializeCriticalSection(&tdata.crit_sect);
838 /* Create the listening socket. It is used to create the writing socket by
839 * accepting a connection from the reading socket. */
840 socket_l = CURL_SOCKET(AF_INET, SOCK_STREAM, IPPROTO_TCP);
841 if(socket_l == CURL_SOCKET_BAD) {
842 errorf("socket() error: %d", SOCKERRNO);
843 break;
844 }
846 socksize = sizeof(selfaddr);
847 memset(&selfaddr, 0, socksize);
848 selfaddr.sin_family = AF_INET;
849 selfaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
850 /* Bind to any available loopback port */
851 if(bind(socket_l, (const struct sockaddr *)&selfaddr, socksize)) {
852 errorf("bind error: %d", SOCKERRNO);
853 break;
854 }
856 /* Retrieve the assigned loopback port/address */
857 if(getsockname(socket_l, (struct sockaddr *)&selfaddr, &socksize)) {
858 errorf("getsockname error: %d", SOCKERRNO);
859 break;
860 }
862 if(listen(socket_l, 1)) {
863 errorf("listen error: %d", SOCKERRNO);
864 break;
865 }
867 /* Create the reading socket */
868 socket_r = CURL_SOCKET(AF_INET, SOCK_STREAM, IPPROTO_TCP);
869 if(socket_r == CURL_SOCKET_BAD) {
870 errorf("socket error: %d", SOCKERRNO);
871 break;
872 }
874 /* Make the reading socket nonblocking */
875 if(curlx_nonblock(socket_r, TRUE)) {
876 errorf("curlx_nonblock() error");
877 break;
878 }
880 /* Connect to the listening socket */
881 if(connect(socket_r, (const struct sockaddr *)&selfaddr, socksize)) {
882 int sockerr = SOCKERRNO;
883 if(!SOCK_EAGAIN(sockerr)) {
884 errorf("connect error: %d", sockerr);
885 break;
886 }
887 }
889 /* Accept the connection on the other end, creating the writing socket
890 * which will be given to the background thread */
891 tdata.socket_w = CURL_ACCEPT(socket_l, NULL, NULL);
893 if(tdata.socket_w == CURL_SOCKET_BAD) {
894 errorf("accept error: %d", SOCKERRNO);
895 break;
896 }
898 /* We don't need the listening socket anymore */
899 sclose(socket_l);
900 socket_l = CURL_SOCKET_BAD;
902 /* Authenticate the reading socket to the writing socket to make sure
903 * we don't leak information.*/
904 if(curlx_win32_random((unsigned char *)&auth_rnd, sizeof(auth_rnd))) {
905 errorf("curlx_win32_random() error");
906 break;
907 }
909 if(swrite_blocking_on_nonblock(socket_r, (unsigned char *)&auth_rnd,
910 sizeof(auth_rnd)))
911 break;
913 if(read_auth_val(tdata.socket_w, &recvd_val))
914 break;
916 if(recvd_val != auth_rnd) {
917 errorf("relay peer auth failed");
918 break;
919 }
921 /* Make a copy of the stdin handle to be used by win_stdin_thread_func */
922 if(!DuplicateHandle(GetCurrentProcess(), GetStdHandle(STD_INPUT_HANDLE),
923 GetCurrentProcess(), &tdata.stdin_handle,
924 0, FALSE, DUPLICATE_SAME_ACCESS)) {
925 errorf("DuplicateHandle error: 0x%08lx", GetLastError());
926 break;
927 }
929 /* Set the stdin handle to read from the socket. */
930 if(SetStdHandle(STD_INPUT_HANDLE, (HANDLE)socket_r) == 0) {
931 errorf("SetStdHandle error: 0x%08lx", GetLastError());
932 break;
933 }
935 /* Start up the thread. We do not bother keeping a reference to it
936 because it runs until program termination. From here on out all reads
937 from the stdin handle or file descriptor 0 is reading from the
938 socket that is fed by the thread. */
939 stdin_thread = CreateThread(NULL, 0, win_stdin_thread_func,
940 NULL, 0, NULL);
941 if(!stdin_thread) {
942 errorf("CreateThread error: 0x%08lx", GetLastError());
943 break;
944 }
945 CloseHandle(stdin_thread);
947 /* Starting the thread is the last thing we do, since there aren't any
948 * reliable ways to close it in case of subsequent errors. */
950 rc = 1;
951 } while(0);
953 if(rc != 1) {
954 /* we rely on the background thread not running at this point, as there
955 * could be TOCTOU bugs otherwise */
956 if(socket_r != CURL_SOCKET_BAD) {
957 if(GetStdHandle(STD_INPUT_HANDLE) == (HANDLE)socket_r &&
958 tdata.stdin_handle) {
959 /* restore STDIN */
960 SetStdHandle(STD_INPUT_HANDLE, tdata.stdin_handle);
961 tdata.stdin_handle = NULL;
962 }
964 sclose(socket_r);
965 socket_r = CURL_SOCKET_BAD;
966 }
968 if(socket_l != CURL_SOCKET_BAD)
969 sclose(socket_l);
971 cleanup_tdata_sync();
972 DeleteCriticalSection(&tdata.crit_sect);
974 return CURL_SOCKET_BAD;
975 }
977 /* prevent mem leak warnings */
978 atexit(&cleanup_tdata_sync);
980 DEBUGASSERT(socket_r != CURL_SOCKET_BAD);
981 return socket_r;
982}
983#endif /* USE_WINSOCK */
985#endif /* !CURL_WINDOWS_UWP */
987CURLcode win32_init(void)
988{
989 curlx_verify_windows_init();
990 curlx_now_init();
991#ifndef CURL_WINDOWS_UWP
992 init_terminal();
993#endif
995 return CURLE_OK;
996}
998#endif /* _WIN32 */
1000#endif /* _WIN32 || MSDOS */
Diagnostics4 git calls · 282 ms
CallStatusSizeTime0282 ms
discover200152 B3 ms
git.upload-pack discover http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=3 git.response.bytes=152 git.server.agent=gitty/1.0 git.server.object_format=sha1 git.server.caps=agent ls-refs fetch object-format git.server.fetch=shallow filter sideband-all git.protocol.version=2 git.pkt.frames=8 git.pkt.data=6 git.pkt.flush=2 git.pkt.delim=0 git.pkt.bytes=152 git.pkt.payload.max=34
ls-refs200149 B · hit2 ms
git.upload-pack ls-refs http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=2 git.response.bytes=149 git.response.cache=HIT git.response.duration_ms=2 git.protocol.version=2 git.pkt.frames=3 git.pkt.data=2 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=149 git.pkt.payload.max=78 git.ls_refs.count=2 git.ls_refs.head=refs/heads/master
fetchblob:none · deepen 10200287 KiB · hit3 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=276 git.response.bytes=293470 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=blob:none git.fetch.filter.requested=tree:0 git.fetch.filter.fallback=blob:none git.fetch.filter.learned=false git.fetch.wants=31c911efe5652725e930f4d2e60c9060e5f6646d git.fetch.haves.count=0 git.fetch.deepen=10 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=10 git.pkt.data=8 git.pkt.flush=1 git.pkt.delim=1 git.pkt.bytes=293470 git.pkt.payload.max=65516 git.sideband.band1.bytes=293354 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=87 git.pack.bytes=293354 git.pack.ofs_delta=0 git.pack.ref_delta=1 git.pack.chain.max=1 git.pack.trailer=6a646bcda6740bab42e321b51998b52ea15146c0 git.pack.full=86Open pack map
fetch20010 KiB276 ms
git.upload-pack fetch http.response.status_code=200 git.response.bytes=10241 git.response.cache=MISS git.response.duration_ms=276 git.fetch.wants=dc3628103fcee7fcefae972362fc477bef138530 git.fetch.haves.count=0 git.fetch.deepen=0 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=3 git.pkt.data=2 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=10241 git.pkt.payload.max=10220 git.sideband.band1.bytes=10219 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0
Each row is one HTTP round trip ply made to the git server for this page, on one timeline. discover asks what the server speaks, ls-refs lists branch tips, fetch brings objects by id. A hit was served by Workers Cache. Tap a row for its wire details.
- Remote
- https://5ad2236b39de4c8bd8f6270ea63f3ea9.artifacts.cloudflare.net/git/public-v0/curl.git
- Ref
- refs/heads/master
- Commit
- 31c911efe5652725e930f4d2e60c9060e5f6646d
- cf-ray
- a5e1858d1830dbb4
- Request
- b7076472…
- Protocol
- v2 · sha1
- Agent
- gitty/1.0
- Filter
- advertised
- Fetch
- shallow filter sideband-all
- Capabilities
- agent ls-refs fetch object-format