enable better Win32::DomainName() by demand loading netapi32.dll
[p5sagit/p5-mst-13.2.git] / win32 / win32.c
index 59e493a..3f56f60 100644 (file)
 #endif
 #include <windows.h>
 
-#ifndef __MINGW32__
-#include <lmcons.h>
-#include <lmerr.h>
-/* ugliness to work around a buggy struct definition in lmwksta.h */
-#undef LPTSTR
-#define LPTSTR LPWSTR
-#include <lmwksta.h>
-#undef LPTSTR
-#define LPTSTR LPSTR
-#include <lmapibuf.h>
-#endif /* __MINGW32__ */
-
 /* #include "config.h" */
 
 #define PERLIO_NOT_STDIO 0 
 int _CRT_glob = 0;
 #endif
 
-#ifdef __BORLANDC__
+#if defined(__MINGW32__)
+#  define _stat stat
+#endif
+
+#if defined(__BORLANDC__)
 #  define _stat stat
 #  define _utimbuf utimbuf
 #endif
@@ -75,23 +67,26 @@ int _CRT_glob = 0;
 #define EXECF_SPAWN 2
 #define EXECF_SPAWN_NOWAIT 3
 
+#if defined(PERL_IMPLICIT_SYS)
+#  undef win32_get_privlib
+#  define win32_get_privlib g_win32_get_privlib
+#  undef win32_get_sitelib
+#  define win32_get_sitelib g_win32_get_sitelib
+#  undef do_spawn
+#  define do_spawn g_do_spawn
+#  undef getlogin
+#  define getlogin g_getlogin
+#endif
+
 #if defined(PERL_OBJECT)
-#undef win32_get_privlib
-#define win32_get_privlib g_win32_get_privlib
-#undef win32_get_sitelib
-#define win32_get_sitelib g_win32_get_sitelib
-#undef do_aspawn
-#define do_aspawn g_do_aspawn
-#undef do_spawn
-#define do_spawn g_do_spawn
-#undef Perl_do_exec
-#define Perl_do_exec g_do_exec
-#undef getlogin
-#define getlogin g_getlogin
+#  undef do_aspawn
+#  define do_aspawn g_do_aspawn
+#  undef Perl_do_exec
+#  define Perl_do_exec g_do_exec
 #endif
 
 static void            get_shell(void);
-static long            tokenize(char *str, char **dest, char ***destv);
+static long            tokenize(const char *str, char **dest, char ***destv);
        int             do_spawn2(char *cmd, int exectype);
 static BOOL            has_shell_metachars(char *ptr);
 static long            filetime_to_clock(PFILETIME ft);
@@ -208,9 +203,9 @@ get_emd_part(SV **prev_pathp, char *trailing_path, ...)
 
        /* try to get full path to binary (which may be mangled when perl is
         * run from a 16-bit app) */
-       /*PerlIO_printf(PerlIO_stderr(), "Before %s\n", w32_module_name);*/
+       /*PerlIO_printf(Perl_debug_log, "Before %s\n", w32_module_name);*/
        (void)win32_longpath(w32_module_name);
-       /*PerlIO_printf(PerlIO_stderr(), "After  %s\n", w32_module_name);*/
+       /*PerlIO_printf(Perl_debug_log, "After  %s\n", w32_module_name);*/
 
        /* normalize to forward slashes */
        ptr = w32_module_name;
@@ -369,7 +364,7 @@ has_shell_metachars(char *ptr)
     return FALSE;
 }
 
-#if !defined(PERL_OBJECT)
+#if !defined(PERL_IMPLICIT_SYS)
 /* since the current process environment is being updated in util.c
  * the library functions will get the correct environment
  */
@@ -424,7 +419,7 @@ win32_os_id(void)
  * Returns number of words in result buffer.
  */
 static long
