compat / mingw.con commit Merge branch 'js/send-email' (2fb9c42)
   1#include "../git-compat-util.h"
   2#include "win32.h"
   3#include "../strbuf.h"
   4
   5unsigned int _CRT_fmode = _O_BINARY;
   6
   7#undef open
   8int mingw_open (const char *filename, int oflags, ...)
   9{
  10        va_list args;
  11        unsigned mode;
  12        va_start(args, oflags);
  13        mode = va_arg(args, int);
  14        va_end(args);
  15
  16        if (!strcmp(filename, "/dev/null"))
  17                filename = "nul";
  18        int fd = open(filename, oflags, mode);
  19        if (fd < 0 && (oflags & O_CREAT) && errno == EACCES) {
  20                DWORD attrs = GetFileAttributes(filename);
  21                if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY))
  22                        errno = EISDIR;
  23        }
  24        return fd;
  25}
  26
  27static inline time_t filetime_to_time_t(const FILETIME *ft)
  28{
  29        long long winTime = ((long long)ft->dwHighDateTime << 32) + ft->dwLowDateTime;
  30        winTime -= 116444736000000000LL; /* Windows to Unix Epoch conversion */
  31        winTime /= 10000000;             /* Nano to seconds resolution */
  32        return (time_t)winTime;
  33}
  34
  35/* We keep the do_lstat code in a separate function to avoid recursion.
  36 * When a path ends with a slash, the stat will fail with ENOENT. In
  37 * this case, we strip the trailing slashes and stat again.
  38 */
  39static int do_lstat(const char *file_name, struct stat *buf)
  40{
  41        WIN32_FILE_ATTRIBUTE_DATA fdata;
  42
  43        if (!(errno = get_file_attr(file_name, &fdata))) {
  44                buf->st_ino = 0;
  45                buf->st_gid = 0;
  46                buf->st_uid = 0;
  47                buf->st_nlink = 1;
  48                buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
  49                buf->st_size = fdata.nFileSizeLow |
  50                        (((off_t)fdata.nFileSizeHigh)<<32);
  51                buf->st_dev = buf->st_rdev = 0; /* not used by Git */
  52                buf->st_atime = filetime_to_time_t(&(fdata.ftLastAccessTime));
  53                buf->st_mtime = filetime_to_time_t(&(fdata.ftLastWriteTime));
  54                buf->st_ctime = filetime_to_time_t(&(fdata.ftCreationTime));
  55                return 0;
  56        }
  57        return -1;
  58}
  59
  60/* We provide our own lstat/fstat functions, since the provided
  61 * lstat/fstat functions are so slow. These stat functions are
  62 * tailored for Git's usage (read: fast), and are not meant to be
  63 * complete. Note that Git stat()s are redirected to mingw_lstat()
  64 * too, since Windows doesn't really handle symlinks that well.
  65 */
  66int mingw_lstat(const char *file_name, struct stat *buf)
  67{
  68        int namelen;
  69        static char alt_name[PATH_MAX];
  70
  71        if (!do_lstat(file_name, buf))
  72                return 0;
  73
  74        /* if file_name ended in a '/', Windows returned ENOENT;
  75         * try again without trailing slashes
  76         */
  77        if (errno != ENOENT)
  78                return -1;
  79
  80        namelen = strlen(file_name);
  81        if (namelen && file_name[namelen-1] != '/')
  82                return -1;
  83        while (namelen && file_name[namelen-1] == '/')
  84                --namelen;
  85        if (!namelen || namelen >= PATH_MAX)
  86                return -1;
  87
  88        memcpy(alt_name, file_name, namelen);
  89        alt_name[namelen] = 0;
  90        return do_lstat(alt_name, buf);
  91}
  92
  93#undef fstat
  94int mingw_fstat(int fd, struct stat *buf)
  95{
  96        HANDLE fh = (HANDLE)_get_osfhandle(fd);
  97        BY_HANDLE_FILE_INFORMATION fdata;
  98
  99        if (fh == INVALID_HANDLE_VALUE) {
 100                errno = EBADF;
 101                return -1;
 102        }
 103        /* direct non-file handles to MS's fstat() */
 104        if (GetFileType(fh) != FILE_TYPE_DISK)
 105                return _fstati64(fd, buf);
 106
 107        if (GetFileInformationByHandle(fh, &fdata)) {
 108                buf->st_ino = 0;
 109                buf->st_gid = 0;
 110                buf->st_uid = 0;
 111                buf->st_nlink = 1;
 112                buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
 113                buf->st_size = fdata.nFileSizeLow |
 114                        (((off_t)fdata.nFileSizeHigh)<<32);
 115                buf->st_dev = buf->st_rdev = 0; /* not used by Git */
 116                buf->st_atime = filetime_to_time_t(&(fdata.ftLastAccessTime));
 117                buf->st_mtime = filetime_to_time_t(&(fdata.ftLastWriteTime));
 118                buf->st_ctime = filetime_to_time_t(&(fdata.ftCreationTime));
 119                return 0;
 120        }
 121        errno = EBADF;
 122        return -1;
 123}
 124
 125static inline void time_t_to_filetime(time_t t, FILETIME *ft)
 126{
 127        long long winTime = t * 10000000LL + 116444736000000000LL;
 128        ft->dwLowDateTime = winTime;
 129        ft->dwHighDateTime = winTime >> 32;
 130}
 131
 132int mingw_utime (const char *file_name, const struct utimbuf *times)
 133{
 134        FILETIME mft, aft;
 135        int fh, rc;
 136
 137        /* must have write permission */
 138        if ((fh = open(file_name, O_RDWR | O_BINARY)) < 0)
 139                return -1;
 140
 141        time_t_to_filetime(times->modtime, &mft);
 142        time_t_to_filetime(times->actime, &aft);
 143        if (!SetFileTime((HANDLE)_get_osfhandle(fh), NULL, &aft, &mft)) {
 144                errno = EINVAL;
 145                rc = -1;
 146        } else
 147                rc = 0;
 148        close(fh);
 149        return rc;
 150}
 151
 152unsigned int sleep (unsigned int seconds)
 153{
 154        Sleep(seconds*1000);
 155        return 0;
 156}
 157
 158int mkstemp(char *template)
 159{
 160        char *filename = mktemp(template);
 161        if (filename == NULL)
 162                return -1;
 163        return open(filename, O_RDWR | O_CREAT, 0600);
 164}
 165
 166int gettimeofday(struct timeval *tv, void *tz)
 167{
 168        SYSTEMTIME st;
 169        struct tm tm;
 170        GetSystemTime(&st);
 171        tm.tm_year = st.wYear-1900;
 172        tm.tm_mon = st.wMonth-1;
 173        tm.tm_mday = st.wDay;
 174        tm.tm_hour = st.wHour;
 175        tm.tm_min = st.wMinute;
 176        tm.tm_sec = st.wSecond;
 177        tv->tv_sec = tm_to_time_t(&tm);
 178        if (tv->tv_sec < 0)
 179                return -1;
 180        tv->tv_usec = st.wMilliseconds*1000;
 181        return 0;
 182}
 183
 184int pipe(int filedes[2])
 185{
 186        int fd;
 187        HANDLE h[2], parent;
 188
 189        if (_pipe(filedes, 8192, 0) < 0)
 190                return -1;
 191
 192        parent = GetCurrentProcess();
 193
 194        if (!DuplicateHandle (parent, (HANDLE)_get_osfhandle(filedes[0]),
 195                        parent, &h[0], 0, FALSE, DUPLICATE_SAME_ACCESS)) {
 196                close(filedes[0]);
 197                close(filedes[1]);
 198                return -1;
 199        }
 200        if (!DuplicateHandle (parent, (HANDLE)_get_osfhandle(filedes[1]),
 201                        parent, &h[1], 0, FALSE, DUPLICATE_SAME_ACCESS)) {
 202                close(filedes[0]);
 203                close(filedes[1]);
 204                CloseHandle(h[0]);
 205                return -1;
 206        }
 207        fd = _open_osfhandle((int)h[0], O_NOINHERIT);
 208        if (fd < 0) {
 209                close(filedes[0]);
 210                close(filedes[1]);
 211                CloseHandle(h[0]);
 212                CloseHandle(h[1]);
 213                return -1;
 214        }
 215        close(filedes[0]);
 216        filedes[0] = fd;
 217        fd = _open_osfhandle((int)h[1], O_NOINHERIT);
 218        if (fd < 0) {
 219                close(filedes[0]);
 220                close(filedes[1]);
 221                CloseHandle(h[1]);
 222                return -1;
 223        }
 224        close(filedes[1]);
 225        filedes[1] = fd;
 226        return 0;
 227}
 228
 229int poll(struct pollfd *ufds, unsigned int nfds, int timeout)
 230{
 231        int i, pending;
 232
 233        if (timeout >= 0) {
 234                if (nfds == 0) {
 235                        Sleep(timeout);
 236                        return 0;
 237                }
 238                return errno = EINVAL, error("poll timeout not supported");
 239        }
 240
 241        /* When there is only one fd to wait for, then we pretend that
 242         * input is available and let the actual wait happen when the
 243         * caller invokes read().
 244         */
 245        if (nfds == 1) {
 246                if (!(ufds[0].events & POLLIN))
 247                        return errno = EINVAL, error("POLLIN not set");
 248                ufds[0].revents = POLLIN;
 249                return 0;
 250        }
 251
 252repeat:
 253        pending = 0;
 254        for (i = 0; i < nfds; i++) {
 255                DWORD avail = 0;
 256                HANDLE h = (HANDLE) _get_osfhandle(ufds[i].fd);
 257                if (h == INVALID_HANDLE_VALUE)
 258                        return -1;      /* errno was set */
 259
 260                if (!(ufds[i].events & POLLIN))
 261                        return errno = EINVAL, error("POLLIN not set");
 262
 263                /* this emulation works only for pipes */
 264                if (!PeekNamedPipe(h, NULL, 0, NULL, &avail, NULL)) {
 265                        int err = GetLastError();
 266                        if (err == ERROR_BROKEN_PIPE) {
 267                                ufds[i].revents = POLLHUP;
 268                                pending++;
 269                        } else {
 270                                errno = EINVAL;
 271                                return error("PeekNamedPipe failed,"
 272                                        " GetLastError: %u", err);
 273                        }
 274                } else if (avail) {
 275                        ufds[i].revents = POLLIN;
 276                        pending++;
 277                } else
 278                        ufds[i].revents = 0;
 279        }
 280        if (!pending) {
 281                /* The only times that we spin here is when the process
 282                 * that is connected through the pipes is waiting for
 283                 * its own input data to become available. But since
 284                 * the process (pack-objects) is itself CPU intensive,
 285                 * it will happily pick up the time slice that we are
 286                 * relinguishing here.
 287                 */
 288                Sleep(0);
 289                goto repeat;
 290        }
 291        return 0;
 292}
 293
 294struct tm *gmtime_r(const time_t *timep, struct tm *result)
 295{
 296        /* gmtime() in MSVCRT.DLL is thread-safe, but not reentrant */
 297        memcpy(result, gmtime(timep), sizeof(struct tm));
 298        return result;
 299}
 300
 301struct tm *localtime_r(const time_t *timep, struct tm *result)
 302{
 303        /* localtime() in MSVCRT.DLL is thread-safe, but not reentrant */
 304        memcpy(result, localtime(timep), sizeof(struct tm));
 305        return result;
 306}
 307
 308#undef getcwd
 309char *mingw_getcwd(char *pointer, int len)
 310{
 311        int i;
 312        char *ret = getcwd(pointer, len);
 313        if (!ret)
 314                return ret;
 315        for (i = 0; pointer[i]; i++)
 316                if (pointer[i] == '\\')
 317                        pointer[i] = '/';
 318        return ret;
 319}
 320
 321#undef getenv
 322char *mingw_getenv(const char *name)
 323{
 324        char *result = getenv(name);
 325        if (!result && !strcmp(name, "TMPDIR")) {
 326                /* on Windows it is TMP and TEMP */
 327                result = getenv("TMP");
 328                if (!result)
 329                        result = getenv("TEMP");
 330        }
 331        return result;
 332}
 333
 334/*
 335 * See http://msdn2.microsoft.com/en-us/library/17w5ykft(vs.71).aspx
 336 * (Parsing C++ Command-Line Arguments)
 337 */
 338static const char *quote_arg(const char *arg)
 339{
 340        /* count chars to quote */
 341        int len = 0, n = 0;
 342        int force_quotes = 0;
 343        char *q, *d;
 344        const char *p = arg;
 345        if (!*p) force_quotes = 1;
 346        while (*p) {
 347                if (isspace(*p) || *p == '*' || *p == '?' || *p == '{')
 348                        force_quotes = 1;
 349                else if (*p == '"')
 350                        n++;
 351                else if (*p == '\\') {
 352                        int count = 0;
 353                        while (*p == '\\') {
 354                                count++;
 355                                p++;
 356                                len++;
 357                        }
 358                        if (*p == '"')
 359                                n += count*2 + 1;
 360                        continue;
 361                }
 362                len++;
 363                p++;
 364        }
 365        if (!force_quotes && n == 0)
 366                return arg;
 367
 368        /* insert \ where necessary */
 369        d = q = xmalloc(len+n+3);
 370        *d++ = '"';
 371        while (*arg) {
 372                if (*arg == '"')
 373                        *d++ = '\\';
 374                else if (*arg == '\\') {
 375                        int count = 0;
 376                        while (*arg == '\\') {
 377                                count++;
 378                                *d++ = *arg++;
 379                        }
 380                        if (*arg == '"') {
 381                                while (count-- > 0)
 382                                        *d++ = '\\';
 383                                *d++ = '\\';
 384                        }
 385                }
 386                *d++ = *arg++;
 387        }
 388        *d++ = '"';
 389        *d++ = 0;
 390        return q;
 391}
 392
 393static const char *parse_interpreter(const char *cmd)
 394{
 395        static char buf[100];
 396        char *p, *opt;
 397        int n, fd;
 398
 399        /* don't even try a .exe */
 400        n = strlen(cmd);
 401        if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
 402                return NULL;
 403
 404        fd = open(cmd, O_RDONLY);
 405        if (fd < 0)
 406                return NULL;
 407        n = read(fd, buf, sizeof(buf)-1);
 408        close(fd);
 409        if (n < 4)      /* at least '#!/x' and not error */
 410                return NULL;
 411
 412        if (buf[0] != '#' || buf[1] != '!')
 413                return NULL;
 414        buf[n] = '\0';
 415        p = strchr(buf, '\n');
 416        if (!p)
 417                return NULL;
 418
 419        *p = '\0';
 420        if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
 421                return NULL;
 422        /* strip options */
 423        if ((opt = strchr(p+1, ' ')))
 424                *opt = '\0';
 425        return p+1;
 426}
 427
 428/*
 429 * Splits the PATH into parts.
 430 */
 431static char **get_path_split(void)
 432{
 433        char *p, **path, *envpath = getenv("PATH");
 434        int i, n = 0;
 435
 436        if (!envpath || !*envpath)
 437                return NULL;
 438
 439        envpath = xstrdup(envpath);
 440        p = envpath;
 441        while (p) {
 442                char *dir = p;
 443                p = strchr(p, ';');
 444                if (p) *p++ = '\0';
 445                if (*dir) {     /* not earlier, catches series of ; */
 446                        ++n;
 447                }
 448        }
 449        if (!n)
 450                return NULL;
 451
 452        path = xmalloc((n+1)*sizeof(char*));
 453        p = envpath;
 454        i = 0;
 455        do {
 456                if (*p)
 457                        path[i++] = xstrdup(p);
 458                p = p+strlen(p)+1;
 459        } while (i < n);
 460        path[i] = NULL;
 461
 462        free(envpath);
 463
 464        return path;
 465}
 466
 467static void free_path_split(char **path)
 468{
 469        if (!path)
 470                return;
 471
 472        char **p = path;
 473        while (*p)
 474                free(*p++);
 475        free(path);
 476}
 477
 478/*
 479 * exe_only means that we only want to detect .exe files, but not scripts
 480 * (which do not have an extension)
 481 */
 482static char *lookup_prog(const char *dir, const char *cmd, int isexe, int exe_only)
 483{
 484        char path[MAX_PATH];
 485        snprintf(path, sizeof(path), "%s/%s.exe", dir, cmd);
 486
 487        if (!isexe && access(path, F_OK) == 0)
 488                return xstrdup(path);
 489        path[strlen(path)-4] = '\0';
 490        if ((!exe_only || isexe) && access(path, F_OK) == 0)
 491                if (!(GetFileAttributes(path) & FILE_ATTRIBUTE_DIRECTORY))
 492                        return xstrdup(path);
 493        return NULL;
 494}
 495
 496/*
 497 * Determines the absolute path of cmd using the the split path in path.
 498 * If cmd contains a slash or backslash, no lookup is performed.
 499 */
 500static char *path_lookup(const char *cmd, char **path, int exe_only)
 501{
 502        char *prog = NULL;
 503        int len = strlen(cmd);
 504        int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
 505
 506        if (strchr(cmd, '/') || strchr(cmd, '\\'))
 507                prog = xstrdup(cmd);
 508
 509        while (!prog && *path)
 510                prog = lookup_prog(*path++, cmd, isexe, exe_only);
 511
 512        return prog;
 513}
 514
 515static int env_compare(const void *a, const void *b)
 516{
 517        char *const *ea = a;
 518        char *const *eb = b;
 519        return strcasecmp(*ea, *eb);
 520}
 521
 522static pid_t mingw_spawnve(const char *cmd, const char **argv, char **env,
 523                           int prepend_cmd)
 524{
 525        STARTUPINFO si;
 526        PROCESS_INFORMATION pi;
 527        struct strbuf envblk, args;
 528        unsigned flags;
 529        BOOL ret;
 530
 531        /* Determine whether or not we are associated to a console */
 532        HANDLE cons = CreateFile("CONOUT$", GENERIC_WRITE,
 533                        FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
 534                        FILE_ATTRIBUTE_NORMAL, NULL);
 535        if (cons == INVALID_HANDLE_VALUE) {
 536                /* There is no console associated with this process.
 537                 * Since the child is a console process, Windows
 538                 * would normally create a console window. But
 539                 * since we'll be redirecting std streams, we do
 540                 * not need the console.
 541                 * It is necessary to use DETACHED_PROCESS
 542                 * instead of CREATE_NO_WINDOW to make ssh
 543                 * recognize that it has no console.
 544                 */
 545                flags = DETACHED_PROCESS;
 546        } else {
 547                /* There is already a console. If we specified
 548                 * DETACHED_PROCESS here, too, Windows would
 549                 * disassociate the child from the console.
 550                 * The same is true for CREATE_NO_WINDOW.
 551                 * Go figure!
 552                 */
 553                flags = 0;
 554                CloseHandle(cons);
 555        }
 556        memset(&si, 0, sizeof(si));
 557        si.cb = sizeof(si);
 558        si.dwFlags = STARTF_USESTDHANDLES;
 559        si.hStdInput = (HANDLE) _get_osfhandle(0);
 560        si.hStdOutput = (HANDLE) _get_osfhandle(1);
 561        si.hStdError = (HANDLE) _get_osfhandle(2);
 562
 563        /* concatenate argv, quoting args as we go */
 564        strbuf_init(&args, 0);
 565        if (prepend_cmd) {
 566                char *quoted = (char *)quote_arg(cmd);
 567                strbuf_addstr(&args, quoted);
 568                if (quoted != cmd)
 569                        free(quoted);
 570        }
 571        for (; *argv; argv++) {
 572                char *quoted = (char *)quote_arg(*argv);
 573                if (*args.buf)
 574                        strbuf_addch(&args, ' ');
 575                strbuf_addstr(&args, quoted);
 576                if (quoted != *argv)
 577                        free(quoted);
 578        }
 579
 580        if (env) {
 581                int count = 0;
 582                char **e, **sorted_env;
 583
 584                for (e = env; *e; e++)
 585                        count++;
 586
 587                /* environment must be sorted */
 588                sorted_env = xmalloc(sizeof(*sorted_env) * (count + 1));
 589                memcpy(sorted_env, env, sizeof(*sorted_env) * (count + 1));
 590                qsort(sorted_env, count, sizeof(*sorted_env), env_compare);
 591
 592                strbuf_init(&envblk, 0);
 593                for (e = sorted_env; *e; e++) {
 594                        strbuf_addstr(&envblk, *e);
 595                        strbuf_addch(&envblk, '\0');
 596                }
 597                free(sorted_env);
 598        }
 599
 600        memset(&pi, 0, sizeof(pi));
 601        ret = CreateProcess(cmd, args.buf, NULL, NULL, TRUE, flags,
 602                env ? envblk.buf : NULL, NULL, &si, &pi);
 603
 604        if (env)
 605                strbuf_release(&envblk);
 606        strbuf_release(&args);
 607
 608        if (!ret) {
 609                errno = ENOENT;
 610                return -1;
 611        }
 612        CloseHandle(pi.hThread);
 613        return (pid_t)pi.hProcess;
 614}
 615
 616pid_t mingw_spawnvpe(const char *cmd, const char **argv, char **env)
 617{
 618        pid_t pid;
 619        char **path = get_path_split();
 620        char *prog = path_lookup(cmd, path, 0);
 621
 622        if (!prog) {
 623                errno = ENOENT;
 624                pid = -1;
 625        }
 626        else {
 627                const char *interpr = parse_interpreter(prog);
 628
 629                if (interpr) {
 630                        const char *argv0 = argv[0];
 631                        char *iprog = path_lookup(interpr, path, 1);
 632                        argv[0] = prog;
 633                        if (!iprog) {
 634                                errno = ENOENT;
 635                                pid = -1;
 636                        }
 637                        else {
 638                                pid = mingw_spawnve(iprog, argv, env, 1);
 639                                free(iprog);
 640                        }
 641                        argv[0] = argv0;
 642                }
 643                else
 644                        pid = mingw_spawnve(prog, argv, env, 0);
 645                free(prog);
 646        }
 647        free_path_split(path);
 648        return pid;
 649}
 650
 651static int try_shell_exec(const char *cmd, char *const *argv, char **env)
 652{
 653        const char *interpr = parse_interpreter(cmd);
 654        char **path;
 655        char *prog;
 656        int pid = 0;
 657
 658        if (!interpr)
 659                return 0;
 660        path = get_path_split();
 661        prog = path_lookup(interpr, path, 1);
 662        if (prog) {
 663                int argc = 0;
 664                const char **argv2;
 665                while (argv[argc]) argc++;
 666                argv2 = xmalloc(sizeof(*argv) * (argc+1));
 667                argv2[0] = (char *)cmd; /* full path to the script file */
 668                memcpy(&argv2[1], &argv[1], sizeof(*argv) * argc);
 669                pid = mingw_spawnve(prog, argv2, env, 1);
 670                if (pid >= 0) {
 671                        int status;
 672                        if (waitpid(pid, &status, 0) < 0)
 673                                status = 255;
 674                        exit(status);
 675                }
 676                pid = 1;        /* indicate that we tried but failed */
 677                free(prog);
 678                free(argv2);
 679        }
 680        free_path_split(path);
 681        return pid;
 682}
 683
 684static void mingw_execve(const char *cmd, char *const *argv, char *const *env)
 685{
 686        /* check if git_command is a shell script */
 687        if (!try_shell_exec(cmd, argv, (char **)env)) {
 688                int pid, status;
 689
 690                pid = mingw_spawnve(cmd, (const char **)argv, (char **)env, 0);
 691                if (pid < 0)
 692                        return;
 693                if (waitpid(pid, &status, 0) < 0)
 694                        status = 255;
 695                exit(status);
 696        }
 697}
 698
 699void mingw_execvp(const char *cmd, char *const *argv)
 700{
 701        char **path = get_path_split();
 702        char *prog = path_lookup(cmd, path, 0);
 703
 704        if (prog) {
 705                mingw_execve(prog, argv, environ);
 706                free(prog);
 707        } else
 708                errno = ENOENT;
 709
 710        free_path_split(path);
 711}
 712
 713char **copy_environ()
 714{
 715        char **env;
 716        int i = 0;
 717        while (environ[i])
 718                i++;
 719        env = xmalloc((i+1)*sizeof(*env));
 720        for (i = 0; environ[i]; i++)
 721                env[i] = xstrdup(environ[i]);
 722        env[i] = NULL;
 723        return env;
 724}
 725
 726void free_environ(char **env)
 727{
 728        int i;
 729        for (i = 0; env[i]; i++)
 730                free(env[i]);
 731        free(env);
 732}
 733
 734static int lookup_env(char **env, const char *name, size_t nmln)
 735{
 736        int i;
 737
 738        for (i = 0; env[i]; i++) {
 739                if (0 == strncmp(env[i], name, nmln)
 740                    && '=' == env[i][nmln])
 741                        /* matches */
 742                        return i;
 743        }
 744        return -1;
 745}
 746
 747/*
 748 * If name contains '=', then sets the variable, otherwise it unsets it
 749 */
 750char **env_setenv(char **env, const char *name)
 751{
 752        char *eq = strchrnul(name, '=');
 753        int i = lookup_env(env, name, eq-name);
 754
 755        if (i < 0) {
 756                if (*eq) {
 757                        for (i = 0; env[i]; i++)
 758                                ;
 759                        env = xrealloc(env, (i+2)*sizeof(*env));
 760                        env[i] = xstrdup(name);
 761                        env[i+1] = NULL;
 762                }
 763        }
 764        else {
 765                free(env[i]);
 766                if (*eq)
 767                        env[i] = xstrdup(name);
 768                else
 769                        for (; env[i]; i++)
 770                                env[i] = env[i+1];
 771        }
 772        return env;
 773}
 774
 775/* this is the first function to call into WS_32; initialize it */
 776#undef gethostbyname
 777struct hostent *mingw_gethostbyname(const char *host)
 778{
 779        WSADATA wsa;
 780
 781        if (WSAStartup(MAKEWORD(2,2), &wsa))
 782                die("unable to initialize winsock subsystem, error %d",
 783                        WSAGetLastError());
 784        atexit((void(*)(void)) WSACleanup);
 785        return gethostbyname(host);
 786}
 787
 788int mingw_socket(int domain, int type, int protocol)
 789{
 790        int sockfd;
 791        SOCKET s = WSASocket(domain, type, protocol, NULL, 0, 0);
 792        if (s == INVALID_SOCKET) {
 793                /*
 794                 * WSAGetLastError() values are regular BSD error codes
 795                 * biased by WSABASEERR.
 796                 * However, strerror() does not know about networking
 797                 * specific errors, which are values beginning at 38 or so.
 798                 * Therefore, we choose to leave the biased error code
 799                 * in errno so that _if_ someone looks up the code somewhere,
 800                 * then it is at least the number that are usually listed.
 801                 */
 802                errno = WSAGetLastError();
 803                return -1;
 804        }
 805        /* convert into a file descriptor */
 806        if ((sockfd = _open_osfhandle(s, O_RDWR|O_BINARY)) < 0) {
 807                closesocket(s);
 808                return error("unable to make a socket file descriptor: %s",
 809                        strerror(errno));
 810        }
 811        return sockfd;
 812}
 813
 814#undef connect
 815int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz)
 816{
 817        SOCKET s = (SOCKET)_get_osfhandle(sockfd);
 818        return connect(s, sa, sz);
 819}
 820
 821#undef rename
 822int mingw_rename(const char *pold, const char *pnew)
 823{
 824        DWORD attrs;
 825
 826        /*
 827         * Try native rename() first to get errno right.
 828         * It is based on MoveFile(), which cannot overwrite existing files.
 829         */
 830        if (!rename(pold, pnew))
 831                return 0;
 832        if (errno != EEXIST)
 833                return -1;
 834        if (MoveFileEx(pold, pnew, MOVEFILE_REPLACE_EXISTING))
 835                return 0;
 836        /* TODO: translate more errors */
 837        if (GetLastError() == ERROR_ACCESS_DENIED &&
 838            (attrs = GetFileAttributes(pnew)) != INVALID_FILE_ATTRIBUTES) {
 839                if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
 840                        errno = EISDIR;
 841                        return -1;
 842                }
 843                if ((attrs & FILE_ATTRIBUTE_READONLY) &&
 844                    SetFileAttributes(pnew, attrs & ~FILE_ATTRIBUTE_READONLY)) {
 845                        if (MoveFileEx(pold, pnew, MOVEFILE_REPLACE_EXISTING))
 846                                return 0;
 847                        /* revert file attributes on failure */
 848                        SetFileAttributes(pnew, attrs);
 849                }
 850        }
 851        errno = EACCES;
 852        return -1;
 853}
 854
 855struct passwd *getpwuid(int uid)
 856{
 857        static char user_name[100];
 858        static struct passwd p;
 859
 860        DWORD len = sizeof(user_name);
 861        if (!GetUserName(user_name, &len))
 862                return NULL;
 863        p.pw_name = user_name;
 864        p.pw_gecos = "unknown";
 865        p.pw_dir = NULL;
 866        return &p;
 867}
 868
 869static HANDLE timer_event;
 870static HANDLE timer_thread;
 871static int timer_interval;
 872static int one_shot;
 873static sig_handler_t timer_fn = SIG_DFL;
 874
 875/* The timer works like this:
 876 * The thread, ticktack(), is a trivial routine that most of the time
 877 * only waits to receive the signal to terminate. The main thread tells
 878 * the thread to terminate by setting the timer_event to the signalled
 879 * state.
 880 * But ticktack() interrupts the wait state after the timer's interval
 881 * length to call the signal handler.
 882 */
 883
 884static __stdcall unsigned ticktack(void *dummy)
 885{
 886        while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
 887                if (timer_fn == SIG_DFL)
 888                        die("Alarm");
 889                if (timer_fn != SIG_IGN)
 890                        timer_fn(SIGALRM);
 891                if (one_shot)
 892                        break;
 893        }
 894        return 0;
 895}
 896
 897static int start_timer_thread(void)
 898{
 899        timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
 900        if (timer_event) {
 901                timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
 902                if (!timer_thread )
 903                        return errno = ENOMEM,
 904                                error("cannot start timer thread");
 905        } else
 906                return errno = ENOMEM,
 907                        error("cannot allocate resources for timer");
 908        return 0;
 909}
 910
 911static void stop_timer_thread(void)
 912{
 913        if (timer_event)
 914                SetEvent(timer_event);  /* tell thread to terminate */
 915        if (timer_thread) {
 916                int rc = WaitForSingleObject(timer_thread, 1000);
 917                if (rc == WAIT_TIMEOUT)
 918                        error("timer thread did not terminate timely");
 919                else if (rc != WAIT_OBJECT_0)
 920                        error("waiting for timer thread failed: %lu",
 921                              GetLastError());
 922                CloseHandle(timer_thread);
 923        }
 924        if (timer_event)
 925                CloseHandle(timer_event);
 926        timer_event = NULL;
 927        timer_thread = NULL;
 928}
 929
 930static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
 931{
 932        return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
 933}
 934
 935int setitimer(int type, struct itimerval *in, struct itimerval *out)
 936{
 937        static const struct timeval zero;
 938        static int atexit_done;
 939
 940        if (out != NULL)
 941                return errno = EINVAL,
 942                        error("setitimer param 3 != NULL not implemented");
 943        if (!is_timeval_eq(&in->it_interval, &zero) &&
 944            !is_timeval_eq(&in->it_interval, &in->it_value))
 945                return errno = EINVAL,
 946                        error("setitimer: it_interval must be zero or eq it_value");
 947
 948        if (timer_thread)
 949                stop_timer_thread();
 950
 951        if (is_timeval_eq(&in->it_value, &zero) &&
 952            is_timeval_eq(&in->it_interval, &zero))
 953                return 0;
 954
 955        timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000;
 956        one_shot = is_timeval_eq(&in->it_interval, &zero);
 957        if (!atexit_done) {
 958                atexit(stop_timer_thread);
 959                atexit_done = 1;
 960        }
 961        return start_timer_thread();
 962}
 963
 964int sigaction(int sig, struct sigaction *in, struct sigaction *out)
 965{
 966        if (sig != SIGALRM)
 967                return errno = EINVAL,
 968                        error("sigaction only implemented for SIGALRM");
 969        if (out != NULL)
 970                return errno = EINVAL,
 971                        error("sigaction: param 3 != NULL not implemented");
 972
 973        timer_fn = in->sa_handler;
 974        return 0;
 975}
 976
 977#undef signal
 978sig_handler_t mingw_signal(int sig, sig_handler_t handler)
 979{
 980        if (sig != SIGALRM)
 981                return signal(sig, handler);
 982        sig_handler_t old = timer_fn;
 983        timer_fn = handler;
 984        return old;
 985}
 986
 987static const char *make_backslash_path(const char *path)
 988{
 989        static char buf[PATH_MAX + 1];
 990        char *c;
 991
 992        if (strlcpy(buf, path, PATH_MAX) >= PATH_MAX)
 993                die("Too long path: %.*s", 60, path);
 994
 995        for (c = buf; *c; c++) {
 996                if (*c == '/')
 997                        *c = '\\';
 998        }
 999        return buf;
1000}
1001
1002void mingw_open_html(const char *unixpath)
1003{
1004        const char *htmlpath = make_backslash_path(unixpath);
1005        printf("Launching default browser to display HTML ...\n");
1006        ShellExecute(NULL, "open", htmlpath, NULL, "\\", 0);
1007}