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