-tokenize(char *str, char **dest, char ***destv)
+tokenize(const char *str, char **dest, char ***destv)
 {
     char *retstart = Nullch;
     char **retvstart = 0;
@@ -482,8 +477,9 @@ get_shell(void)
         *     interactive use (which is what most programs look in COMSPEC
         *     for).
         */
-       char* defaultshell = (IsWinNT() ? "cmd.exe /x/c" : "command.com /c");
-       char *usershell = getenv("PERL5SHELL");
+       const char* defaultshell = (IsWinNT()
+                                   ? "cmd.exe /x/c" : "command.com /c");
+       const char *usershell = getenv("PERL5SHELL");
        w32_perlshell_items = tokenize(usershell ? usershell : defaultshell,
                                       &w32_perlshell_tokens,
                                       &w32_perlshell_vec);
@@ -672,7 +668,7 @@ DllExport DIR *
 win32_opendir(char *filename)
 {
     dTHXo;
-    DIR                        *p;
+    DIR                        *dirp;
     long               len;
     long               idx;
     char               scanname[MAX_PATH+3];
@@ -682,7 +678,7 @@ win32_opendir(char *filename)
     HANDLE             fh;
     char               buffer[MAX_PATH*2];
     WCHAR              wbuffer[MAX_PATH];
-    char*              ptr;            
+    char*              ptr;
 
     len = strlen(filename);
     if (len > MAX_PATH)
@@ -693,9 +689,7 @@ win32_opendir(char *filename)
        return NULL;
 
     /* Get us a DIR structure */
-    Newz(1303, p, 1, DIR);
-    if (p == NULL)
-       return NULL;
+    Newz(1303, dirp, 1, DIR);
 
     /* Create the search pattern */
     strcpy(scanname, filename);
@@ -719,11 +713,25 @@ win32_opendir(char *filename)
     else {
        fh = FindFirstFileA(scanname, &aFindData);
     }
+    dirp->handle = fh;
     if (fh == INVALID_HANDLE_VALUE) {
+       DWORD err = GetLastError();
        /* FindFirstFile() fails on empty drives! */
-       if (GetLastError() == ERROR_FILE_NOT_FOUND)
-           return p;
-       Safefree( p);
+       switch (err) {
+       case ERROR_FILE_NOT_FOUND:
+           return dirp;
+       case ERROR_NO_MORE_FILES:
+       case ERROR_PATH_NOT_FOUND:
+           errno = ENOENT;
+           break;
+       case ERROR_NOT_ENOUGH_MEMORY:
+           errno = ENOMEM;
+           break;
+       default:
+           errno = EINVAL;
+           break;
+       }
+       Safefree(dirp);
        return NULL;
     }
 
@@ -738,39 +746,16 @@ win32_opendir(char *filename)
        ptr = aFindData.cFileName;
     }
     idx = strlen(ptr)+1;
-    New(1304, p->start, idx, char);
-    if (p->start == NULL)
-       Perl_croak_nocontext("opendir: malloc failed!\n");
-    strcpy(p->start, ptr);
-    p->nfiles++;
-
-    /* loop finding all the files that match the wildcard
-     * (which should be all of them in this directory!).
-     * the variable idx should point one past the null terminator
-     * of the previous string found.
-     */
-    while (USING_WIDE()
-           ? FindNextFileW(fh, &wFindData)
-           : FindNextFileA(fh, &aFindData)) {
-       if (USING_WIDE()) {
-           W2AHELPER(wFindData.cFileName, buffer, sizeof(buffer));
-       }
-       /* ptr is set above to the correct area */
-       len = strlen(ptr);
-       /* bump the string table size by enough for the
-        * new name and it's null terminator
-        */
-       Renew(p->start, idx+len+1, char);
-       if (p->start == NULL)
-           Perl_croak_nocontext("opendir: malloc failed!\n");
-       strcpy(&p->start[idx], ptr);
-       p->nfiles++;
-       idx += len+1;
-    }
-    FindClose(fh);
-    p->size = idx;
-    p->curr = p->start;
-    return p;
+    if (idx < 256)
+       dirp->size = 128;
+    else
+       dirp->size = idx;
+    New(1304, dirp->start, dirp->size, char);
+    strcpy(dirp->start, ptr);
+    dirp->nfiles++;
+    dirp->end = dirp->curr = dirp->start;
+    dirp->end += idx;
+    return dirp;
 }
 
 
