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