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