@@ -780,8 +765,7 @@ win32_opendir(char *filename)
 DllExport struct direct *
 win32_readdir(DIR *dirp)
 {
-    int         len;
-    static int  dummy = 0;
+    long         len;
 
     if (dirp->curr) {
        /* first set up the structure to return */
@@ -790,14 +774,51 @@ win32_readdir(DIR *dirp)
        dirp->dirstr.d_namlen = len;
 
        /* Fake an inode */
-       dirp->dirstr.d_ino = dummy++;
+       dirp->dirstr.d_ino = dirp->curr - dirp->start;
 
-       /* Now set up for the nDllExport call to readdir */
+       /* Now set up for the next call to readdir */
        dirp->curr += len + 1;
-       if (dirp->curr >= (dirp->start + dirp->size)) {
-           dirp->curr = NULL;
+       if (dirp->curr >= dirp->end) {
+           dTHXo;
+           char*               ptr;
+           BOOL                res;
+           WIN32_FIND_DATAW    wFindData;
+           WIN32_FIND_DATAA    aFindData;
+           char                buffer[MAX_PATH*2];
+
+           /* finding the next file that matches the wildcard
+            * (which should be all of them in this directory!).
+            */
+           if (USING_WIDE()) {
+               res = FindNextFileW(dirp->handle, &wFindData);
+               if (res) {
+                   W2AHELPER(wFindData.cFileName, buffer, sizeof(buffer));
+                   ptr = buffer;
+               }
+           }
+           else {
+               res = FindNextFileA(dirp->handle, &aFindData);
+               if (res)
+                   ptr = aFindData.cFileName;
+           }
+           if (res) {
+               long endpos = dirp->end - dirp->start;
+               long newsize = endpos + strlen(ptr) + 1;
+               /* bump the string table size by enough for the
+                * new name and it's null terminator */
+               while (newsize > dirp->size) {
+                   long curpos = dirp->curr - dirp->start;
+                   dirp->size *= 2;
+                   Renew(dirp->start, dirp->size, char);
+                   dirp->curr = dirp->start + curpos;
+               }
+               strcpy(dirp->start + endpos, ptr);
+               dirp->end = dirp->start + newsize;
+               dirp->nfiles++;
+           }
+           else
+               dirp->curr = NULL;
        }
-
        return &(dirp->dirstr);
     } 
     else
@@ -808,17 +829,17 @@ win32_readdir(DIR *dirp)
 DllExport long
 win32_telldir(DIR *dirp)
 {
-    return (long) dirp->curr;
+    return (dirp->curr - dirp->start);
 }
 
 
 /* Seekdir moves the string pointer to a previously saved position
- *(Saved by telldir).
+ * (returned by telldir).
  */
 DllExport void
 win32_seekdir(DIR *dirp, long loc)
 {
-    dirp->curr = (char *)loc;
+    dirp->curr = dirp->start + loc;
 }
 
 /* Rewinddir resets the string pointer to the start */
@@ -833,6 +854,8 @@ DllExport int
 win32_closedir(DIR *dirp)
 {
     dTHXo;
+    if (dirp->handle != INVALID_HANDLE_VALUE)
+       FindClose(dirp->handle);
     Safefree(dirp->start);
     Safefree(dirp);
     return 1;
@@ -1118,7 +1141,7 @@ win32_longpath(char *path)
        }
        else {
            /* failed a step, just return without side effects */
-           /*PerlIO_printf(PerlIO_stderr(), "Failed to find %s\n", path);*/
+           /*PerlIO_printf(Perl_debug_log, "Failed to find %s\n", path);*/
            *start = sep;
            return Nullch;
        }
@@ -1266,14 +1289,13 @@ win32_times(struct tms *timebuf)
     return 0;
 }
 
-/* fix utime() so it works on directories in NT
- * thanks to Jan Dubois <jan.dubois@ibm.net>
- */
+/* fix utime() so it works on directories in NT */
 static BOOL
 filetime_from_time(PFILETIME pFileTime, time_t Time)
 {
-    struct tm *pTM = gmtime(&Time);
+    struct tm *pTM = localtime(&Time);
     SYSTEMTIME SystemTime;
+    FILETIME LocalTime;
 
     if (pTM == NULL)
        return FALSE;
@@ -1286,7 +1308,8 @@ filetime_from_time(PFILETIME pFileTime, time_t Time)
     SystemTime.wSecond = pTM->tm_sec;
     SystemTime.wMilliseconds = 0;
 
-    return SystemTimeToFileTime(&SystemTime, pFileTime);
+    return SystemTimeToFileTime(&SystemTime, &LocalTime) &&
+           LocalFileTimeToFileTime(&LocalTime, pFileTime);
 }
 
 DllExport int
@@ -1802,12 +1825,14 @@ win32_str_os_error(void *sv, DWORD dwErr)
                          |FORMAT_MESSAGE_IGNORE_INSERTS
                          |FORMAT_MESSAGE_FROM_SYSTEM, NULL,
                           dwErr, 0, (char *)&sMsg, 1, NULL);
