mingw: reuse tty-version of git_terminal_prompt
[git.git] / compat / mingw.c
1 #include "../git-compat-util.h"
2 #include "win32.h"
3 #include <conio.h>
4 #include "../strbuf.h"
5 #include "../run-command.h"
6
7 static const int delay[] = { 0, 1, 10, 20, 40 };
8
9 int err_win_to_posix(DWORD winerr)
10 {
11         int error = ENOSYS;
12         switch(winerr) {
13         case ERROR_ACCESS_DENIED: error = EACCES; break;
14         case ERROR_ACCOUNT_DISABLED: error = EACCES; break;
15         case ERROR_ACCOUNT_RESTRICTION: error = EACCES; break;
16         case ERROR_ALREADY_ASSIGNED: error = EBUSY; break;
17         case ERROR_ALREADY_EXISTS: error = EEXIST; break;
18         case ERROR_ARITHMETIC_OVERFLOW: error = ERANGE; break;
19         case ERROR_BAD_COMMAND: error = EIO; break;
20         case ERROR_BAD_DEVICE: error = ENODEV; break;
21         case ERROR_BAD_DRIVER_LEVEL: error = ENXIO; break;
22         case ERROR_BAD_EXE_FORMAT: error = ENOEXEC; break;
23         case ERROR_BAD_FORMAT: error = ENOEXEC; break;
24         case ERROR_BAD_LENGTH: error = EINVAL; break;
25         case ERROR_BAD_PATHNAME: error = ENOENT; break;
26         case ERROR_BAD_PIPE: error = EPIPE; break;
27         case ERROR_BAD_UNIT: error = ENODEV; break;
28         case ERROR_BAD_USERNAME: error = EINVAL; break;
29         case ERROR_BROKEN_PIPE: error = EPIPE; break;
30         case ERROR_BUFFER_OVERFLOW: error = ENAMETOOLONG; break;
31         case ERROR_BUSY: error = EBUSY; break;
32         case ERROR_BUSY_DRIVE: error = EBUSY; break;
33         case ERROR_CALL_NOT_IMPLEMENTED: error = ENOSYS; break;
34         case ERROR_CANNOT_MAKE: error = EACCES; break;
35         case ERROR_CANTOPEN: error = EIO; break;
36         case ERROR_CANTREAD: error = EIO; break;
37         case ERROR_CANTWRITE: error = EIO; break;
38         case ERROR_CRC: error = EIO; break;
39         case ERROR_CURRENT_DIRECTORY: error = EACCES; break;
40         case ERROR_DEVICE_IN_USE: error = EBUSY; break;
41         case ERROR_DEV_NOT_EXIST: error = ENODEV; break;
42         case ERROR_DIRECTORY: error = EINVAL; break;
43         case ERROR_DIR_NOT_EMPTY: error = ENOTEMPTY; break;
44         case ERROR_DISK_CHANGE: error = EIO; break;
45         case ERROR_DISK_FULL: error = ENOSPC; break;
46         case ERROR_DRIVE_LOCKED: error = EBUSY; break;
47         case ERROR_ENVVAR_NOT_FOUND: error = EINVAL; break;
48         case ERROR_EXE_MARKED_INVALID: error = ENOEXEC; break;
49         case ERROR_FILENAME_EXCED_RANGE: error = ENAMETOOLONG; break;
50         case ERROR_FILE_EXISTS: error = EEXIST; break;
51         case ERROR_FILE_INVALID: error = ENODEV; break;
52         case ERROR_FILE_NOT_FOUND: error = ENOENT; break;
53         case ERROR_GEN_FAILURE: error = EIO; break;
54         case ERROR_HANDLE_DISK_FULL: error = ENOSPC; break;
55         case ERROR_INSUFFICIENT_BUFFER: error = ENOMEM; break;
56         case ERROR_INVALID_ACCESS: error = EACCES; break;
57         case ERROR_INVALID_ADDRESS: error = EFAULT; break;
58         case ERROR_INVALID_BLOCK: error = EFAULT; break;
59         case ERROR_INVALID_DATA: error = EINVAL; break;
60         case ERROR_INVALID_DRIVE: error = ENODEV; break;
61         case ERROR_INVALID_EXE_SIGNATURE: error = ENOEXEC; break;
62         case ERROR_INVALID_FLAGS: error = EINVAL; break;
63         case ERROR_INVALID_FUNCTION: error = ENOSYS; break;
64         case ERROR_INVALID_HANDLE: error = EBADF; break;
65         case ERROR_INVALID_LOGON_HOURS: error = EACCES; break;
66         case ERROR_INVALID_NAME: error = EINVAL; break;
67         case ERROR_INVALID_OWNER: error = EINVAL; break;
68         case ERROR_INVALID_PARAMETER: error = EINVAL; break;
69         case ERROR_INVALID_PASSWORD: error = EPERM; break;
70         case ERROR_INVALID_PRIMARY_GROUP: error = EINVAL; break;
71         case ERROR_INVALID_SIGNAL_NUMBER: error = EINVAL; break;
72         case ERROR_INVALID_TARGET_HANDLE: error = EIO; break;
73         case ERROR_INVALID_WORKSTATION: error = EACCES; break;
74         case ERROR_IO_DEVICE: error = EIO; break;
75         case ERROR_IO_INCOMPLETE: error = EINTR; break;
76         case ERROR_LOCKED: error = EBUSY; break;
77         case ERROR_LOCK_VIOLATION: error = EACCES; break;
78         case ERROR_LOGON_FAILURE: error = EACCES; break;
79         case ERROR_MAPPED_ALIGNMENT: error = EINVAL; break;
80         case ERROR_META_EXPANSION_TOO_LONG: error = E2BIG; break;
81         case ERROR_MORE_DATA: error = EPIPE; break;
82         case ERROR_NEGATIVE_SEEK: error = ESPIPE; break;
83         case ERROR_NOACCESS: error = EFAULT; break;
84         case ERROR_NONE_MAPPED: error = EINVAL; break;
85         case ERROR_NOT_ENOUGH_MEMORY: error = ENOMEM; break;
86         case ERROR_NOT_READY: error = EAGAIN; break;
87         case ERROR_NOT_SAME_DEVICE: error = EXDEV; break;
88         case ERROR_NO_DATA: error = EPIPE; break;
89         case ERROR_NO_MORE_SEARCH_HANDLES: error = EIO; break;
90         case ERROR_NO_PROC_SLOTS: error = EAGAIN; break;
91         case ERROR_NO_SUCH_PRIVILEGE: error = EACCES; break;
92         case ERROR_OPEN_FAILED: error = EIO; break;
93         case ERROR_OPEN_FILES: error = EBUSY; break;
94         case ERROR_OPERATION_ABORTED: error = EINTR; break;
95         case ERROR_OUTOFMEMORY: error = ENOMEM; break;
96         case ERROR_PASSWORD_EXPIRED: error = EACCES; break;
97         case ERROR_PATH_BUSY: error = EBUSY; break;
98         case ERROR_PATH_NOT_FOUND: error = ENOENT; break;
99         case ERROR_PIPE_BUSY: error = EBUSY; break;
100         case ERROR_PIPE_CONNECTED: error = EPIPE; break;
101         case ERROR_PIPE_LISTENING: error = EPIPE; break;
102         case ERROR_PIPE_NOT_CONNECTED: error = EPIPE; break;
103         case ERROR_PRIVILEGE_NOT_HELD: error = EACCES; break;
104         case ERROR_READ_FAULT: error = EIO; break;
105         case ERROR_SEEK: error = EIO; break;
106         case ERROR_SEEK_ON_DEVICE: error = ESPIPE; break;
107         case ERROR_SHARING_BUFFER_EXCEEDED: error = ENFILE; break;
108         case ERROR_SHARING_VIOLATION: error = EACCES; break;
109         case ERROR_STACK_OVERFLOW: error = ENOMEM; break;
110         case ERROR_SWAPERROR: error = ENOENT; break;
111         case ERROR_TOO_MANY_MODULES: error = EMFILE; break;
112         case ERROR_TOO_MANY_OPEN_FILES: error = EMFILE; break;
113         case ERROR_UNRECOGNIZED_MEDIA: error = ENXIO; break;
114         case ERROR_UNRECOGNIZED_VOLUME: error = ENODEV; break;
115         case ERROR_WAIT_NO_CHILDREN: error = ECHILD; break;
116         case ERROR_WRITE_FAULT: error = EIO; break;
117         case ERROR_WRITE_PROTECT: error = EROFS; break;
118         }
119         return error;
120 }
121
122 static inline int is_file_in_use_error(DWORD errcode)
123 {
124         switch (errcode) {
125         case ERROR_SHARING_VIOLATION:
126         case ERROR_ACCESS_DENIED:
127                 return 1;
128         }
129
130         return 0;
131 }
132
133 static int read_yes_no_answer(void)
134 {
135         char answer[1024];
136
137         if (fgets(answer, sizeof(answer), stdin)) {
138                 size_t answer_len = strlen(answer);
139                 int got_full_line = 0, c;
140
141                 /* remove the newline */
142                 if (answer_len >= 2 && answer[answer_len-2] == '\r') {
143                         answer[answer_len-2] = '\0';
144                         got_full_line = 1;
145                 } else if (answer_len >= 1 && answer[answer_len-1] == '\n') {
146                         answer[answer_len-1] = '\0';
147                         got_full_line = 1;
148                 }
149                 /* flush the buffer in case we did not get the full line */
150                 if (!got_full_line)
151                         while ((c = getchar()) != EOF && c != '\n')
152                                 ;
153         } else
154                 /* we could not read, return the
155                  * default answer which is no */
156                 return 0;
157
158         if (tolower(answer[0]) == 'y' && !answer[1])
159                 return 1;
160         if (!strncasecmp(answer, "yes", sizeof(answer)))
161                 return 1;
162         if (tolower(answer[0]) == 'n' && !answer[1])
163                 return 0;
164         if (!strncasecmp(answer, "no", sizeof(answer)))
165                 return 0;
166
167         /* did not find an answer we understand */
168         return -1;
169 }
170
171 static int ask_yes_no_if_possible(const char *format, ...)
172 {
173         char question[4096];
174         const char *retry_hook[] = { NULL, NULL, NULL };
175         va_list args;
176
177         va_start(args, format);
178         vsnprintf(question, sizeof(question), format, args);
179         va_end(args);
180
181         if ((retry_hook[0] = mingw_getenv("GIT_ASK_YESNO"))) {
182                 retry_hook[1] = question;
183                 return !run_command_v_opt(retry_hook, 0);
184         }
185
186         if (!isatty(_fileno(stdin)) || !isatty(_fileno(stderr)))
187                 return 0;
188
189         while (1) {
190                 int answer;
191                 fprintf(stderr, "%s (y/n) ", question);
192
193                 if ((answer = read_yes_no_answer()) >= 0)
194                         return answer;
195
196                 fprintf(stderr, "Sorry, I did not understand your answer. "
197                                 "Please type 'y' or 'n'\n");
198         }
199 }
200
201 #undef unlink
202 int mingw_unlink(const char *pathname)
203 {
204         int ret, tries = 0;
205
206         /* read-only files cannot be removed */
207         chmod(pathname, 0666);
208         while ((ret = unlink(pathname)) == -1 && tries < ARRAY_SIZE(delay)) {
209                 if (!is_file_in_use_error(GetLastError()))
210                         break;
211                 /*
212                  * We assume that some other process had the source or
213                  * destination file open at the wrong moment and retry.
214                  * In order to give the other process a higher chance to
215                  * complete its operation, we give up our time slice now.
216                  * If we have to retry again, we do sleep a bit.
217                  */
218                 Sleep(delay[tries]);
219                 tries++;
220         }
221         while (ret == -1 && is_file_in_use_error(GetLastError()) &&
222                ask_yes_no_if_possible("Unlink of file '%s' failed. "
223                         "Should I try again?", pathname))
224                ret = unlink(pathname);
225         return ret;
226 }
227
228 static int is_dir_empty(const char *path)
229 {
230         struct strbuf buf = STRBUF_INIT;
231         WIN32_FIND_DATAA findbuf;
232         HANDLE handle;
233
234         strbuf_addf(&buf, "%s\\*", path);
235         handle = FindFirstFileA(buf.buf, &findbuf);
236         if (handle == INVALID_HANDLE_VALUE) {
237                 strbuf_release(&buf);
238                 return GetLastError() == ERROR_NO_MORE_FILES;
239         }
240
241         while (!strcmp(findbuf.cFileName, ".") ||
242                         !strcmp(findbuf.cFileName, ".."))
243                 if (!FindNextFile(handle, &findbuf)) {
244                         strbuf_release(&buf);
245                         return GetLastError() == ERROR_NO_MORE_FILES;
246                 }
247         FindClose(handle);
248         strbuf_release(&buf);
249         return 0;
250 }
251
252 #undef rmdir
253 int mingw_rmdir(const char *pathname)
254 {
255         int ret, tries = 0;
256
257         while ((ret = rmdir(pathname)) == -1 && tries < ARRAY_SIZE(delay)) {
258                 if (!is_file_in_use_error(GetLastError()))
259                         break;
260                 if (!is_dir_empty(pathname)) {
261                         errno = ENOTEMPTY;
262                         break;
263                 }
264                 /*
265                  * We assume that some other process had the source or
266                  * destination file open at the wrong moment and retry.
267                  * In order to give the other process a higher chance to
268                  * complete its operation, we give up our time slice now.
269                  * If we have to retry again, we do sleep a bit.
270                  */
271                 Sleep(delay[tries]);
272                 tries++;
273         }
274         while (ret == -1 && is_file_in_use_error(GetLastError()) &&
275                ask_yes_no_if_possible("Deletion of directory '%s' failed. "
276                         "Should I try again?", pathname))
277                ret = rmdir(pathname);
278         return ret;
279 }
280
281 #undef open
282 int mingw_open (const char *filename, int oflags, ...)
283 {
284         va_list args;
285         unsigned mode;
286         int fd;
287
288         va_start(args, oflags);
289         mode = va_arg(args, int);
290         va_end(args);
291
292         if (filename && !strcmp(filename, "/dev/null"))
293                 filename = "nul";
294
295         fd = open(filename, oflags, mode);
296
297         if (fd < 0 && (oflags & O_CREAT) && errno == EACCES) {
298                 DWORD attrs = GetFileAttributes(filename);
299                 if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY))
300                         errno = EISDIR;
301         }
302         return fd;
303 }
304
305 #undef write
306 ssize_t mingw_write(int fd, const void *buf, size_t count)
307 {
308         /*
309          * While write() calls to a file on a local disk are translated
310          * into WriteFile() calls with a maximum size of 64KB on Windows
311          * XP and 256KB on Vista, no such cap is placed on writes to
312          * files over the network on Windows XP.  Unfortunately, there
313          * seems to be a limit of 32MB-28KB on X64 and 64MB-32KB on x86;
314          * bigger writes fail on Windows XP.
315          * So we cap to a nice 31MB here to avoid write failures over
316          * the net without changing the number of WriteFile() calls in
317          * the local case.
318          */
319         return write(fd, buf, min(count, 31 * 1024 * 1024));
320 }
321
322 static BOOL WINAPI ctrl_ignore(DWORD type)
323 {
324         return TRUE;
325 }
326
327 #undef fgetc
328 int mingw_fgetc(FILE *stream)
329 {
330         int ch;
331         if (!isatty(_fileno(stream)))
332                 return fgetc(stream);
333
334         SetConsoleCtrlHandler(ctrl_ignore, TRUE);
335         while (1) {
336                 ch = fgetc(stream);
337                 if (ch != EOF || GetLastError() != ERROR_OPERATION_ABORTED)
338                         break;
339
340                 /* Ctrl+C was pressed, simulate SIGINT and retry */
341                 mingw_raise(SIGINT);
342         }
343         SetConsoleCtrlHandler(ctrl_ignore, FALSE);
344         return ch;
345 }
346
347 #undef fopen
348 FILE *mingw_fopen (const char *filename, const char *otype)
349 {
350         if (filename && !strcmp(filename, "/dev/null"))
351                 filename = "nul";
352         return fopen(filename, otype);
353 }
354
355 #undef freopen
356 FILE *mingw_freopen (const char *filename, const char *otype, FILE *stream)
357 {
358         if (filename && !strcmp(filename, "/dev/null"))
359                 filename = "nul";
360         return freopen(filename, otype, stream);
361 }
362
363 #undef fflush
364 int mingw_fflush(FILE *stream)
365 {
366         int ret = fflush(stream);
367
368         /*
369          * write() is used behind the scenes of stdio output functions.
370          * Since git code does not check for errors after each stdio write
371          * operation, it can happen that write() is called by a later
372          * stdio function even if an earlier write() call failed. In the
373          * case of a pipe whose readable end was closed, only the first
374          * call to write() reports EPIPE on Windows. Subsequent write()
375          * calls report EINVAL. It is impossible to notice whether this
376          * fflush invocation triggered such a case, therefore, we have to
377          * catch all EINVAL errors whole-sale.
378          */
379         if (ret && errno == EINVAL)
380                 errno = EPIPE;
381
382         return ret;
383 }
384
385 /*
386  * The unit of FILETIME is 100-nanoseconds since January 1, 1601, UTC.
387  * Returns the 100-nanoseconds ("hekto nanoseconds") since the epoch.
388  */
389 static inline long long filetime_to_hnsec(const FILETIME *ft)
390 {
391         long long winTime = ((long long)ft->dwHighDateTime << 32) + ft->dwLowDateTime;
392         /* Windows to Unix Epoch conversion */
393         return winTime - 116444736000000000LL;
394 }
395
396 static inline time_t filetime_to_time_t(const FILETIME *ft)
397 {
398         return (time_t)(filetime_to_hnsec(ft) / 10000000);
399 }
400
401 /* We keep the do_lstat code in a separate function to avoid recursion.
402  * When a path ends with a slash, the stat will fail with ENOENT. In
403  * this case, we strip the trailing slashes and stat again.
404  *
405  * If follow is true then act like stat() and report on the link
406  * target. Otherwise report on the link itself.
407  */
408 static int do_lstat(int follow, const char *file_name, struct stat *buf)
409 {
410         int err;
411         WIN32_FILE_ATTRIBUTE_DATA fdata;
412
413         if (!(err = get_file_attr(file_name, &fdata))) {
414                 buf->st_ino = 0;
415                 buf->st_gid = 0;
416                 buf->st_uid = 0;
417                 buf->st_nlink = 1;
418                 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
419                 buf->st_size = fdata.nFileSizeLow |
420                         (((off_t)fdata.nFileSizeHigh)<<32);
421                 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
422                 buf->st_atime = filetime_to_time_t(&(fdata.ftLastAccessTime));
423                 buf->st_mtime = filetime_to_time_t(&(fdata.ftLastWriteTime));
424                 buf->st_ctime = filetime_to_time_t(&(fdata.ftCreationTime));
425                 if (fdata.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
426                         WIN32_FIND_DATAA findbuf;
427                         HANDLE handle = FindFirstFileA(file_name, &findbuf);
428                         if (handle != INVALID_HANDLE_VALUE) {
429                                 if ((findbuf.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
430                                                 (findbuf.dwReserved0 == IO_REPARSE_TAG_SYMLINK)) {
431                                         if (follow) {
432                                                 char buffer[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
433                                                 buf->st_size = readlink(file_name, buffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE);
434                                         } else {
435                                                 buf->st_mode = S_IFLNK;
436                                         }
437                                         buf->st_mode |= S_IREAD;
438                                         if (!(findbuf.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
439                                                 buf->st_mode |= S_IWRITE;
440                                 }
441                                 FindClose(handle);
442                         }
443                 }
444                 return 0;
445         }
446         errno = err;
447         return -1;
448 }
449
450 /* We provide our own lstat/fstat functions, since the provided
451  * lstat/fstat functions are so slow. These stat functions are
452  * tailored for Git's usage (read: fast), and are not meant to be
453  * complete. Note that Git stat()s are redirected to mingw_lstat()
454  * too, since Windows doesn't really handle symlinks that well.
455  */
456 static int do_stat_internal(int follow, const char *file_name, struct stat *buf)
457 {
458         int namelen;
459         static char alt_name[PATH_MAX];
460
461         if (!do_lstat(follow, file_name, buf))
462                 return 0;
463
464         /* if file_name ended in a '/', Windows returned ENOENT;
465          * try again without trailing slashes
466          */
467         if (errno != ENOENT)
468                 return -1;
469
470         namelen = strlen(file_name);
471         if (namelen && file_name[namelen-1] != '/')
472                 return -1;
473         while (namelen && file_name[namelen-1] == '/')
474                 --namelen;
475         if (!namelen || namelen >= PATH_MAX)
476                 return -1;
477
478         memcpy(alt_name, file_name, namelen);
479         alt_name[namelen] = 0;
480         return do_lstat(follow, alt_name, buf);
481 }
482
483 int mingw_lstat(const char *file_name, struct stat *buf)
484 {
485         return do_stat_internal(0, file_name, buf);
486 }
487 int mingw_stat(const char *file_name, struct stat *buf)
488 {
489         return do_stat_internal(1, file_name, buf);
490 }
491
492 #undef fstat
493 int mingw_fstat(int fd, struct stat *buf)
494 {
495         HANDLE fh = (HANDLE)_get_osfhandle(fd);
496         BY_HANDLE_FILE_INFORMATION fdata;
497
498         if (fh == INVALID_HANDLE_VALUE) {
499                 errno = EBADF;
500                 return -1;
501         }
502         /* direct non-file handles to MS's fstat() */
503         if (GetFileType(fh) != FILE_TYPE_DISK)
504                 return _fstati64(fd, buf);
505
506         if (GetFileInformationByHandle(fh, &fdata)) {
507                 buf->st_ino = 0;
508                 buf->st_gid = 0;
509                 buf->st_uid = 0;
510                 buf->st_nlink = 1;
511                 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
512                 buf->st_size = fdata.nFileSizeLow |
513                         (((off_t)fdata.nFileSizeHigh)<<32);
514                 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
515                 buf->st_atime = filetime_to_time_t(&(fdata.ftLastAccessTime));
516                 buf->st_mtime = filetime_to_time_t(&(fdata.ftLastWriteTime));
517                 buf->st_ctime = filetime_to_time_t(&(fdata.ftCreationTime));
518                 return 0;
519         }
520         errno = EBADF;
521         return -1;
522 }
523
524 static inline void time_t_to_filetime(time_t t, FILETIME *ft)
525 {
526         long long winTime = t * 10000000LL + 116444736000000000LL;
527         ft->dwLowDateTime = winTime;
528         ft->dwHighDateTime = winTime >> 32;
529 }
530
531 int mingw_utime (const char *file_name, const struct utimbuf *times)
532 {
533         FILETIME mft, aft;
534         int fh, rc;
535
536         /* must have write permission */
537         DWORD attrs = GetFileAttributes(file_name);
538         if (attrs != INVALID_FILE_ATTRIBUTES &&
539             (attrs & FILE_ATTRIBUTE_READONLY)) {
540                 /* ignore errors here; open() will report them */
541                 SetFileAttributes(file_name, attrs & ~FILE_ATTRIBUTE_READONLY);
542         }
543
544         if ((fh = open(file_name, O_RDWR | O_BINARY)) < 0) {
545                 rc = -1;
546                 goto revert_attrs;
547         }
548
549         if (times) {
550                 time_t_to_filetime(times->modtime, &mft);
551                 time_t_to_filetime(times->actime, &aft);
552         } else {
553                 GetSystemTimeAsFileTime(&mft);
554                 aft = mft;
555         }
556         if (!SetFileTime((HANDLE)_get_osfhandle(fh), NULL, &aft, &mft)) {
557                 errno = EINVAL;
558                 rc = -1;
559         } else
560                 rc = 0;
561         close(fh);
562
563 revert_attrs:
564         if (attrs != INVALID_FILE_ATTRIBUTES &&
565             (attrs & FILE_ATTRIBUTE_READONLY)) {
566                 /* ignore errors again */
567                 SetFileAttributes(file_name, attrs);
568         }
569         return rc;
570 }
571
572 unsigned int sleep (unsigned int seconds)
573 {
574         Sleep(seconds*1000);
575         return 0;
576 }
577
578 int mkstemp(char *template)
579 {
580         char *filename = mktemp(template);
581         if (filename == NULL)
582                 return -1;
583         return open(filename, O_RDWR | O_CREAT, 0600);
584 }
585
586 int gettimeofday(struct timeval *tv, void *tz)
587 {
588         FILETIME ft;
589         long long hnsec;
590
591         GetSystemTimeAsFileTime(&ft);
592         hnsec = filetime_to_hnsec(&ft);
593         tv->tv_sec = hnsec / 10000000;
594         tv->tv_usec = (hnsec % 10000000) / 10;
595         return 0;
596 }
597
598 int pipe(int filedes[2])
599 {
600         HANDLE h[2];
601
602         /* this creates non-inheritable handles */
603         if (!CreatePipe(&h[0], &h[1], NULL, 8192)) {
604                 errno = err_win_to_posix(GetLastError());
605                 return -1;
606         }
607         filedes[0] = _open_osfhandle((int)h[0], O_NOINHERIT);
608         if (filedes[0] < 0) {
609                 CloseHandle(h[0]);
610                 CloseHandle(h[1]);
611                 return -1;
612         }
613         filedes[1] = _open_osfhandle((int)h[1], O_NOINHERIT);
614         if (filedes[0] < 0) {
615                 close(filedes[0]);
616                 CloseHandle(h[1]);
617                 return -1;
618         }
619         return 0;
620 }
621
622 struct tm *gmtime_r(const time_t *timep, struct tm *result)
623 {
624         /* gmtime() in MSVCRT.DLL is thread-safe, but not reentrant */
625         memcpy(result, gmtime(timep), sizeof(struct tm));
626         return result;
627 }
628
629 struct tm *localtime_r(const time_t *timep, struct tm *result)
630 {
631         /* localtime() in MSVCRT.DLL is thread-safe, but not reentrant */
632         memcpy(result, localtime(timep), sizeof(struct tm));
633         return result;
634 }
635
636 #undef getcwd
637 char *mingw_getcwd(char *pointer, int len)
638 {
639         int i;
640         char *ret = getcwd(pointer, len);
641         if (!ret)
642                 return ret;
643         for (i = 0; pointer[i]; i++)
644                 if (pointer[i] == '\\')
645                         pointer[i] = '/';
646         return ret;
647 }
648
649 /*
650  * See http://msdn2.microsoft.com/en-us/library/17w5ykft(vs.71).aspx
651  * (Parsing C++ Command-Line Arguments)
652  */
653 static const char *quote_arg(const char *arg)
654 {
655         /* count chars to quote */
656         int len = 0, n = 0;
657         int force_quotes = 0;
658         char *q, *d;
659         const char *p = arg;
660         if (!*p) force_quotes = 1;
661         while (*p) {
662                 if (isspace(*p) || *p == '*' || *p == '?' || *p == '{' || *p == '\'')
663                         force_quotes = 1;
664                 else if (*p == '"')
665                         n++;
666                 else if (*p == '\\') {
667                         int count = 0;
668                         while (*p == '\\') {
669                                 count++;
670                                 p++;
671                                 len++;
672                         }
673                         if (*p == '"')
674                                 n += count*2 + 1;
675                         continue;
676                 }
677                 len++;
678                 p++;
679         }
680         if (!force_quotes && n == 0)
681                 return arg;
682
683         /* insert \ where necessary */
684         d = q = xmalloc(len+n+3);
685         *d++ = '"';
686         while (*arg) {
687                 if (*arg == '"')
688                         *d++ = '\\';
689                 else if (*arg == '\\') {
690                         int count = 0;
691                         while (*arg == '\\') {
692                                 count++;
693                                 *d++ = *arg++;
694                         }
695                         if (*arg == '"') {
696                                 while (count-- > 0)
697                                         *d++ = '\\';
698                                 *d++ = '\\';
699                         }
700                 }
701                 *d++ = *arg++;
702         }
703         *d++ = '"';
704         *d++ = 0;
705         return q;
706 }
707
708 static const char *parse_interpreter(const char *cmd)
709 {
710         static char buf[100];
711         char *p, *opt;
712         int n, fd;
713
714         /* don't even try a .exe */
715         n = strlen(cmd);
716         if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
717                 return NULL;
718
719         fd = open(cmd, O_RDONLY);
720         if (fd < 0)
721                 return NULL;
722         n = read(fd, buf, sizeof(buf)-1);
723         close(fd);
724         if (n < 4)      /* at least '#!/x' and not error */
725                 return NULL;
726
727         if (buf[0] != '#' || buf[1] != '!')
728                 return NULL;
729         buf[n] = '\0';
730         p = buf + strcspn(buf, "\r\n");
731         if (!*p)
732                 return NULL;
733
734         *p = '\0';
735         if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
736                 return NULL;
737         /* strip options */
738         if ((opt = strchr(p+1, ' ')))
739                 *opt = '\0';
740         return p+1;
741 }
742
743 /*
744  * Splits the PATH into parts.
745  */
746 static char **get_path_split(void)
747 {
748         char *p, **path, *envpath = mingw_getenv("PATH");
749         int i, n = 0;
750
751         if (!envpath || !*envpath)
752                 return NULL;
753
754         envpath = xstrdup(envpath);
755         p = envpath;
756         while (p) {
757                 char *dir = p;
758                 p = strchr(p, ';');
759                 if (p) *p++ = '\0';
760                 if (*dir) {     /* not earlier, catches series of ; */
761                         ++n;
762                 }
763         }
764         if (!n)
765                 return NULL;
766
767         path = xmalloc((n+1)*sizeof(char *));
768         p = envpath;
769         i = 0;
770         do {
771                 if (*p)
772                         path[i++] = xstrdup(p);
773                 p = p+strlen(p)+1;
774         } while (i < n);
775         path[i] = NULL;
776
777         free(envpath);
778
779         return path;
780 }
781
782 static void free_path_split(char **path)
783 {
784         char **p = path;
785
786         if (!path)
787                 return;
788
789         while (*p)
790                 free(*p++);
791         free(path);
792 }
793
794 /*
795  * exe_only means that we only want to detect .exe files, but not scripts
796  * (which do not have an extension)
797  */
798 static char *lookup_prog(const char *dir, const char *cmd, int isexe, int exe_only)
799 {
800         char path[MAX_PATH];
801         snprintf(path, sizeof(path), "%s/%s.exe", dir, cmd);
802
803         if (!isexe && access(path, F_OK) == 0)
804                 return xstrdup(path);
805         path[strlen(path)-4] = '\0';
806         if ((!exe_only || isexe) && access(path, F_OK) == 0)
807                 if (!(GetFileAttributes(path) & FILE_ATTRIBUTE_DIRECTORY))
808                         return xstrdup(path);
809         return NULL;
810 }
811
812 /*
813  * Determines the absolute path of cmd using the split path in path.
814  * If cmd contains a slash or backslash, no lookup is performed.
815  */
816 static char *path_lookup(const char *cmd, char **path, int exe_only)
817 {
818         char *prog = NULL;
819         int len = strlen(cmd);
820         int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
821
822         if (strchr(cmd, '/') || strchr(cmd, '\\'))
823                 prog = xstrdup(cmd);
824
825         while (!prog && *path)
826                 prog = lookup_prog(*path++, cmd, isexe, exe_only);
827
828         return prog;
829 }
830
831 static int env_compare(const void *a, const void *b)
832 {
833         char *const *ea = a;
834         char *const *eb = b;
835         return strcasecmp(*ea, *eb);
836 }
837
838 struct pinfo_t {
839         struct pinfo_t *next;
840         pid_t pid;
841         HANDLE proc;
842 } pinfo_t;
843 struct pinfo_t *pinfo = NULL;
844 CRITICAL_SECTION pinfo_cs;
845
846 static pid_t mingw_spawnve_fd(const char *cmd, const char **argv, char **env,
847                               const char *dir,
848                               int prepend_cmd, int fhin, int fhout, int fherr)
849 {
850         STARTUPINFO si;
851         PROCESS_INFORMATION pi;
852         struct strbuf envblk, args;
853         unsigned flags;
854         BOOL ret;
855
856         /* Determine whether or not we are associated to a console */
857         HANDLE cons = CreateFile("CONOUT$", GENERIC_WRITE,
858                         FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
859                         FILE_ATTRIBUTE_NORMAL, NULL);
860         if (cons == INVALID_HANDLE_VALUE) {
861                 /* There is no console associated with this process.
862                  * Since the child is a console process, Windows
863                  * would normally create a console window. But
864                  * since we'll be redirecting std streams, we do
865                  * not need the console.
866                  * It is necessary to use DETACHED_PROCESS
867                  * instead of CREATE_NO_WINDOW to make ssh
868                  * recognize that it has no console.
869                  */
870                 flags = DETACHED_PROCESS;
871         } else {
872                 /* There is already a console. If we specified
873                  * DETACHED_PROCESS here, too, Windows would
874                  * disassociate the child from the console.
875                  * The same is true for CREATE_NO_WINDOW.
876                  * Go figure!
877                  */
878                 flags = 0;
879                 CloseHandle(cons);
880         }
881         memset(&si, 0, sizeof(si));
882         si.cb = sizeof(si);
883         si.dwFlags = STARTF_USESTDHANDLES;
884         si.hStdInput = (HANDLE) _get_osfhandle(fhin);
885         si.hStdOutput = (HANDLE) _get_osfhandle(fhout);
886         si.hStdError = (HANDLE) _get_osfhandle(fherr);
887
888         /* concatenate argv, quoting args as we go */
889         strbuf_init(&args, 0);
890         if (prepend_cmd) {
891                 char *quoted = (char *)quote_arg(cmd);
892                 strbuf_addstr(&args, quoted);
893                 if (quoted != cmd)
894                         free(quoted);
895         }
896         for (; *argv; argv++) {
897                 char *quoted = (char *)quote_arg(*argv);
898                 if (*args.buf)
899                         strbuf_addch(&args, ' ');
900                 strbuf_addstr(&args, quoted);
901                 if (quoted != *argv)
902                         free(quoted);
903         }
904
905         if (env) {
906                 int count = 0;
907                 char **e, **sorted_env;
908
909                 for (e = env; *e; e++)
910                         count++;
911
912                 /* environment must be sorted */
913                 sorted_env = xmalloc(sizeof(*sorted_env) * (count + 1));
914                 memcpy(sorted_env, env, sizeof(*sorted_env) * (count + 1));
915                 qsort(sorted_env, count, sizeof(*sorted_env), env_compare);
916
917                 strbuf_init(&envblk, 0);
918                 for (e = sorted_env; *e; e++) {
919                         strbuf_addstr(&envblk, *e);
920                         strbuf_addch(&envblk, '\0');
921                 }
922                 free(sorted_env);
923         }
924
925         memset(&pi, 0, sizeof(pi));
926         ret = CreateProcess(cmd, args.buf, NULL, NULL, TRUE, flags,
927                 env ? envblk.buf : NULL, dir, &si, &pi);
928
929         if (env)
930                 strbuf_release(&envblk);
931         strbuf_release(&args);
932
933         if (!ret) {
934                 errno = ENOENT;
935                 return -1;
936         }
937         CloseHandle(pi.hThread);
938
939         /*
940          * The process ID is the human-readable identifier of the process
941          * that we want to present in log and error messages. The handle
942          * is not useful for this purpose. But we cannot close it, either,
943          * because it is not possible to turn a process ID into a process
944          * handle after the process terminated.
945          * Keep the handle in a list for waitpid.
946          */
947         EnterCriticalSection(&pinfo_cs);
948         {
949                 struct pinfo_t *info = xmalloc(sizeof(struct pinfo_t));
950                 info->pid = pi.dwProcessId;
951                 info->proc = pi.hProcess;
952                 info->next = pinfo;
953                 pinfo = info;
954         }
955         LeaveCriticalSection(&pinfo_cs);
956
957         return (pid_t)pi.dwProcessId;
958 }
959
960 static pid_t mingw_spawnve(const char *cmd, const char **argv, char **env,
961                            int prepend_cmd)
962 {
963         return mingw_spawnve_fd(cmd, argv, env, NULL, prepend_cmd, 0, 1, 2);
964 }
965
966 pid_t mingw_spawnvpe(const char *cmd, const char **argv, char **env,
967                      const char *dir,
968                      int fhin, int fhout, int fherr)
969 {
970         pid_t pid;
971         char **path = get_path_split();
972         char *prog = path_lookup(cmd, path, 0);
973
974         if (!prog) {
975                 errno = ENOENT;
976                 pid = -1;
977         }
978         else {
979                 const char *interpr = parse_interpreter(prog);
980
981                 if (interpr) {
982                         const char *argv0 = argv[0];
983                         char *iprog = path_lookup(interpr, path, 1);
984                         argv[0] = prog;
985                         if (!iprog) {
986                                 errno = ENOENT;
987                                 pid = -1;
988                         }
989                         else {
990                                 pid = mingw_spawnve_fd(iprog, argv, env, dir, 1,
991                                                        fhin, fhout, fherr);
992                                 free(iprog);
993                         }
994                         argv[0] = argv0;
995                 }
996                 else
997                         pid = mingw_spawnve_fd(prog, argv, env, dir, 0,
998                                                fhin, fhout, fherr);
999                 free(prog);
1000         }
1001         free_path_split(path);
1002         return pid;
1003 }
1004
1005 static int try_shell_exec(const char *cmd, char *const *argv, char **env)
1006 {
1007         const char *interpr = parse_interpreter(cmd);
1008         char **path;
1009         char *prog;
1010         int pid = 0;
1011
1012         if (!interpr)
1013                 return 0;
1014         path = get_path_split();
1015         prog = path_lookup(interpr, path, 1);
1016         if (prog) {
1017                 int argc = 0;
1018                 const char **argv2;
1019                 while (argv[argc]) argc++;
1020                 argv2 = xmalloc(sizeof(*argv) * (argc+1));
1021                 argv2[0] = (char *)cmd; /* full path to the script file */
1022                 memcpy(&argv2[1], &argv[1], sizeof(*argv) * argc);
1023                 pid = mingw_spawnve(prog, argv2, env, 1);
1024                 if (pid >= 0) {
1025                         int status;
1026                         if (waitpid(pid, &status, 0) < 0)
1027                                 status = 255;
1028                         exit(status);
1029                 }
1030                 pid = 1;        /* indicate that we tried but failed */
1031                 free(prog);
1032                 free(argv2);
1033         }
1034         free_path_split(path);
1035         return pid;
1036 }
1037
1038 static void mingw_execve(const char *cmd, char *const *argv, char *const *env)
1039 {
1040         /* check if git_command is a shell script */
1041         if (!try_shell_exec(cmd, argv, (char **)env)) {
1042                 int pid, status;
1043
1044                 pid = mingw_spawnve(cmd, (const char **)argv, (char **)env, 0);
1045                 if (pid < 0)
1046                         return;
1047                 if (waitpid(pid, &status, 0) < 0)
1048                         status = 255;
1049                 exit(status);
1050         }
1051 }
1052
1053 int mingw_execvp(const char *cmd, char *const *argv)
1054 {
1055         char **path = get_path_split();
1056         char *prog = path_lookup(cmd, path, 0);
1057
1058         if (prog) {
1059                 mingw_execve(prog, argv, environ);
1060                 free(prog);
1061         } else
1062                 errno = ENOENT;
1063
1064         free_path_split(path);
1065         return -1;
1066 }
1067
1068 int mingw_execv(const char *cmd, char *const *argv)
1069 {
1070         mingw_execve(cmd, argv, environ);
1071         return -1;
1072 }
1073
1074 int mingw_kill(pid_t pid, int sig)
1075 {
1076         if (pid > 0 && sig == SIGTERM) {
1077                 HANDLE h = OpenProcess(PROCESS_TERMINATE, FALSE, pid);
1078
1079                 if (TerminateProcess(h, -1)) {
1080                         CloseHandle(h);
1081                         return 0;
1082                 }
1083
1084                 errno = err_win_to_posix(GetLastError());
1085                 CloseHandle(h);
1086                 return -1;
1087         }
1088
1089         errno = EINVAL;
1090         return -1;
1091 }
1092
1093 static char **copy_environ(void)
1094 {
1095         char **env;
1096         int i = 0;
1097         while (environ[i])
1098                 i++;
1099         env = xmalloc((i+1)*sizeof(*env));
1100         for (i = 0; environ[i]; i++)
1101                 env[i] = xstrdup(environ[i]);
1102         env[i] = NULL;
1103         return env;
1104 }
1105
1106 void free_environ(char **env)
1107 {
1108         int i;
1109         for (i = 0; env[i]; i++)
1110                 free(env[i]);
1111         free(env);
1112 }
1113
1114 static int lookup_env(char **env, const char *name, size_t nmln)
1115 {
1116         int i;
1117
1118         for (i = 0; env[i]; i++) {
1119                 if (0 == strncmp(env[i], name, nmln)
1120                     && '=' == env[i][nmln])
1121                         /* matches */
1122                         return i;
1123         }
1124         return -1;
1125 }
1126
1127 /*
1128  * If name contains '=', then sets the variable, otherwise it unsets it
1129  */
1130 static char **env_setenv(char **env, const char *name)
1131 {
1132         char *eq = strchrnul(name, '=');
1133         int i = lookup_env(env, name, eq-name);
1134
1135         if (i < 0) {
1136                 if (*eq) {
1137                         for (i = 0; env[i]; i++)
1138                                 ;
1139                         env = xrealloc(env, (i+2)*sizeof(*env));
1140                         env[i] = xstrdup(name);
1141                         env[i+1] = NULL;
1142                 }
1143         }
1144         else {
1145                 free(env[i]);
1146                 if (*eq)
1147                         env[i] = xstrdup(name);
1148                 else
1149                         for (; env[i]; i++)
1150                                 env[i] = env[i+1];
1151         }
1152         return env;
1153 }
1154
1155 /*
1156  * Copies global environ and adjusts variables as specified by vars.
1157  */
1158 char **make_augmented_environ(const char *const *vars)
1159 {
1160         char **env = copy_environ();
1161
1162         while (*vars)
1163                 env = env_setenv(env, *vars++);
1164         return env;
1165 }
1166
1167 #undef getenv
1168
1169 /*
1170  * The system's getenv looks up the name in a case-insensitive manner.
1171  * This version tries a case-sensitive lookup and falls back to
1172  * case-insensitive if nothing was found.  This is necessary because,
1173  * as a prominent example, CMD sets 'Path', but not 'PATH'.
1174  * Warning: not thread-safe.
1175  */
1176 static char *getenv_cs(const char *name)
1177 {
1178         size_t len = strlen(name);
1179         int i = lookup_env(environ, name, len);
1180         if (i >= 0)
1181                 return environ[i] + len + 1;    /* skip past name and '=' */
1182         return getenv(name);
1183 }
1184
1185 char *mingw_getenv(const char *name)
1186 {
1187         char *result = getenv_cs(name);
1188         if (!result && !strcmp(name, "TMPDIR")) {
1189                 /* on Windows it is TMP and TEMP */
1190                 result = getenv_cs("TMP");
1191                 if (!result)
1192                         result = getenv_cs("TEMP");
1193         }
1194         return result;
1195 }
1196
1197 /*
1198  * Note, this isn't a complete replacement for getaddrinfo. It assumes
1199  * that service contains a numerical port, or that it is null. It
1200  * does a simple search using gethostbyname, and returns one IPv4 host
1201  * if one was found.
1202  */
1203 static int WSAAPI getaddrinfo_stub(const char *node, const char *service,
1204                                    const struct addrinfo *hints,
1205                                    struct addrinfo **res)
1206 {
1207         struct hostent *h = NULL;
1208         struct addrinfo *ai;
1209         struct sockaddr_in *sin;
1210
1211         if (node) {
1212                 h = gethostbyname(node);
1213                 if (!h)
1214                         return WSAGetLastError();
1215         }
1216
1217         ai = xmalloc(sizeof(struct addrinfo));
1218         *res = ai;
1219         ai->ai_flags = 0;
1220         ai->ai_family = AF_INET;
1221         ai->ai_socktype = hints ? hints->ai_socktype : 0;
1222         switch (ai->ai_socktype) {
1223         case SOCK_STREAM:
1224                 ai->ai_protocol = IPPROTO_TCP;
1225                 break;
1226         case SOCK_DGRAM:
1227                 ai->ai_protocol = IPPROTO_UDP;
1228                 break;
1229         default:
1230                 ai->ai_protocol = 0;
1231                 break;
1232         }
1233         ai->ai_addrlen = sizeof(struct sockaddr_in);
1234         if (hints && (hints->ai_flags & AI_CANONNAME))
1235                 ai->ai_canonname = h ? xstrdup(h->h_name) : NULL;
1236         else
1237                 ai->ai_canonname = NULL;
1238
1239         sin = xmalloc(ai->ai_addrlen);
1240         memset(sin, 0, ai->ai_addrlen);
1241         sin->sin_family = AF_INET;
1242         /* Note: getaddrinfo is supposed to allow service to be a string,
1243          * which should be looked up using getservbyname. This is
1244          * currently not implemented */
1245         if (service)
1246                 sin->sin_port = htons(atoi(service));
1247         if (h)
1248                 sin->sin_addr = *(struct in_addr *)h->h_addr;
1249         else if (hints && (hints->ai_flags & AI_PASSIVE))
1250                 sin->sin_addr.s_addr = INADDR_ANY;
1251         else
1252                 sin->sin_addr.s_addr = INADDR_LOOPBACK;
1253         ai->ai_addr = (struct sockaddr *)sin;
1254         ai->ai_next = 0;
1255         return 0;
1256 }
1257
1258 static void WSAAPI freeaddrinfo_stub(struct addrinfo *res)
1259 {
1260         free(res->ai_canonname);
1261         free(res->ai_addr);
1262         free(res);
1263 }
1264
1265 static int WSAAPI getnameinfo_stub(const struct sockaddr *sa, socklen_t salen,
1266                                    char *host, DWORD hostlen,
1267                                    char *serv, DWORD servlen, int flags)
1268 {
1269         const struct sockaddr_in *sin = (const struct sockaddr_in *)sa;
1270         if (sa->sa_family != AF_INET)
1271                 return EAI_FAMILY;
1272         if (!host && !serv)
1273                 return EAI_NONAME;
1274
1275         if (host && hostlen > 0) {
1276                 struct hostent *ent = NULL;
1277                 if (!(flags & NI_NUMERICHOST))
1278                         ent = gethostbyaddr((const char *)&sin->sin_addr,
1279                                             sizeof(sin->sin_addr), AF_INET);
1280
1281                 if (ent)
1282                         snprintf(host, hostlen, "%s", ent->h_name);
1283                 else if (flags & NI_NAMEREQD)
1284                         return EAI_NONAME;
1285                 else
1286                         snprintf(host, hostlen, "%s", inet_ntoa(sin->sin_addr));
1287         }
1288
1289         if (serv && servlen > 0) {
1290                 struct servent *ent = NULL;
1291                 if (!(flags & NI_NUMERICSERV))
1292                         ent = getservbyport(sin->sin_port,
1293                                             flags & NI_DGRAM ? "udp" : "tcp");
1294
1295                 if (ent)
1296                         snprintf(serv, servlen, "%s", ent->s_name);
1297                 else
1298                         snprintf(serv, servlen, "%d", ntohs(sin->sin_port));
1299         }
1300
1301         return 0;
1302 }
1303
1304 static HMODULE ipv6_dll = NULL;
1305 static void (WSAAPI *ipv6_freeaddrinfo)(struct addrinfo *res);
1306 static int (WSAAPI *ipv6_getaddrinfo)(const char *node, const char *service,
1307                                       const struct addrinfo *hints,
1308                                       struct addrinfo **res);
1309 static int (WSAAPI *ipv6_getnameinfo)(const struct sockaddr *sa, socklen_t salen,
1310                                       char *host, DWORD hostlen,
1311                                       char *serv, DWORD servlen, int flags);
1312 /*
1313  * gai_strerror is an inline function in the ws2tcpip.h header, so we
1314  * don't need to try to load that one dynamically.
1315  */
1316
1317 static void socket_cleanup(void)
1318 {
1319         WSACleanup();
1320         if (ipv6_dll)
1321                 FreeLibrary(ipv6_dll);
1322         ipv6_dll = NULL;
1323         ipv6_freeaddrinfo = freeaddrinfo_stub;
1324         ipv6_getaddrinfo = getaddrinfo_stub;
1325         ipv6_getnameinfo = getnameinfo_stub;
1326 }
1327
1328 static void ensure_socket_initialization(void)
1329 {
1330         WSADATA wsa;
1331         static int initialized = 0;
1332         const char *libraries[] = { "ws2_32.dll", "wship6.dll", NULL };
1333         const char **name;
1334
1335         if (initialized)
1336                 return;
1337
1338         if (WSAStartup(MAKEWORD(2,2), &wsa))
1339                 die("unable to initialize winsock subsystem, error %d",
1340                         WSAGetLastError());
1341
1342         for (name = libraries; *name; name++) {
1343                 ipv6_dll = LoadLibrary(*name);
1344                 if (!ipv6_dll)
1345                         continue;
1346
1347                 ipv6_freeaddrinfo = (void (WSAAPI *)(struct addrinfo *))
1348                         GetProcAddress(ipv6_dll, "freeaddrinfo");
1349                 ipv6_getaddrinfo = (int (WSAAPI *)(const char *, const char *,
1350                                                    const struct addrinfo *,
1351                                                    struct addrinfo **))
1352                         GetProcAddress(ipv6_dll, "getaddrinfo");
1353                 ipv6_getnameinfo = (int (WSAAPI *)(const struct sockaddr *,
1354                                                    socklen_t, char *, DWORD,
1355                                                    char *, DWORD, int))
1356                         GetProcAddress(ipv6_dll, "getnameinfo");
1357                 if (!ipv6_freeaddrinfo || !ipv6_getaddrinfo || !ipv6_getnameinfo) {
1358                         FreeLibrary(ipv6_dll);
1359                         ipv6_dll = NULL;
1360                 } else
1361                         break;
1362         }
1363         if (!ipv6_freeaddrinfo || !ipv6_getaddrinfo || !ipv6_getnameinfo) {
1364                 ipv6_freeaddrinfo = freeaddrinfo_stub;
1365                 ipv6_getaddrinfo = getaddrinfo_stub;
1366                 ipv6_getnameinfo = getnameinfo_stub;
1367         }
1368
1369         atexit(socket_cleanup);
1370         initialized = 1;
1371 }
1372
1373 #undef gethostname
1374 int mingw_gethostname(char *name, int namelen)
1375 {
1376     ensure_socket_initialization();
1377     return gethostname(name, namelen);
1378 }
1379
1380 #undef gethostbyname
1381 struct hostent *mingw_gethostbyname(const char *host)
1382 {
1383         ensure_socket_initialization();
1384         return gethostbyname(host);
1385 }
1386
1387 void mingw_freeaddrinfo(struct addrinfo *res)
1388 {
1389         ipv6_freeaddrinfo(res);
1390 }
1391
1392 int mingw_getaddrinfo(const char *node, const char *service,
1393                       const struct addrinfo *hints, struct addrinfo **res)
1394 {
1395         ensure_socket_initialization();
1396         return ipv6_getaddrinfo(node, service, hints, res);
1397 }
1398
1399 int mingw_getnameinfo(const struct sockaddr *sa, socklen_t salen,
1400                       char *host, DWORD hostlen, char *serv, DWORD servlen,
1401                       int flags)
1402 {
1403         ensure_socket_initialization();
1404         return ipv6_getnameinfo(sa, salen, host, hostlen, serv, servlen, flags);
1405 }
1406
1407 int mingw_socket(int domain, int type, int protocol)
1408 {
1409         int sockfd;
1410         SOCKET s;
1411
1412         ensure_socket_initialization();
1413         s = WSASocket(domain, type, protocol, NULL, 0, 0);
1414         if (s == INVALID_SOCKET) {
1415                 /*
1416                  * WSAGetLastError() values are regular BSD error codes
1417                  * biased by WSABASEERR.
1418                  * However, strerror() does not know about networking
1419                  * specific errors, which are values beginning at 38 or so.
1420                  * Therefore, we choose to leave the biased error code
1421                  * in errno so that _if_ someone looks up the code somewhere,
1422                  * then it is at least the number that are usually listed.
1423                  */
1424                 errno = WSAGetLastError();
1425                 return -1;
1426         }
1427         /* convert into a file descriptor */
1428         if ((sockfd = _open_osfhandle(s, O_RDWR|O_BINARY)) < 0) {
1429                 closesocket(s);
1430                 return error("unable to make a socket file descriptor: %s",
1431                         strerror(errno));
1432         }
1433         return sockfd;
1434 }
1435
1436 #undef connect
1437 int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz)
1438 {
1439         SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1440         return connect(s, sa, sz);
1441 }
1442
1443 #undef bind
1444 int mingw_bind(int sockfd, struct sockaddr *sa, size_t sz)
1445 {
1446         SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1447         return bind(s, sa, sz);
1448 }
1449
1450 #undef setsockopt
1451 int mingw_setsockopt(int sockfd, int lvl, int optname, void *optval, int optlen)
1452 {
1453         SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1454         return setsockopt(s, lvl, optname, (const char*)optval, optlen);
1455 }
1456
1457 #undef shutdown
1458 int mingw_shutdown(int sockfd, int how)
1459 {
1460         SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1461         return shutdown(s, how);
1462 }
1463
1464 #undef listen
1465 int mingw_listen(int sockfd, int backlog)
1466 {
1467         SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1468         return listen(s, backlog);
1469 }
1470
1471 #undef accept
1472 int mingw_accept(int sockfd1, struct sockaddr *sa, socklen_t *sz)
1473 {
1474         int sockfd2;
1475
1476         SOCKET s1 = (SOCKET)_get_osfhandle(sockfd1);
1477         SOCKET s2 = accept(s1, sa, sz);
1478
1479         /* convert into a file descriptor */
1480         if ((sockfd2 = _open_osfhandle(s2, O_RDWR|O_BINARY)) < 0) {
1481                 int err = errno;
1482                 closesocket(s2);
1483                 return error("unable to make a socket file descriptor: %s",
1484                         strerror(err));
1485         }
1486         return sockfd2;
1487 }
1488
1489 #undef rename
1490 int mingw_rename(const char *pold, const char *pnew)
1491 {
1492         DWORD attrs, gle;
1493         int tries = 0;
1494
1495         /*
1496          * Try native rename() first to get errno right.
1497          * It is based on MoveFile(), which cannot overwrite existing files.
1498          */
1499         if (!rename(pold, pnew))
1500                 return 0;
1501         if (errno != EEXIST)
1502                 return -1;
1503 repeat:
1504         if (MoveFileEx(pold, pnew, MOVEFILE_REPLACE_EXISTING))
1505                 return 0;
1506         /* TODO: translate more errors */
1507         gle = GetLastError();
1508         if (gle == ERROR_ACCESS_DENIED &&
1509             (attrs = GetFileAttributes(pnew)) != INVALID_FILE_ATTRIBUTES) {
1510                 if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
1511                         errno = EISDIR;
1512                         return -1;
1513                 }
1514                 if ((attrs & FILE_ATTRIBUTE_READONLY) &&
1515                     SetFileAttributes(pnew, attrs & ~FILE_ATTRIBUTE_READONLY)) {
1516                         if (MoveFileEx(pold, pnew, MOVEFILE_REPLACE_EXISTING))
1517                                 return 0;
1518                         gle = GetLastError();
1519                         /* revert file attributes on failure */
1520                         SetFileAttributes(pnew, attrs);
1521                 }
1522         }
1523         if (tries < ARRAY_SIZE(delay) && gle == ERROR_ACCESS_DENIED) {
1524                 /*
1525                  * We assume that some other process had the source or
1526                  * destination file open at the wrong moment and retry.
1527                  * In order to give the other process a higher chance to
1528                  * complete its operation, we give up our time slice now.
1529                  * If we have to retry again, we do sleep a bit.
1530                  */
1531                 Sleep(delay[tries]);
1532                 tries++;
1533                 goto repeat;
1534         }
1535         if (gle == ERROR_ACCESS_DENIED &&
1536                ask_yes_no_if_possible("Rename from '%s' to '%s' failed. "
1537                        "Should I try again?", pold, pnew))
1538                 goto repeat;
1539
1540         errno = EACCES;
1541         return -1;
1542 }
1543
1544 /*
1545  * Note that this doesn't return the actual pagesize, but
1546  * the allocation granularity. If future Windows specific git code
1547  * needs the real getpagesize function, we need to find another solution.
1548  */
1549 int mingw_getpagesize(void)
1550 {
1551         SYSTEM_INFO si;
1552         GetSystemInfo(&si);
1553         return si.dwAllocationGranularity;
1554 }
1555
1556 struct passwd *getpwuid(int uid)
1557 {
1558         static char user_name[100];
1559         static struct passwd p;
1560
1561         DWORD len = sizeof(user_name);
1562         if (!GetUserName(user_name, &len))
1563                 return NULL;
1564         p.pw_name = user_name;
1565         p.pw_gecos = "unknown";
1566         p.pw_dir = NULL;
1567         return &p;
1568 }
1569
1570 static HANDLE timer_event;
1571 static HANDLE timer_thread;
1572 static int timer_interval;
1573 static int one_shot;
1574 static sig_handler_t timer_fn = SIG_DFL, sigint_fn = SIG_DFL;
1575
1576 /* The timer works like this:
1577  * The thread, ticktack(), is a trivial routine that most of the time
1578  * only waits to receive the signal to terminate. The main thread tells
1579  * the thread to terminate by setting the timer_event to the signalled
1580  * state.
1581  * But ticktack() interrupts the wait state after the timer's interval
1582  * length to call the signal handler.
1583  */
1584
1585 static unsigned __stdcall ticktack(void *dummy)
1586 {
1587         while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
1588                 mingw_raise(SIGALRM);
1589                 if (one_shot)
1590                         break;
1591         }
1592         return 0;
1593 }
1594
1595 static int start_timer_thread(void)
1596 {
1597         timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
1598         if (timer_event) {
1599                 timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
1600                 if (!timer_thread )
1601                         return errno = ENOMEM,
1602                                 error("cannot start timer thread");
1603         } else
1604                 return errno = ENOMEM,
1605                         error("cannot allocate resources for timer");
1606         return 0;
1607 }
1608
1609 static void stop_timer_thread(void)
1610 {
1611         if (timer_event)
1612                 SetEvent(timer_event);  /* tell thread to terminate */
1613         if (timer_thread) {
1614                 int rc = WaitForSingleObject(timer_thread, 1000);
1615                 if (rc == WAIT_TIMEOUT)
1616                         error("timer thread did not terminate timely");
1617                 else if (rc != WAIT_OBJECT_0)
1618                         error("waiting for timer thread failed: %lu",
1619                               GetLastError());
1620                 CloseHandle(timer_thread);
1621         }
1622         if (timer_event)
1623                 CloseHandle(timer_event);
1624         timer_event = NULL;
1625         timer_thread = NULL;
1626 }
1627
1628 static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
1629 {
1630         return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
1631 }
1632
1633 int setitimer(int type, struct itimerval *in, struct itimerval *out)
1634 {
1635         static const struct timeval zero;
1636         static int atexit_done;
1637
1638         if (out != NULL)
1639                 return errno = EINVAL,
1640                         error("setitimer param 3 != NULL not implemented");
1641         if (!is_timeval_eq(&in->it_interval, &zero) &&
1642             !is_timeval_eq(&in->it_interval, &in->it_value))
1643                 return errno = EINVAL,
1644                         error("setitimer: it_interval must be zero or eq it_value");
1645
1646         if (timer_thread)
1647                 stop_timer_thread();
1648
1649         if (is_timeval_eq(&in->it_value, &zero) &&
1650             is_timeval_eq(&in->it_interval, &zero))
1651                 return 0;
1652
1653         timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000;
1654         one_shot = is_timeval_eq(&in->it_interval, &zero);
1655         if (!atexit_done) {
1656                 atexit(stop_timer_thread);
1657                 atexit_done = 1;
1658         }
1659         return start_timer_thread();
1660 }
1661
1662 int sigaction(int sig, struct sigaction *in, struct sigaction *out)
1663 {
1664         if (sig != SIGALRM)
1665                 return errno = EINVAL,
1666                         error("sigaction only implemented for SIGALRM");
1667         if (out != NULL)
1668                 return errno = EINVAL,
1669                         error("sigaction: param 3 != NULL not implemented");
1670
1671         timer_fn = in->sa_handler;
1672         return 0;
1673 }
1674
1675 #undef signal
1676 sig_handler_t mingw_signal(int sig, sig_handler_t handler)
1677 {
1678         sig_handler_t old = timer_fn;
1679
1680         switch (sig) {
1681         case SIGALRM:
1682                 timer_fn = handler;
1683                 break;
1684
1685         case SIGINT:
1686                 sigint_fn = handler;
1687                 break;
1688
1689         default:
1690                 return signal(sig, handler);
1691         }
1692
1693         return old;
1694 }
1695
1696 #undef raise
1697 int mingw_raise(int sig)
1698 {
1699         switch (sig) {
1700         case SIGALRM:
1701                 if (timer_fn == SIG_DFL) {
1702                         if (isatty(STDERR_FILENO))
1703                                 fputs("Alarm clock\n", stderr);
1704                         exit(128 + SIGALRM);
1705                 } else if (timer_fn != SIG_IGN)
1706                         timer_fn(SIGALRM);
1707                 return 0;
1708
1709         case SIGINT:
1710                 if (sigint_fn == SIG_DFL)
1711                         exit(128 + SIGINT);
1712                 else if (sigint_fn != SIG_IGN)
1713                         sigint_fn(SIGINT);
1714                 return 0;
1715
1716         default:
1717                 return raise(sig);
1718         }
1719 }
1720
1721
1722 static const char *make_backslash_path(const char *path)
1723 {
1724         static char buf[PATH_MAX + 1];
1725         char *c;
1726
1727         if (strlcpy(buf, path, PATH_MAX) >= PATH_MAX)
1728                 die("Too long path: %.*s", 60, path);
1729
1730         for (c = buf; *c; c++) {
1731                 if (*c == '/')
1732                         *c = '\\';
1733         }
1734         return buf;
1735 }
1736
1737 void mingw_open_html(const char *unixpath)
1738 {
1739         const char *htmlpath = make_backslash_path(unixpath);
1740         typedef HINSTANCE (WINAPI *T)(HWND, const char *,
1741                         const char *, const char *, const char *, INT);
1742         T ShellExecute;
1743         HMODULE shell32;
1744         int r;
1745
1746         shell32 = LoadLibrary("shell32.dll");
1747         if (!shell32)
1748                 die("cannot load shell32.dll");
1749         ShellExecute = (T)GetProcAddress(shell32, "ShellExecuteA");
1750         if (!ShellExecute)
1751                 die("cannot run browser");
1752
1753         printf("Launching default browser to display HTML ...\n");
1754         r = (int)ShellExecute(NULL, "open", htmlpath, NULL, "\\", SW_SHOWNORMAL);
1755         FreeLibrary(shell32);
1756         /* see the MSDN documentation referring to the result codes here */
1757         if (r <= 32) {
1758                 die("failed to launch browser for %.*s", MAX_PATH, unixpath);
1759         }
1760 }
1761
1762 int link(const char *oldpath, const char *newpath)
1763 {
1764         typedef BOOL (WINAPI *T)(const char*, const char*, LPSECURITY_ATTRIBUTES);
1765         static T create_hard_link = NULL;
1766         if (!create_hard_link) {
1767                 create_hard_link = (T) GetProcAddress(
1768                         GetModuleHandle("kernel32.dll"), "CreateHardLinkA");
1769                 if (!create_hard_link)
1770                         create_hard_link = (T)-1;
1771         }
1772         if (create_hard_link == (T)-1) {
1773                 errno = ENOSYS;
1774                 return -1;
1775         }
1776         if (!create_hard_link(newpath, oldpath, NULL)) {
1777                 errno = err_win_to_posix(GetLastError());
1778                 return -1;
1779         }
1780         return 0;
1781 }
1782
1783 char *getpass(const char *prompt)
1784 {
1785         struct strbuf buf = STRBUF_INIT;
1786
1787         fputs(prompt, stderr);
1788         for (;;) {
1789                 char c = _getch();
1790                 if (c == '\r' || c == '\n')
1791                         break;
1792                 strbuf_addch(&buf, c);
1793         }
1794         fputs("\n", stderr);
1795         return strbuf_detach(&buf, NULL);
1796 }
1797
1798 pid_t waitpid(pid_t pid, int *status, int options)
1799 {
1800         HANDLE h = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION,
1801             FALSE, pid);
1802         if (!h) {
1803                 errno = ECHILD;
1804                 return -1;
1805         }
1806
1807         if (pid > 0 && options & WNOHANG) {
1808                 if (WAIT_OBJECT_0 != WaitForSingleObject(h, 0)) {
1809                         CloseHandle(h);
1810                         return 0;
1811                 }
1812                 options &= ~WNOHANG;
1813         }
1814
1815         if (options == 0) {
1816                 struct pinfo_t **ppinfo;
1817                 if (WaitForSingleObject(h, INFINITE) != WAIT_OBJECT_0) {
1818                         CloseHandle(h);
1819                         return 0;
1820                 }
1821
1822                 if (status)
1823                         GetExitCodeProcess(h, (LPDWORD)status);
1824
1825                 EnterCriticalSection(&pinfo_cs);
1826
1827                 ppinfo = &pinfo;
1828                 while (*ppinfo) {
1829                         struct pinfo_t *info = *ppinfo;
1830                         if (info->pid == pid) {
1831                                 CloseHandle(info->proc);
1832                                 *ppinfo = info->next;
1833                                 free(info);
1834                                 break;
1835                         }
1836                         ppinfo = &info->next;
1837                 }
1838
1839                 LeaveCriticalSection(&pinfo_cs);
1840
1841                 CloseHandle(h);
1842                 return pid;
1843         }
1844         CloseHandle(h);
1845
1846         errno = EINVAL;
1847         return -1;
1848 }