1 /* mswindows.c -- Windows-specific support
2 Copyright (C) 1995, 1996, 1997, 1998, 2004
3 Free Software Foundation, Inc.
5 This file is part of GNU Wget.
7 GNU Wget is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
12 GNU Wget is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with Wget; if not, write to the Free Software
19 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21 In addition, as a special exception, the Free Software Foundation
22 gives permission to link the code of its release of Wget with the
23 OpenSSL project's "OpenSSL" library (or with modified versions of it
24 that use the same license as the "OpenSSL" library), and distribute
25 the linked executables. You must obey the GNU General Public License
26 in all respects for all of the code used other than "OpenSSL". If you
27 modify this file, you may extend this exception to your version of the
28 file, but you are not obligated to do so. If you do not wish to do
29 so, delete this exception statement from your version. */
40 #ifdef HACK_BCC_UTIME_BUG
46 # ifdef HAVE_SYS_UTIME_H
47 # include <sys/utime.h>
59 #ifndef ES_SYSTEM_REQUIRED
60 #define ES_SYSTEM_REQUIRED 0x00000001
64 #define ES_CONTINUOUS 0x80000000
68 /* Defined in log.c. */
69 void log_request_redirect_output PARAMS ((const char *));
71 /* Windows version of xsleep in utils.c. */
74 xsleep (double seconds)
79 /* Explained in utils.c. */
81 seconds -= (long) seconds;
83 usleep (seconds * 1000000L);
84 #else /* not HAVE_USLEEP */
85 SleepEx (seconds * 1000, FALSE);
86 #endif /* not HAVE_USLEEP */
89 #if defined(__BORLANDC__) || (defined(_MSC_VER) && _MSC_VER < 1300)
92 char_value (char c, int base)
97 if ('0' <= c && c <= '9')
99 else if ('a' <= c && c <= 'z')
100 value = c - 'a' + 10;
101 else if ('A' <= c && c <= 'Z')
102 value = c - 'A' + 10;
110 /* A fairly simple strtoll replacement for MS VC versions that don't
114 str_to_int64 (const char *nptr, char **endptr, int base)
116 #define OVERFLOW 9223372036854775807I64
117 #define UNDERFLOW (-OVERFLOW - 1)
122 if (base != 0 && (base < 2 || base > 36))
128 while (*nptr == ' ' || *nptr == '\t')
135 else if (*nptr == '+')
143 /* If base is 0, determine the real base based on the beginning on
144 the number; octal numbers begin with "0", hexadecimal with "0x",
145 and the others are considered octal. */
148 if ((base == 0 || base == 16)
150 (*(nptr + 1) == 'x' || *(nptr + 1) == 'X'))
163 /* Parse positive number, checking for overflow. */
165 for (; (val = char_value (*nptr, base)) != -1; ++nptr)
167 __int64 newresult = base * result + val;
168 if (newresult < result)
179 /* Parse negative number, checking for underflow. */
181 for (; (val = char_value (*nptr, base)) != -1; ++nptr)
183 __int64 newresult = base * result - val;
184 if (newresult > result)
194 *endptr = (char *) nptr;
198 #else /* !defined(__BORLANDC__) && (!defined(_MSC_VER) || _MSC_VER >= 1300) */
201 str_to_int64 (const char *nptr, char **endptr, int base)
204 return _strtoi64 (nptr, endptr, base);
206 return strtoll (nptr, endptr, base);
210 #endif /* !defined(__BORLANDC__) && (!defined(_MSC_VER) || _MSC_VER >= 1300) */
213 windows_main_junk (int *argc, char **argv, char **exec_name)
217 /* Remove .EXE from filename if it has one. */
218 *exec_name = xstrdup (*exec_name);
219 p = strrchr (*exec_name, '.');
231 ws_hangup (const char *reason)
233 fprintf (stderr, _("Continuing in background.\n"));
234 log_request_redirect_output (reason);
236 /* Detach process from the current console. Under Windows 9x, if we
237 were launched from a 16-bit process (which is usually the case;
238 command.com is 16-bit) the parent process should resume right away.
239 Under NT or if launched from a 32-process under 9x, this is a futile
240 gesture as the parent will wait for us to terminate before resuming. */
244 /* Construct the name for a named section (a.k.a. `file mapping') object.
245 The returned string is dynamically allocated and needs to be xfree()'d. */
247 make_section_name (DWORD pid)
249 return aprintf ("gnu_wget_fake_fork_%lu", pid);
252 /* This structure is used to hold all the data that is exchanged between
254 struct fake_fork_info
258 char lfilename[MAX_PATH + 1];
261 /* Determines if we are the child and if so performs the child logic.
268 fake_fork_child (void)
270 HANDLE section, event;
271 struct fake_fork_info *info;
274 name = make_section_name (GetCurrentProcessId ());
275 section = OpenFileMapping (FILE_MAP_WRITE, FALSE, name);
277 /* It seems that Windows 9x and NT set last-error inconsistently when
278 OpenFileMapping() fails; so we assume it failed because the section
279 object does not exist. */
281 return 0; /* We are the parent. */
283 info = MapViewOfFile (section, FILE_MAP_WRITE, 0, 0, 0);
286 CloseHandle (section);
292 info->logfile_changed = 0;
295 /* See utils:fork_to_background for explanation. */
296 FILE *new_log_fp = unique_create (DEFAULT_LOGFILE, 0, &opt.lfilename);
299 info->logfile_changed = 1;
300 strncpy (info->lfilename, opt.lfilename, sizeof (info->lfilename));
301 info->lfilename[sizeof (info->lfilename) - 1] = '\0';
306 UnmapViewOfFile (info);
307 CloseHandle (section);
309 /* Inform the parent that we've done our part. */
310 if (!SetEvent (event))
314 return 1; /* We are the child. */
317 /* Windows doesn't support the fork() call; so we fake it by invoking
318 another copy of Wget with the same arguments with which we were
319 invoked. The child copy of Wget should perform the same initialization
320 sequence as the parent; so we should have two processes that are
321 essentially identical. We create a specially named section object that
322 allows the child to distinguish itself from the parent and is used to
323 exchange information between the two processes. We use an event object
324 for synchronization. */
328 char exe[MAX_PATH + 1];
330 SECURITY_ATTRIBUTES sa;
331 HANDLE section, event, h[2];
333 PROCESS_INFORMATION pi;
334 struct fake_fork_info *info;
338 event = section = pi.hProcess = pi.hThread = NULL;
340 /* Get the fully qualified name of our executable. This is more reliable
341 than using argv[0]. */
342 exe_len = GetModuleFileName (GetModuleHandle (NULL), exe, sizeof (exe));
343 if (!exe_len || (exe_len >= sizeof (exe)))
346 sa.nLength = sizeof (sa);
347 sa.lpSecurityDescriptor = NULL;
348 sa.bInheritHandle = TRUE;
350 /* Create an anonymous inheritable event object that starts out
352 event = CreateEvent (&sa, FALSE, FALSE, NULL);
356 /* Create the child process detached form the current console and in a
358 memset (&si, 0, sizeof (si));
360 rv = CreateProcess (exe, GetCommandLine (), NULL, NULL, TRUE,
361 CREATE_SUSPENDED | DETACHED_PROCESS,
362 NULL, NULL, &si, &pi);
366 /* Create a named section object with a name based on the process id of
368 name = make_section_name (pi.dwProcessId);
370 CreateFileMapping (INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0,
371 sizeof (struct fake_fork_info), name);
374 /* Fail if the section object already exists (should not happen). */
375 if (!section || (le == ERROR_ALREADY_EXISTS))
381 /* Copy the event handle into the section object. */
382 info = MapViewOfFile (section, FILE_MAP_WRITE, 0, 0, 0);
391 UnmapViewOfFile (info);
393 /* Start the child process. */
394 rv = ResumeThread (pi.hThread);
397 TerminateProcess (pi.hProcess, (DWORD) -1);
401 /* Wait for the child to signal to us that it has done its part. If it
402 terminates before signaling us it's an error. */
406 rv = WAIT_OBJECT_0 == WaitForMultipleObjects (2, h, FALSE, 5 * 60 * 1000);
410 info = MapViewOfFile (section, FILE_MAP_READ, 0, 0, 0);
417 /* Ensure string is properly terminated. */
418 if (info->logfile_changed &&
419 !memchr (info->lfilename, '\0', sizeof (info->lfilename)))
425 printf (_("Continuing in background, pid %lu.\n"), pi.dwProcessId);
426 if (info->logfile_changed)
427 printf (_("Output will be written to `%s'.\n"), info->lfilename);
429 UnmapViewOfFile (info);
436 CloseHandle (section);
438 CloseHandle (pi.hThread);
440 CloseHandle (pi.hProcess);
442 /* We're the parent. If all is well, terminate. */
446 /* We failed, return. */
449 /* This is the corresponding Windows implementation of the
450 fork_to_background() function in utils.c. */
452 fork_to_background (void)
456 rv = fake_fork_child ();
459 fprintf (stderr, "fake_fork_child() failed\n");
464 /* We're the parent. */
466 /* If fake_fork() returns, it failed. */
467 fprintf (stderr, "fake_fork() failed\n");
470 /* If we get here, we're the child. */
474 ws_handler (DWORD dwEvent)
480 ws_hangup ("CTRL+C");
483 #ifdef CTRLBREAK_BACKGND
484 case CTRL_BREAK_EVENT:
485 ws_hangup ("CTRL+Break");
493 static char *title_buf = NULL;
494 static char *curr_url = NULL;
495 static int old_percentage = -1;
497 /* Updates the console title with the URL of the current file being
500 ws_changetitle (const char *url)
502 xfree_null (title_buf);
503 xfree_null (curr_url);
504 title_buf = (char *)xmalloc (strlen (url) + 20);
505 curr_url = xstrdup (url);
507 sprintf (title_buf, "Wget %s", curr_url);
508 SetConsoleTitle (title_buf);
511 /* Updates the console title with the percentage of the current file
514 ws_percenttitle (double percentage_float)
518 if (!title_buf || !curr_url)
521 percentage = (int) percentage_float;
523 /* Clamp percentage value. */
526 if (percentage > 100)
529 /* Only update the title when the percentage has changed. */
530 if (percentage == old_percentage)
533 old_percentage = percentage;
535 sprintf (title_buf, "Wget [%d%%] %s", percentage, curr_url);
536 SetConsoleTitle (title_buf);
539 /* Returns a pointer to the fully qualified name of the directory that
540 contains the Wget binary (wget.exe). The returned path does not have a
541 trailing path separator. Returns NULL on failure. */
545 static char *wspathsave = NULL;
549 char buf[MAX_PATH + 1];
553 len = GetModuleFileName (GetModuleHandle (NULL), buf, sizeof (buf));
554 if (!len || (len >= sizeof (buf)))
557 p = strrchr (buf, PATH_SEPARATOR);
562 wspathsave = xstrdup (buf);
568 /* Prevent Windows entering sleep/hibernation-mode while Wget is doing
569 a lengthy transfer. Windows does not, by default, consider network
570 activity in console-programs as activity! Works on Win-98/ME/2K
573 set_sleep_mode (void)
575 typedef DWORD (WINAPI *func_t) (DWORD);
576 func_t set_exec_state;
579 (func_t) GetProcAddress (GetModuleHandle ("KERNEL32.DLL"),
580 "SetThreadExecutionState");
583 set_exec_state (ES_SYSTEM_REQUIRED | ES_CONTINUOUS);
586 /* Perform Windows specific initialization. */
594 requested = MAKEWORD (1, 1);
595 err = WSAStartup (requested, &data);
598 fprintf (stderr, _("%s: Couldn't find usable socket driver.\n"),
603 if (data.wVersion < requested)
605 fprintf (stderr, _("%s: Couldn't find usable socket driver.\n"),
613 SetConsoleCtrlHandler (ws_handler, TRUE);
616 /* Replacement utime function for buggy Borland C++Builder 5.5 compiler.
617 (The Borland utime function only works on Windows NT.) */
619 #ifdef HACK_BCC_UTIME_BUG
621 borland_utime (const char *path, const struct utimbuf *times)
628 if ((fd = open (path, O_RDWR)) < 0)
631 ptr_tm = localtime (×->modtime);
632 ft.ft_tsec = ptr_tm->tm_sec >> 1;
633 ft.ft_min = ptr_tm->tm_min;
634 ft.ft_hour = ptr_tm->tm_hour;
635 ft.ft_day = ptr_tm->tm_mday;
636 ft.ft_month = ptr_tm->tm_mon + 1;
637 ft.ft_year = ptr_tm->tm_year - 80;
638 res = setftime (fd, &ft);
644 /* run_with_timeout Windows implementation. */
646 /* Stack size 0 uses default thread stack-size (reserve+commit).
647 Determined by what's in the PE header. */
648 #define THREAD_STACK_SIZE 0
652 void (*fun) (void *);
657 /* The callback that runs FUN(ARG) in a separate thread. This
658 function exists for two reasons: a) to not require FUN to be
659 declared WINAPI/__stdcall[1], and b) to retrieve Winsock errors,
660 which are per-thread. The latter is useful when FUN calls Winsock
661 functions, which is how run_with_timeout is used in Wget.
663 [1] MSVC can use __fastcall globally (cl /Gr) and on Watcom this is
664 the default (wcc386 -3r). */
667 thread_helper (void *arg)
669 struct thread_data *td = (struct thread_data *) arg;
671 /* Initialize Winsock error to what it was in the parent. That way
672 the subsequent call to WSAGetLastError will return the same value
673 if td->fun doesn't change Winsock error state. */
674 WSASetLastError (td->ws_error);
678 /* Return Winsock error to the caller, in case FUN ran Winsock
680 td->ws_error = WSAGetLastError ();
684 /* Call FUN(ARG), but don't allow it to run for more than TIMEOUT
685 seconds. Returns non-zero if the function was interrupted with a
686 timeout, zero otherwise.
688 This works by running FUN in a separate thread and terminating the
689 thread if it doesn't finish in the specified time. */
692 run_with_timeout (double seconds, void (*fun) (void *), void *arg)
694 static HANDLE thread_hnd = NULL;
695 struct thread_data thread_arg;
699 DEBUGP (("seconds %.2f, ", seconds));
708 /* Should never happen, but test for recursivety anyway. */
709 assert (thread_hnd == NULL);
711 thread_arg.fun = fun;
712 thread_arg.arg = arg;
713 thread_arg.ws_error = WSAGetLastError ();
714 thread_hnd = CreateThread (NULL, THREAD_STACK_SIZE, thread_helper,
715 &thread_arg, 0, &thread_id);
718 DEBUGP (("CreateThread() failed; %s\n", strerror (GetLastError ())));
719 goto blocking_fallback;
722 if (WaitForSingleObject (thread_hnd, (DWORD)(1000 * seconds))
725 /* Propagate error state (which is per-thread) to this thread,
726 so the caller can inspect it. */
727 WSASetLastError (thread_arg.ws_error);
728 DEBUGP (("Winsock error: %d\n", WSAGetLastError ()));
733 TerminateThread (thread_hnd, 1);
737 CloseHandle (thread_hnd); /* Clear-up after TerminateThread(). */