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