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