+    /* strip trailing whitespace and period */
     if (0 < dwLen) {
-       while (0 < dwLen  &&  isSPACE(sMsg[--dwLen]))
-           ;
+       do {
+           --dwLen;    /* dwLen doesn't include trailing null */
+       } while (0 < dwLen && isSPACE(sMsg[dwLen]));
        if ('.' != sMsg[dwLen])
            dwLen++;
-       sMsg[dwLen]= '\0';
+       sMsg[dwLen] = '\0';
     }
     if (0 == dwLen) {
        sMsg = (char*)LocalAlloc(0, 64/**sizeof(TCHAR)*/);
@@ -2473,6 +2498,35 @@ GIVE_UP:
     return Nullch;
 }
 
+/* The following are just place holders.
+ * Some hosts may provide and environment that the OS is
+ * not tracking, therefore, these host must provide that
+ * environment and the current directory to CreateProcess
+ */
+
+void*
+get_childenv(void)
+{
+    return NULL;
+}
+
+void
+free_childenv(void* d)
+{
+}
+
+char*
+get_childdir(void)
+{
+    return NULL;
+}
+
+void
+free_childdir(char* d)
+{
+}
+
+
 /* XXX this needs to be made more compatible with the spawnvp()
  * provided by the various RTLs.  In particular, searching for
  * *.{com,bat,cmd} files (as done by the RTLs) is unimplemented.
@@ -2491,7 +2545,9 @@ win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
     return spawnvp(mode, cmdname, (char * const *)argv);
 #else
     dTHXo;
-    DWORD ret;
+    int ret;
+    void* env;
+    char* dir;
     STARTUPINFO StartupInfo;
     PROCESS_INFORMATION ProcessInformation;
     DWORD create = 0;
@@ -2500,6 +2556,9 @@ win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
                                             ? &argv[1] : argv);
     char *fullcmd = Nullch;
 
+    env = PerlEnv_get_childenv();
+    dir = PerlEnv_get_childdir();
+
     switch(mode) {
     case P_NOWAIT:     /* asynch + remember result */
        if (w32_num_children >= MAXIMUM_WAIT_OBJECTS) {
@@ -2530,11 +2589,6 @@ win32_spawnvp(int mode, const char *cmdname, const char *const *argv)
        create |= CREATE_NEW_CONSOLE;
     }
 
-#ifndef DEBUGGING
-    StartupInfo.dwFlags |= STARTF_USESHOWWINDOW;
-    StartupInfo.wShowWindow = SW_HIDE;
-#endif
-
 RETRY:
     if (!CreateProcess(cmdname,                /* search PATH to find executable */
                       cmd,             /* executable, and its arguments */
@@ -2542,8 +2596,8 @@ RETRY:
                       NULL,            /* thread attributes */
                       TRUE,            /* inherit handles */
                       create,          /* creation flags */
-                      NULL,            /* inherit environment */
-                      NULL,            /* inherit cwd */
+                      (LPVOID)env,     /* inherit environment */
+                      dir,             /* inherit cwd */
                       &StartupInfo,
                       &ProcessInformation))
     {
@@ -2568,20 +2622,26 @@ RETRY:
     if (mode == P_NOWAIT) {
        /* asynchronous spawn -- store handle, return PID */
        w32_child_handles[w32_num_children] = ProcessInformation.hProcess;
-       ret = w32_child_pids[w32_num_children] = ProcessInformation.dwProcessId;
+       w32_child_pids[w32_num_children] = ProcessInformation.dwProcessId;
+       ret = (int)ProcessInformation.dwProcessId;
        ++w32_num_children;
     }
     else  {
+       DWORD status;
        WaitForSingleObject(ProcessInformation.hProcess, INFINITE);
-       GetExitCodeProcess(ProcessInformation.hProcess, &ret);
+       GetExitCodeProcess(ProcessInformation.hProcess, &status);
+       ret = (int)status;
        CloseHandle(ProcessInformation.hProcess);
     }
 
     CloseHandle(ProcessInformation.hThread);
+
 RETVAL:
+    PerlEnv_free_childenv(env);
+    PerlEnv_free_childdir(dir);
     Safefree(cmd);
     Safefree(fullcmd);
-    return (int)ret;
+    return ret;
 #endif
 }
 
