compat / mingw.con commit Windows: Implement wrappers for gethostbyname(), socket(), and connect(). (746fb85)
   1#include "../git-compat-util.h"
   2
   3unsigned int _CRT_fmode = _O_BINARY;
   4
   5#undef open
   6int mingw_open (const char *filename, int oflags, ...)
   7{
   8        va_list args;
   9        unsigned mode;
  10        va_start(args, oflags);
  11        mode = va_arg(args, int);
  12        va_end(args);
  13
  14        if (!strcmp(filename, "/dev/null"))
  15                filename = "nul";
  16        int fd = open(filename, oflags, mode);
  17        if (fd < 0 && (oflags & O_CREAT) && errno == EACCES) {
  18                DWORD attrs = GetFileAttributes(filename);
  19                if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY))
  20                        errno = EISDIR;
  21        }
  22        return fd;
  23}
  24
  25unsigned int sleep (unsigned int seconds)
  26{
  27        Sleep(seconds*1000);
  28        return 0;
  29}
  30
  31int mkstemp(char *template)
  32{
  33        char *filename = mktemp(template);
  34        if (filename == NULL)
  35                return -1;
  36        return open(filename, O_RDWR | O_CREAT, 0600);
  37}
  38
  39int gettimeofday(struct timeval *tv, void *tz)
  40{
  41        SYSTEMTIME st;
  42        struct tm tm;
  43        GetSystemTime(&st);
  44        tm.tm_year = st.wYear-1900;
  45        tm.tm_mon = st.wMonth-1;
  46        tm.tm_mday = st.wDay;
  47        tm.tm_hour = st.wHour;
  48        tm.tm_min = st.wMinute;
  49        tm.tm_sec = st.wSecond;
  50        tv->tv_sec = tm_to_time_t(&tm);
  51        if (tv->tv_sec < 0)
  52                return -1;
  53        tv->tv_usec = st.wMilliseconds*1000;
  54        return 0;
  55}
  56
  57int pipe(int filedes[2])
  58{
  59        int fd;
  60        HANDLE h[2], parent;
  61
  62        if (_pipe(filedes, 8192, 0) < 0)
  63                return -1;
  64
  65        parent = GetCurrentProcess();
  66
  67        if (!DuplicateHandle (parent, (HANDLE)_get_osfhandle(filedes[0]),
  68                        parent, &h[0], 0, FALSE, DUPLICATE_SAME_ACCESS)) {
  69                close(filedes[0]);
  70                close(filedes[1]);
  71                return -1;
  72        }
  73        if (!DuplicateHandle (parent, (HANDLE)_get_osfhandle(filedes[1]),
  74                        parent, &h[1], 0, FALSE, DUPLICATE_SAME_ACCESS)) {
  75                close(filedes[0]);
  76                close(filedes[1]);
  77                CloseHandle(h[0]);
  78                return -1;
  79        }
  80        fd = _open_osfhandle((int)h[0], O_NOINHERIT);
  81        if (fd < 0) {
  82                close(filedes[0]);
  83                close(filedes[1]);
  84                CloseHandle(h[0]);
  85                CloseHandle(h[1]);
  86                return -1;
  87        }
  88        close(filedes[0]);
  89        filedes[0] = fd;
  90        fd = _open_osfhandle((int)h[1], O_NOINHERIT);
  91        if (fd < 0) {
  92                close(filedes[0]);
  93                close(filedes[1]);
  94                CloseHandle(h[1]);
  95                return -1;
  96        }
  97        close(filedes[1]);
  98        filedes[1] = fd;
  99        return 0;
 100}
 101
 102int poll(struct pollfd *ufds, unsigned int nfds, int timeout)
 103{
 104        int i, pending;
 105
 106        if (timeout != -1)
 107                return errno = EINVAL, error("poll timeout not supported");
 108
 109        /* When there is only one fd to wait for, then we pretend that
 110         * input is available and let the actual wait happen when the
 111         * caller invokes read().
 112         */
 113        if (nfds == 1) {
 114                if (!(ufds[0].events & POLLIN))
 115                        return errno = EINVAL, error("POLLIN not set");
 116                ufds[0].revents = POLLIN;
 117                return 0;
 118        }
 119
 120repeat:
 121        pending = 0;
 122        for (i = 0; i < nfds; i++) {
 123                DWORD avail = 0;
 124                HANDLE h = (HANDLE) _get_osfhandle(ufds[i].fd);
 125                if (h == INVALID_HANDLE_VALUE)
 126                        return -1;      /* errno was set */
 127
 128                if (!(ufds[i].events & POLLIN))
 129                        return errno = EINVAL, error("POLLIN not set");
 130
 131                /* this emulation works only for pipes */
 132                if (!PeekNamedPipe(h, NULL, 0, NULL, &avail, NULL)) {
 133                        int err = GetLastError();
 134                        if (err == ERROR_BROKEN_PIPE) {
 135                                ufds[i].revents = POLLHUP;
 136                                pending++;
 137                        } else {
 138                                errno = EINVAL;
 139                                return error("PeekNamedPipe failed,"
 140                                        " GetLastError: %u", err);
 141                        }
 142                } else if (avail) {
 143                        ufds[i].revents = POLLIN;
 144                        pending++;
 145                } else
 146                        ufds[i].revents = 0;
 147        }
 148        if (!pending) {
 149                /* The only times that we spin here is when the process
 150                 * that is connected through the pipes is waiting for
 151                 * its own input data to become available. But since
 152                 * the process (pack-objects) is itself CPU intensive,
 153                 * it will happily pick up the time slice that we are
 154                 * relinguishing here.
 155                 */
 156                Sleep(0);
 157                goto repeat;
 158        }
 159        return 0;
 160}
 161
 162struct tm *gmtime_r(const time_t *timep, struct tm *result)
 163{
 164        /* gmtime() in MSVCRT.DLL is thread-safe, but not reentrant */
 165        memcpy(result, gmtime(timep), sizeof(struct tm));
 166        return result;
 167}
 168
 169struct tm *localtime_r(const time_t *timep, struct tm *result)
 170{
 171        /* localtime() in MSVCRT.DLL is thread-safe, but not reentrant */
 172        memcpy(result, localtime(timep), sizeof(struct tm));
 173        return result;
 174}
 175
 176#undef getcwd
 177char *mingw_getcwd(char *pointer, int len)
 178{
 179        int i;
 180        char *ret = getcwd(pointer, len);
 181        if (!ret)
 182                return ret;
 183        for (i = 0; pointer[i]; i++)
 184                if (pointer[i] == '\\')
 185                        pointer[i] = '/';
 186        return ret;
 187}
 188
 189static const char *parse_interpreter(const char *cmd)
 190{
 191        static char buf[100];
 192        char *p, *opt;
 193        int n, fd;
 194
 195        /* don't even try a .exe */
 196        n = strlen(cmd);
 197        if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
 198                return NULL;
 199
 200        fd = open(cmd, O_RDONLY);
 201        if (fd < 0)
 202                return NULL;
 203        n = read(fd, buf, sizeof(buf)-1);
 204        close(fd);
 205        if (n < 4)      /* at least '#!/x' and not error */
 206                return NULL;
 207
 208        if (buf[0] != '#' || buf[1] != '!')
 209                return NULL;
 210        buf[n] = '\0';
 211        p = strchr(buf, '\n');
 212        if (!p)
 213                return NULL;
 214
 215        *p = '\0';
 216        if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
 217                return NULL;
 218        /* strip options */
 219        if ((opt = strchr(p+1, ' ')))
 220                *opt = '\0';
 221        return p+1;
 222}
 223
 224/*
 225 * Splits the PATH into parts.
 226 */
 227static char **get_path_split(void)
 228{
 229        char *p, **path, *envpath = getenv("PATH");
 230        int i, n = 0;
 231
 232        if (!envpath || !*envpath)
 233                return NULL;
 234
 235        envpath = xstrdup(envpath);
 236        p = envpath;
 237        while (p) {
 238                char *dir = p;
 239                p = strchr(p, ';');
 240                if (p) *p++ = '\0';
 241                if (*dir) {     /* not earlier, catches series of ; */
 242                        ++n;
 243                }
 244        }
 245        if (!n)
 246                return NULL;
 247
 248        path = xmalloc((n+1)*sizeof(char*));
 249        p = envpath;
 250        i = 0;
 251        do {
 252                if (*p)
 253                        path[i++] = xstrdup(p);
 254                p = p+strlen(p)+1;
 255        } while (i < n);
 256        path[i] = NULL;
 257
 258        free(envpath);
 259
 260        return path;
 261}
 262
 263static void free_path_split(char **path)
 264{
 265        if (!path)
 266                return;
 267
 268        char **p = path;
 269        while (*p)
 270                free(*p++);
 271        free(path);
 272}
 273
 274/*
 275 * exe_only means that we only want to detect .exe files, but not scripts
 276 * (which do not have an extension)
 277 */
 278static char *lookup_prog(const char *dir, const char *cmd, int isexe, int exe_only)
 279{
 280        char path[MAX_PATH];
 281        snprintf(path, sizeof(path), "%s/%s.exe", dir, cmd);
 282
 283        if (!isexe && access(path, F_OK) == 0)
 284                return xstrdup(path);
 285        path[strlen(path)-4] = '\0';
 286        if ((!exe_only || isexe) && access(path, F_OK) == 0)
 287                return xstrdup(path);
 288        return NULL;
 289}
 290
 291/*
 292 * Determines the absolute path of cmd using the the split path in path.
 293 * If cmd contains a slash or backslash, no lookup is performed.
 294 */
 295static char *path_lookup(const char *cmd, char **path, int exe_only)
 296{
 297        char *prog = NULL;
 298        int len = strlen(cmd);
 299        int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
 300
 301        if (strchr(cmd, '/') || strchr(cmd, '\\'))
 302                prog = xstrdup(cmd);
 303
 304        while (!prog && *path)
 305                prog = lookup_prog(*path++, cmd, isexe, exe_only);
 306
 307        return prog;
 308}
 309
 310static int try_shell_exec(const char *cmd, char *const *argv, char **env)
 311{
 312        const char *interpr = parse_interpreter(cmd);
 313        char **path;
 314        char *prog;
 315        int pid = 0;
 316
 317        if (!interpr)
 318                return 0;
 319        path = get_path_split();
 320        prog = path_lookup(interpr, path, 1);
 321        if (prog) {
 322                int argc = 0;
 323                const char **argv2;
 324                while (argv[argc]) argc++;
 325                argv2 = xmalloc(sizeof(*argv) * (argc+2));
 326                argv2[0] = (char *)interpr;
 327                argv2[1] = (char *)cmd; /* full path to the script file */
 328                memcpy(&argv2[2], &argv[1], sizeof(*argv) * argc);
 329                pid = spawnve(_P_NOWAIT, prog, argv2, (const char **)env);
 330                if (pid >= 0) {
 331                        int status;
 332                        if (waitpid(pid, &status, 0) < 0)
 333                                status = 255;
 334                        exit(status);
 335                }
 336                pid = 1;        /* indicate that we tried but failed */
 337                free(prog);
 338                free(argv2);
 339        }
 340        free_path_split(path);
 341        return pid;
 342}
 343
 344static void mingw_execve(const char *cmd, char *const *argv, char *const *env)
 345{
 346        /* check if git_command is a shell script */
 347        if (!try_shell_exec(cmd, argv, (char **)env)) {
 348                int pid, status;
 349
 350                pid = spawnve(_P_NOWAIT, cmd, (const char **)argv, (const char **)env);
 351                if (pid < 0)
 352                        return;
 353                if (waitpid(pid, &status, 0) < 0)
 354                        status = 255;
 355                exit(status);
 356        }
 357}
 358
 359void mingw_execvp(const char *cmd, char *const *argv)
 360{
 361        char **path = get_path_split();
 362        char *prog = path_lookup(cmd, path, 0);
 363
 364        if (prog) {
 365                mingw_execve(prog, argv, environ);
 366                free(prog);
 367        } else
 368                errno = ENOENT;
 369
 370        free_path_split(path);
 371}
 372
 373char **copy_environ()
 374{
 375        char **env;
 376        int i = 0;
 377        while (environ[i])
 378                i++;
 379        env = xmalloc((i+1)*sizeof(*env));
 380        for (i = 0; environ[i]; i++)
 381                env[i] = xstrdup(environ[i]);
 382        env[i] = NULL;
 383        return env;
 384}
 385
 386void free_environ(char **env)
 387{
 388        int i;
 389        for (i = 0; env[i]; i++)
 390                free(env[i]);
 391        free(env);
 392}
 393
 394static int lookup_env(char **env, const char *name, size_t nmln)
 395{
 396        int i;
 397
 398        for (i = 0; env[i]; i++) {
 399                if (0 == strncmp(env[i], name, nmln)
 400                    && '=' == env[i][nmln])
 401                        /* matches */
 402                        return i;
 403        }
 404        return -1;
 405}
 406
 407/*
 408 * If name contains '=', then sets the variable, otherwise it unsets it
 409 */
 410char **env_setenv(char **env, const char *name)
 411{
 412        char *eq = strchrnul(name, '=');
 413        int i = lookup_env(env, name, eq-name);
 414
 415        if (i < 0) {
 416                if (*eq) {
 417                        for (i = 0; env[i]; i++)
 418                                ;
 419                        env = xrealloc(env, (i+2)*sizeof(*env));
 420                        env[i] = xstrdup(name);
 421                        env[i+1] = NULL;
 422                }
 423        }
 424        else {
 425                free(env[i]);
 426                if (*eq)
 427                        env[i] = xstrdup(name);
 428                else
 429                        for (; env[i]; i++)
 430                                env[i] = env[i+1];
 431        }
 432        return env;
 433}
 434
 435/* this is the first function to call into WS_32; initialize it */
 436#undef gethostbyname
 437struct hostent *mingw_gethostbyname(const char *host)
 438{
 439        WSADATA wsa;
 440
 441        if (WSAStartup(MAKEWORD(2,2), &wsa))
 442                die("unable to initialize winsock subsystem, error %d",
 443                        WSAGetLastError());
 444        atexit((void(*)(void)) WSACleanup);
 445        return gethostbyname(host);
 446}
 447
 448int mingw_socket(int domain, int type, int protocol)
 449{
 450        int sockfd;
 451        SOCKET s = WSASocket(domain, type, protocol, NULL, 0, 0);
 452        if (s == INVALID_SOCKET) {
 453                /*
 454                 * WSAGetLastError() values are regular BSD error codes
 455                 * biased by WSABASEERR.
 456                 * However, strerror() does not know about networking
 457                 * specific errors, which are values beginning at 38 or so.
 458                 * Therefore, we choose to leave the biased error code
 459                 * in errno so that _if_ someone looks up the code somewhere,
 460                 * then it is at least the number that are usually listed.
 461                 */
 462                errno = WSAGetLastError();
 463                return -1;
 464        }
 465        /* convert into a file descriptor */
 466        if ((sockfd = _open_osfhandle(s, O_RDWR|O_BINARY)) < 0) {
 467                closesocket(s);
 468                return error("unable to make a socket file descriptor: %s",
 469                        strerror(errno));
 470        }
 471        return sockfd;
 472}
 473
 474#undef connect
 475int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz)
 476{
 477        SOCKET s = (SOCKET)_get_osfhandle(sockfd);
 478        return connect(s, sa, sz);
 479}
 480
 481#undef rename
 482int mingw_rename(const char *pold, const char *pnew)
 483{
 484        /*
 485         * Try native rename() first to get errno right.
 486         * It is based on MoveFile(), which cannot overwrite existing files.
 487         */
 488        if (!rename(pold, pnew))
 489                return 0;
 490        if (errno != EEXIST)
 491                return -1;
 492        if (MoveFileEx(pold, pnew, MOVEFILE_REPLACE_EXISTING))
 493                return 0;
 494        /* TODO: translate more errors */
 495        if (GetLastError() == ERROR_ACCESS_DENIED) {
 496                DWORD attrs = GetFileAttributes(pnew);
 497                if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY)) {
 498                        errno = EISDIR;
 499                        return -1;
 500                }
 501        }
 502        errno = EACCES;
 503        return -1;
 504}
 505
 506struct passwd *getpwuid(int uid)
 507{
 508        static char user_name[100];
 509        static struct passwd p;
 510
 511        DWORD len = sizeof(user_name);
 512        if (!GetUserName(user_name, &len))
 513                return NULL;
 514        p.pw_name = user_name;
 515        p.pw_gecos = "unknown";
 516        p.pw_dir = NULL;
 517        return &p;
 518}
 519
 520static HANDLE timer_event;
 521static HANDLE timer_thread;
 522static int timer_interval;
 523static int one_shot;
 524static sig_handler_t timer_fn = SIG_DFL;
 525
 526/* The timer works like this:
 527 * The thread, ticktack(), is a trivial routine that most of the time
 528 * only waits to receive the signal to terminate. The main thread tells
 529 * the thread to terminate by setting the timer_event to the signalled
 530 * state.
 531 * But ticktack() interrupts the wait state after the timer's interval
 532 * length to call the signal handler.
 533 */
 534
 535static __stdcall unsigned ticktack(void *dummy)
 536{
 537        while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
 538                if (timer_fn == SIG_DFL)
 539                        die("Alarm");
 540                if (timer_fn != SIG_IGN)
 541                        timer_fn(SIGALRM);
 542                if (one_shot)
 543                        break;
 544        }
 545        return 0;
 546}
 547
 548static int start_timer_thread(void)
 549{
 550        timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
 551        if (timer_event) {
 552                timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
 553                if (!timer_thread )
 554                        return errno = ENOMEM,
 555                                error("cannot start timer thread");
 556        } else
 557                return errno = ENOMEM,
 558                        error("cannot allocate resources for timer");
 559        return 0;
 560}
 561
 562static void stop_timer_thread(void)
 563{
 564        if (timer_event)
 565                SetEvent(timer_event);  /* tell thread to terminate */
 566        if (timer_thread) {
 567                int rc = WaitForSingleObject(timer_thread, 1000);
 568                if (rc == WAIT_TIMEOUT)
 569                        error("timer thread did not terminate timely");
 570                else if (rc != WAIT_OBJECT_0)
 571                        error("waiting for timer thread failed: %lu",
 572                              GetLastError());
 573                CloseHandle(timer_thread);
 574        }
 575        if (timer_event)
 576                CloseHandle(timer_event);
 577        timer_event = NULL;
 578        timer_thread = NULL;
 579}
 580
 581static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
 582{
 583        return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
 584}
 585
 586int setitimer(int type, struct itimerval *in, struct itimerval *out)
 587{
 588        static const struct timeval zero;
 589        static int atexit_done;
 590
 591        if (out != NULL)
 592                return errno = EINVAL,
 593                        error("setitimer param 3 != NULL not implemented");
 594        if (!is_timeval_eq(&in->it_interval, &zero) &&
 595            !is_timeval_eq(&in->it_interval, &in->it_value))
 596                return errno = EINVAL,
 597                        error("setitimer: it_interval must be zero or eq it_value");
 598
 599        if (timer_thread)
 600                stop_timer_thread();
 601
 602        if (is_timeval_eq(&in->it_value, &zero) &&
 603            is_timeval_eq(&in->it_interval, &zero))
 604                return 0;
 605
 606        timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000;
 607        one_shot = is_timeval_eq(&in->it_interval, &zero);
 608        if (!atexit_done) {
 609                atexit(stop_timer_thread);
 610                atexit_done = 1;
 611        }
 612        return start_timer_thread();
 613}
 614
 615int sigaction(int sig, struct sigaction *in, struct sigaction *out)
 616{
 617        if (sig != SIGALRM)
 618                return errno = EINVAL,
 619                        error("sigaction only implemented for SIGALRM");
 620        if (out != NULL)
 621                return errno = EINVAL,
 622                        error("sigaction: param 3 != NULL not implemented");
 623
 624        timer_fn = in->sa_handler;
 625        return 0;
 626}
 627
 628#undef signal
 629sig_handler_t mingw_signal(int sig, sig_handler_t handler)
 630{
 631        if (sig != SIGALRM)
 632                return signal(sig, handler);
 633        sig_handler_t old = timer_fn;
 634        timer_fn = handler;
 635        return old;
 636}