@@ -2942,43 +3002,63 @@ static
 XS(w32_DomainName)
 {
     dXSARGS;
-#ifndef HAS_NETWKSTAGETINFO
-    /* mingw32 (and Win95) don't have NetWksta*(), so do it the old way */
-    char name[256];
-    DWORD size = sizeof(name);
+    HINSTANCE hNetApi32 = LoadLibrary("netapi32.dll");
+    DWORD (__stdcall *pfnNetApiBufferFree)(LPVOID Buffer);
+    DWORD (__stdcall *pfnNetWkstaGetInfo)(LPWSTR servername, DWORD level,
+                                         void *bufptr);
+
+    if (hNetApi32) {
+       pfnNetApiBufferFree = (DWORD (__stdcall *)(void *))
+           GetProcAddress(hNetApi32, "NetApiBufferFree");
+       pfnNetWkstaGetInfo = (DWORD (__stdcall *)(LPWSTR, DWORD, void *))
+           GetProcAddress(hNetApi32, "NetWkstaGetInfo");
+    }
     EXTEND(SP,1);
-    if (GetUserName(name,&size)) {
-       char sid[1024];
-       DWORD sidlen = sizeof(sid);
+    if (hNetApi32 && pfnNetWkstaGetInfo && pfnNetApiBufferFree) {
+       /* this way is more reliable, in case user has a local account. */
        char dname[256];
        DWORD dnamelen = sizeof(dname);
-       SID_NAME_USE snu;
-       if (LookupAccountName(NULL, name, (PSID)&sid, &sidlen,
-                             dname, &dnamelen, &snu)) {
-           XSRETURN_PV(dname);         /* all that for this */
+       struct {
+           DWORD   wki100_platform_id;
+           LPWSTR  wki100_computername;
+           LPWSTR  wki100_langroup;
+           DWORD   wki100_ver_major;
+           DWORD   wki100_ver_minor;
+       } *pwi;
+       /* NERR_Success *is* 0*/
+       if (0 == pfnNetWkstaGetInfo(NULL, 100, &pwi)) {
+           if (pwi->wki100_langroup && *(pwi->wki100_langroup)) {
+               WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_langroup,
+                                   -1, (LPSTR)dname, dnamelen, NULL, NULL);
+           }
+           else {
+               WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_computername,
+                                   -1, (LPSTR)dname, dnamelen, NULL, NULL);
+           }
+           pfnNetApiBufferFree(pwi);
+           FreeLibrary(hNetApi32);
+           XSRETURN_PV(dname);
        }
+       FreeLibrary(hNetApi32);
     }
-#else
-    /* this way is more reliable, in case user has a local account.
-     * XXX need dynamic binding of netapi32.dll symbols or this will fail on
-     * Win95. Probably makes more sense to move it into libwin32. */
-    char dname[256];
-    DWORD dnamelen = sizeof(dname);
-    PWKSTA_INFO_100 pwi;
-    EXTEND(SP,1);
-    if (NERR_Success == NetWkstaGetInfo(NULL, 100, (LPBYTE*)&pwi)) {
-       if (pwi->wki100_langroup && *(pwi->wki100_langroup)) {
-           WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_langroup,
-                               -1, (LPSTR)dname, dnamelen, NULL, NULL);
-       }
-       else {
-           WideCharToMultiByte(CP_ACP, NULL, pwi->wki100_computername,
-                               -1, (LPSTR)dname, dnamelen, NULL, NULL);
+    else {
+       /* Win95 doesn't have NetWksta*(), so do it the old way */
+       char name[256];
+       DWORD size = sizeof(name);
+       if (hNetApi32)
+           FreeLibrary(hNetApi32);
+       if (GetUserName(name,&size)) {
+           char sid[1024];
+           DWORD sidlen = sizeof(sid);
+           char dname[256];
+           DWORD dnamelen = sizeof(dname);
+           SID_NAME_USE snu;
+           if (LookupAccountName(NULL, name, (PSID)&sid, &sidlen,
+                                 dname, &dnamelen, &snu)) {
+               XSRETURN_PV(dname);             /* all that for this */
+           }
        }
-       NetApiBufferFree(pwi);
-       XSRETURN_PV(dname);
     }
-#endif
     XSRETURN_UNDEF;
 }