windows-nls-includes-20080626
[openafs.git] / src / sys / pioctl_nt.c
1 /*
2  * Copyright 2000, International Business Machines Corporation and others.
3  * All Rights Reserved.
4  * 
5  * This software has been released under the terms of the IBM Public
6  * License.  For details, see the LICENSE file in the top-level source
7  * directory or online at http://www.openafs.org/dl/license10.html
8  */
9
10 #include <afsconfig.h>
11 #include <afs/param.h>
12
13 RCSID
14     ("$Header$");
15
16 #include <afs/stds.h>
17 #include <windows.h>
18 #include <stdlib.h>
19 #include <stdio.h>
20 #include <errno.h>
21 #include <malloc.h>
22 #include <string.h>
23 #include <winioctl.h>
24 #include <winsock2.h>
25 #define SECURITY_WIN32
26 #include <security.h>
27 #include <nb30.h>
28
29 #include <osi.h>
30
31 #include <cm.h>
32 #include <cm_nls.h>
33 #include <cm_server.h>
34 #include <cm_cell.h>
35 #include <cm_user.h>
36 #include <cm_conn.h>
37 #include <cm_scache.h>
38 #include <cm_buf.h>
39 #include <cm_dir.h>
40 #include <cm_utils.h>
41 #include <cm_ioctl.h>
42
43 #include <smb.h>
44 #include <pioctl_nt.h>
45 #include <WINNT/afsreg.h>
46 #include <lanahelper.h>
47
48 #include <loadfuncs-krb5.h>
49 #include <krb5.h>
50
51 static char AFSConfigKeyName[] = AFSREG_CLT_SVC_PARAM_SUBKEY;
52
53 static const char utf8_prefix[] = UTF8_PREFIX;
54 static const int  utf8_prefix_size = sizeof(utf8_prefix) -  sizeof(char);
55
56 #define FS_IOCTLREQUEST_MAXSIZE 8192
57 /* big structure for representing and storing an IOCTL request */
58 typedef struct fs_ioctlRequest {
59     char *mp;                   /* marshalling/unmarshalling ptr */
60     long nbytes;                /* bytes received (when unmarshalling) */
61     char data[FS_IOCTLREQUEST_MAXSIZE]; /* data we're marshalling */
62 } fs_ioctlRequest_t;
63
64 static int
65 CMtoUNIXerror(int cm_code)
66 {
67     switch (cm_code) {
68     case CM_ERROR_TIMEDOUT:
69         return ETIMEDOUT;
70     case CM_ERROR_NOACCESS:
71         return EACCES;
72     case CM_ERROR_NOSUCHFILE:
73     case CM_ERROR_NOSUCHPATH:
74     case CM_ERROR_BPLUS_NOMATCH:
75         return ENOENT;
76     case CM_ERROR_INVAL:
77         return EINVAL;
78     case CM_ERROR_BADFD:
79         return EBADF;
80     case CM_ERROR_EXISTS:
81     case CM_ERROR_INEXACT_MATCH:
82         return EEXIST;
83     case CM_ERROR_CROSSDEVLINK:
84         return EXDEV;
85     case CM_ERROR_NOTDIR:
86         return ENOTDIR;
87     case CM_ERROR_ISDIR:
88         return EISDIR;
89     case CM_ERROR_READONLY:
90         return EROFS;
91     case CM_ERROR_WOULDBLOCK:
92         return EWOULDBLOCK;
93     case CM_ERROR_NOSUCHCELL:
94         return ESRCH;           /* hack */
95     case CM_ERROR_NOSUCHVOLUME:
96         return EPIPE;           /* hack */
97     case CM_ERROR_NOMORETOKENS:
98         return EDOM;            /* hack */
99     case CM_ERROR_TOOMANYBUFS:
100         return EFBIG;           /* hack */
101     case CM_ERROR_ALLBUSY:
102         return EBUSY;
103     case CM_ERROR_ALLDOWN:
104         return ENOSYS;          /* hack */
105     case CM_ERROR_ALLOFFLINE:
106         return ENXIO;           /* hack */
107     default:
108         if (cm_code > 0 && cm_code < EILSEQ)
109             return cm_code;
110         else
111             return ENOTTY;
112     }
113 }
114
115 static void
116 InitFSRequest(fs_ioctlRequest_t * rp)
117 {
118     rp->mp = rp->data;
119     rp->nbytes = 0;
120 }
121
122 static BOOL
123 IoctlDebug(void)
124 {
125     static int init = 0;
126     static BOOL debug = 0;
127
128     if ( !init ) {
129         HKEY hk;
130
131         if (RegOpenKey (HKEY_LOCAL_MACHINE, 
132                          TEXT("Software\\OpenAFS\\Client"), &hk) == 0)
133         {
134             DWORD dwSize = sizeof(BOOL);
135             DWORD dwType = REG_DWORD;
136             RegQueryValueEx (hk, TEXT("IoctlDebug"), NULL, &dwType, (PBYTE)&debug, &dwSize);
137             RegCloseKey (hk);
138         }
139
140         init = 1;
141     }
142
143     return debug;
144 }
145
146 static BOOL
147 DisableServiceManagerCheck(void)
148 {
149     static int init = 0;
150     static BOOL smcheck = 0;
151
152     if ( !init ) {
153         HKEY hk;
154
155         if (RegOpenKey (HKEY_LOCAL_MACHINE, 
156                          TEXT("Software\\OpenAFS\\Client"), &hk) == 0)
157         {
158             DWORD dwSize = sizeof(BOOL);
159             DWORD dwType = REG_DWORD;
160             RegQueryValueEx (hk, TEXT("DisableIoctlSMCheck"), NULL, &dwType, (PBYTE)&smcheck, &dwSize);
161             RegCloseKey (hk);
162         }
163
164         init = 1;
165     }
166
167     return smcheck;
168 }
169
170 static DWORD 
171 GetServiceStatus(
172     LPSTR lpszMachineName, 
173     LPSTR lpszServiceName,
174     DWORD *lpdwCurrentState) 
175
176     DWORD           hr               = NOERROR; 
177     SC_HANDLE       schSCManager     = NULL; 
178     SC_HANDLE       schService       = NULL; 
179     DWORD           fdwDesiredAccess = 0; 
180     SERVICE_STATUS  ssServiceStatus  = {0}; 
181     BOOL            fRet             = FALSE; 
182
183     *lpdwCurrentState = 0; 
184  
185     fdwDesiredAccess = GENERIC_READ; 
186  
187     schSCManager = OpenSCManager(lpszMachineName,  
188                                  NULL,
189                                  fdwDesiredAccess); 
190  
191     if(schSCManager == NULL) 
192     { 
193         hr = GetLastError();
194         goto cleanup; 
195     } 
196  
197     schService = OpenService(schSCManager,
198                              lpszServiceName,
199                              fdwDesiredAccess); 
200  
201     if(schService == NULL) 
202     { 
203         hr = GetLastError();
204         goto cleanup; 
205     } 
206  
207     fRet = QueryServiceStatus(schService,
208                               &ssServiceStatus); 
209  
210     if(fRet == FALSE) 
211     { 
212         hr = GetLastError(); 
213         goto cleanup; 
214     } 
215  
216     *lpdwCurrentState = ssServiceStatus.dwCurrentState; 
217  
218 cleanup: 
219  
220     CloseServiceHandle(schService); 
221     CloseServiceHandle(schSCManager); 
222  
223     return(hr); 
224
225
226 // krb5 functions
227 DECL_FUNC_PTR(krb5_cc_default_name);
228 DECL_FUNC_PTR(krb5_cc_set_default_name);
229 DECL_FUNC_PTR(krb5_get_default_config_files);
230 DECL_FUNC_PTR(krb5_free_config_files);
231 DECL_FUNC_PTR(krb5_free_context);
232 DECL_FUNC_PTR(krb5_get_default_realm);
233 DECL_FUNC_PTR(krb5_free_default_realm);
234 DECL_FUNC_PTR(krb5_init_context);
235 DECL_FUNC_PTR(krb5_cc_default);
236 DECL_FUNC_PTR(krb5_parse_name);
237 DECL_FUNC_PTR(krb5_free_principal);
238 DECL_FUNC_PTR(krb5_cc_close);
239 DECL_FUNC_PTR(krb5_cc_get_principal);
240 DECL_FUNC_PTR(krb5_build_principal);
241 DECL_FUNC_PTR(krb5_c_random_make_octets);
242 DECL_FUNC_PTR(krb5_get_init_creds_password);
243 DECL_FUNC_PTR(krb5_free_cred_contents);
244 DECL_FUNC_PTR(krb5_cc_resolve);
245 DECL_FUNC_PTR(krb5_unparse_name);
246 DECL_FUNC_PTR(krb5_free_unparsed_name);
247
248 FUNC_INFO krb5_fi[] = {
249     MAKE_FUNC_INFO(krb5_cc_default_name),
250     MAKE_FUNC_INFO(krb5_cc_set_default_name),
251     MAKE_FUNC_INFO(krb5_get_default_config_files),
252     MAKE_FUNC_INFO(krb5_free_config_files),
253     MAKE_FUNC_INFO(krb5_free_context),
254     MAKE_FUNC_INFO(krb5_get_default_realm),
255     MAKE_FUNC_INFO(krb5_free_default_realm),
256     MAKE_FUNC_INFO(krb5_init_context),
257     MAKE_FUNC_INFO(krb5_cc_default),
258     MAKE_FUNC_INFO(krb5_parse_name),
259     MAKE_FUNC_INFO(krb5_free_principal),
260     MAKE_FUNC_INFO(krb5_cc_close),
261     MAKE_FUNC_INFO(krb5_cc_get_principal),
262     MAKE_FUNC_INFO(krb5_build_principal),
263     MAKE_FUNC_INFO(krb5_c_random_make_octets),
264     MAKE_FUNC_INFO(krb5_get_init_creds_password),
265     MAKE_FUNC_INFO(krb5_free_cred_contents),
266     MAKE_FUNC_INFO(krb5_cc_resolve),
267     MAKE_FUNC_INFO(krb5_unparse_name),
268     MAKE_FUNC_INFO(krb5_free_unparsed_name),
269     END_FUNC_INFO
270 };
271
272 static int
273 LoadFuncs(
274     const char* dll_name,
275     FUNC_INFO fi[],
276     HINSTANCE* ph,  // [out, optional] - DLL handle
277     int* pindex,    // [out, optional] - index of last func loaded (-1 if none)
278     int cleanup,    // cleanup function pointers and unload on error
279     int go_on,      // continue loading even if some functions cannot be loaded
280     int silent      // do not pop-up a system dialog if DLL cannot be loaded
281     )
282 {
283     HINSTANCE h;
284     int i, n, last_i;
285     int error = 0;
286     UINT em;
287
288     if (ph) *ph = 0;
289     if (pindex) *pindex = -1;
290
291     for (n = 0; fi[n].func_ptr_var; n++)
292         *(fi[n].func_ptr_var) = 0;
293
294     if (silent)
295         em = SetErrorMode(SEM_FAILCRITICALERRORS);
296     h = LoadLibrary(dll_name);
297     if (silent)
298         SetErrorMode(em);
299
300     if (!h)
301         return 0;
302
303     last_i = -1;
304     for (i = 0; (go_on || !error) && (i < n); i++)
305     {
306         void* p = (void*)GetProcAddress(h, fi[i].func_name);
307         if (!p)
308             error = 1;
309         else
310         {
311             last_i = i;
312             *(fi[i].func_ptr_var) = p;
313         }
314     }
315     if (pindex) *pindex = last_i;
316     if (error && cleanup && !go_on) {
317         for (i = 0; i < n; i++) {
318             *(fi[i].func_ptr_var) = 0;
319         }
320         FreeLibrary(h);
321         return 0;
322     }
323     if (ph) *ph = h;
324     if (error) return 0;
325     return 1;
326 }
327 #if defined(_IA64_) || defined(_AMD64_)
328 #define KERB5DLL "krb5_64.dll"
329 #else
330 #define KERB5DLL "krb5_32.dll"
331 #endif
332 static BOOL
333 IsKrb5Available()
334 {
335     static HINSTANCE hKrb5DLL = 0;
336
337     if ( hKrb5DLL )
338         return TRUE;
339
340     hKrb5DLL = LoadLibrary(KERB5DLL);
341     if (hKrb5DLL) {
342         if (!LoadFuncs(KERB5DLL, krb5_fi, 0, 0, 1, 0, 0))
343         {
344             FreeLibrary(hKrb5DLL);
345             hKrb5DLL = 0;
346             return FALSE;
347         }
348         return TRUE;
349     }
350     return FALSE;
351 }
352
353 static BOOL
354 GetLSAPrincipalName(char * szUser, DWORD *dwSize)
355 {
356     krb5_context   ctx = 0;
357     krb5_error_code code;
358     krb5_ccache mslsa_ccache=0;
359     krb5_principal princ = 0;
360     char * pname = 0;
361     BOOL success = 0;
362
363     if (!IsKrb5Available())
364         return FALSE;
365
366     if (code = pkrb5_init_context(&ctx))
367         goto cleanup;
368
369     if (code = pkrb5_cc_resolve(ctx, "MSLSA:", &mslsa_ccache))
370         goto cleanup;
371
372     if (code = pkrb5_cc_get_principal(ctx, mslsa_ccache, &princ))
373         goto cleanup;
374
375     if (code = pkrb5_unparse_name(ctx, princ, &pname))
376         goto cleanup;
377
378     if ( strlen(pname) < *dwSize ) {
379         strncpy(szUser, pname, *dwSize);
380         szUser[*dwSize-1] = '\0';
381         success = 1;
382     }
383     *dwSize = (DWORD)strlen(pname);
384
385   cleanup:
386     if (pname)
387         pkrb5_free_unparsed_name(ctx, pname);
388
389     if (princ)
390         pkrb5_free_principal(ctx, princ);
391
392     if (mslsa_ccache)
393         pkrb5_cc_close(ctx, mslsa_ccache);
394
395     if (ctx)
396         pkrb5_free_context(ctx);
397     return success;
398 }
399
400 static long
401 GetIoctlHandle(char *fileNamep, HANDLE * handlep)
402 {
403     char *drivep;
404     char netbiosName[MAX_NB_NAME_LENGTH];
405     DWORD CurrentState = 0;
406     char  HostName[64] = "";
407     char tbuffer[256]="";
408     HANDLE fh;
409     HKEY hk;
410     char szUser[128] = "";
411     char szClient[MAX_PATH] = "";
412     char szPath[MAX_PATH] = "";
413     NETRESOURCE nr;
414     DWORD res;
415     DWORD ioctlDebug = IoctlDebug();
416     DWORD gle;
417     DWORD dwSize = sizeof(szUser);
418
419     memset(HostName, '\0', sizeof(HostName));
420     gethostname(HostName, sizeof(HostName));
421     if (!DisableServiceManagerCheck() &&
422         GetServiceStatus(HostName, TEXT("TransarcAFSDaemon"), &CurrentState) == NOERROR &&
423         CurrentState != SERVICE_RUNNING)
424         return -1;
425
426     if (fileNamep) {
427         drivep = strchr(fileNamep, ':');
428         if (drivep && (drivep - fileNamep) >= 1) {
429             tbuffer[0] = *(drivep - 1);
430             tbuffer[1] = ':';
431             strcpy(tbuffer + 2, SMB_IOCTL_FILENAME);
432         } else if (fileNamep[0] == fileNamep[1] && 
433                    (fileNamep[0] == '\\' || fileNamep[0] == '/'))
434         {
435             int count = 0, i = 0;
436
437             while (count < 4 && fileNamep[i]) {
438                 tbuffer[i] = fileNamep[i];
439                 if ( tbuffer[i] == '\\' ||
440                      tbuffer[i] == '/')
441                     count++;
442                 i++;
443             }
444             if (fileNamep[i] == 0)
445                 tbuffer[i++] = '\\';
446             tbuffer[i] = 0;
447             strcat(tbuffer, SMB_IOCTL_FILENAME);
448         } else {
449             char curdir[256]="";
450
451             GetCurrentDirectory(sizeof(curdir), curdir);
452             if ( curdir[1] == ':' ) {
453                 tbuffer[0] = curdir[0];
454                 tbuffer[1] = ':';
455                 strcpy(tbuffer + 2, SMB_IOCTL_FILENAME);
456             } else if (curdir[0] == curdir[1] &&
457                        (curdir[0] == '\\' || curdir[0] == '/')) 
458             {
459                 int count = 0, i = 0;
460
461                 while (count < 4 && curdir[i]) {
462                     tbuffer[i] = curdir[i];
463                     if ( tbuffer[i] == '\\' ||
464                          tbuffer[i] == '/')
465                         count++;
466                     i++;
467                 }
468                 if (tbuffer[i] == 0)
469                     tbuffer[i++] = '\\';
470                 tbuffer[i] = 0;
471                 strcat(tbuffer, SMB_IOCTL_FILENAME_NOSLASH);
472             }
473         }
474     }
475     if (!tbuffer[0]) {
476         /* No file name starting with drive colon specified, use UNC name */
477         lana_GetNetbiosName(netbiosName,LANA_NETBIOS_NAME_FULL);
478         sprintf(tbuffer,"\\\\%s\\all%s",netbiosName,SMB_IOCTL_FILENAME);
479     }
480
481     fflush(stdout);
482     /* now open the file */
483     fh = CreateFile(tbuffer, GENERIC_READ | GENERIC_WRITE,
484                     FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
485                     FILE_FLAG_WRITE_THROUGH, NULL);
486
487         fflush(stdout);
488
489     if (fh == INVALID_HANDLE_VALUE) {
490         int  gonext = 0;
491
492         gle = GetLastError();
493         if (gle && ioctlDebug ) {
494             char buf[4096];
495
496             if ( FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
497                                NULL,
498                                gle,
499                                MAKELANGID(LANG_ENGLISH,SUBLANG_ENGLISH_US),
500                                buf,
501                                4096,
502                                (va_list *) NULL
503                                ) )
504             {
505                 fprintf(stderr,"pioctl CreateFile(%s) failed: 0x%X\r\n\t[%s]\r\n",
506                         tbuffer,gle,buf);
507             }
508         }
509
510         lana_GetNetbiosName(szClient, LANA_NETBIOS_NAME_FULL);
511
512         if (RegOpenKey (HKEY_CURRENT_USER, 
513                          TEXT("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer"), &hk) == 0)
514         {
515             DWORD dwType = REG_SZ;
516             RegQueryValueEx (hk, TEXT("Logon User Name"), NULL, &dwType, (PBYTE)szUser, &dwSize);
517             RegCloseKey (hk);
518         }
519
520         if ( szUser[0] ) {
521             if ( ioctlDebug )
522                 fprintf(stderr, "pioctl Explorer logon user: [%s]\r\n",szUser);
523
524             sprintf(szPath, "\\\\%s", szClient);
525             memset (&nr, 0x00, sizeof(NETRESOURCE));
526             nr.dwType=RESOURCETYPE_DISK;
527             nr.lpLocalName=0;
528             nr.lpRemoteName=szPath;
529             res = WNetAddConnection2(&nr,NULL,szUser,0);
530             if (res) {
531                 if ( ioctlDebug ) {
532                     fprintf(stderr, "pioctl WNetAddConnection2(%s,%s) failed: 0x%X\r\n",
533                              szPath,szUser,res);
534                 }
535                 gonext = 1;
536             }
537
538             sprintf(szPath, "\\\\%s\\all", szClient);
539             res = WNetAddConnection2(&nr,NULL,szUser,0);
540             if (res) {
541                 if ( ioctlDebug ) {
542                     fprintf(stderr, "pioctl WNetAddConnection2(%s,%s) failed: 0x%X\r\n",
543                              szPath,szUser,res);
544                 }
545                 gonext = 1;
546             }
547
548             if (gonext)
549                 goto try_lsa_principal;
550
551             fh = CreateFile(tbuffer, GENERIC_READ | GENERIC_WRITE,
552                              FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
553                              FILE_FLAG_WRITE_THROUGH, NULL);
554             fflush(stdout);
555             if (fh == INVALID_HANDLE_VALUE) {
556                 gle = GetLastError();
557                 if (gle && ioctlDebug ) {
558                     char buf[4096];
559
560                     if ( FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
561                                         NULL,
562                                         gle,
563                                         MAKELANGID(LANG_ENGLISH,SUBLANG_ENGLISH_US),
564                                         buf,
565                                         4096,
566                                         (va_list *) NULL
567                                         ) )
568                     {
569                         fprintf(stderr,"pioctl CreateFile(%s) failed: 0x%X\r\n\t[%s]\r\n",
570                                  tbuffer,gle,buf);
571                     }
572                 }
573             }
574         }
575     }
576
577   try_lsa_principal:
578     if (fh == INVALID_HANDLE_VALUE) {
579         int  gonext = 0;
580
581         dwSize = sizeof(szUser);
582         if (GetLSAPrincipalName(szUser, &dwSize)) {
583             if ( ioctlDebug )
584                 fprintf(stderr, "pioctl LSA Principal logon user: [%s]\r\n",szUser);
585
586             sprintf(szPath, "\\\\%s", szClient);
587             memset (&nr, 0x00, sizeof(NETRESOURCE));
588             nr.dwType=RESOURCETYPE_DISK;
589             nr.lpLocalName=0;
590             nr.lpRemoteName=szPath;
591             res = WNetAddConnection2(&nr,NULL,szUser,0);
592             if (res) {
593                 if ( ioctlDebug ) {
594                     fprintf(stderr, "pioctl WNetAddConnection2(%s,%s) failed: 0x%X\r\n",
595                              szPath,szUser,res);
596                 }
597                 gonext = 1;
598             }
599
600             sprintf(szPath, "\\\\%s\\all", szClient);
601             res = WNetAddConnection2(&nr,NULL,szUser,0);
602             if (res) {
603                 if ( ioctlDebug ) {
604                     fprintf(stderr, "pioctl WNetAddConnection2(%s,%s) failed: 0x%X\r\n",
605                              szPath,szUser,res);
606                 }
607                 gonext = 1;
608             }
609
610             if (gonext)
611                 goto try_sam_compat;
612
613             fh = CreateFile(tbuffer, GENERIC_READ | GENERIC_WRITE,
614                              FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
615                              FILE_FLAG_WRITE_THROUGH, NULL);
616             fflush(stdout);
617             if (fh == INVALID_HANDLE_VALUE) {
618                 gle = GetLastError();
619                 if (gle && ioctlDebug ) {
620                     char buf[4096];
621
622                     if ( FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
623                                         NULL,
624                                         gle,
625                                         MAKELANGID(LANG_ENGLISH,SUBLANG_ENGLISH_US),
626                                         buf,
627                                         4096,
628                                         (va_list *) NULL
629                                         ) )
630                     {
631                         fprintf(stderr,"pioctl CreateFile(%s) failed: 0x%X\r\n\t[%s]\r\n",
632                                  tbuffer,gle,buf);
633                     }
634                 }
635             }
636         }
637     }
638
639   try_sam_compat:
640     if ( fh == INVALID_HANDLE_VALUE ) {
641         dwSize = sizeof(szUser);
642         if (GetUserNameEx(NameSamCompatible, szUser, &dwSize)) {
643             if ( ioctlDebug )
644                 fprintf(stderr, "pioctl SamCompatible logon user: [%s]\r\n",szUser);
645
646             sprintf(szPath, "\\\\%s", szClient);
647             memset (&nr, 0x00, sizeof(NETRESOURCE));
648             nr.dwType=RESOURCETYPE_DISK;
649             nr.lpLocalName=0;
650             nr.lpRemoteName=szPath;
651             res = WNetAddConnection2(&nr,NULL,szUser,0);
652             if (res) {
653                 if ( ioctlDebug ) {
654                     fprintf(stderr, "pioctl WNetAddConnection2(%s,%s) failed: 0x%X\r\n",
655                              szPath,szUser,res);
656                 }
657             }
658
659             sprintf(szPath, "\\\\%s\\all", szClient);
660             res = WNetAddConnection2(&nr,NULL,szUser,0);
661             if (res) {
662                 if ( ioctlDebug ) {
663                     fprintf(stderr, "pioctl WNetAddConnection2(%s,%s) failed: 0x%X\r\n",
664                              szPath,szUser,res);
665                 }
666                 return -1;
667             }
668
669             fh = CreateFile(tbuffer, GENERIC_READ | GENERIC_WRITE,
670                              FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
671                              FILE_FLAG_WRITE_THROUGH, NULL);
672             fflush(stdout);
673             if (fh == INVALID_HANDLE_VALUE) {
674                 gle = GetLastError();
675                 if (gle && ioctlDebug ) {
676                     char buf[4096];
677
678                     if ( FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
679                                         NULL,
680                                         gle,
681                                         MAKELANGID(LANG_ENGLISH,SUBLANG_ENGLISH_US),
682                                         buf,
683                                         4096,
684                                         (va_list *) NULL
685                                         ) )
686                     {
687                         fprintf(stderr,"pioctl CreateFile(%s) failed: 0x%X\r\n\t[%s]\r\n",
688                                  tbuffer,gle,buf);
689                     }
690                 }
691                 return -1;
692             }
693         } else {
694             fprintf(stderr, "GetUserNameEx(NameSamCompatible) failed: 0x%X\r\n", GetLastError());
695             return -1;
696         }
697     }
698
699     /* return fh and success code */
700     *handlep = fh;
701     return 0;
702 }
703
704 static long
705 Transceive(HANDLE handle, fs_ioctlRequest_t * reqp)
706 {
707     long rcount;
708     long ioCount;
709     DWORD gle;
710
711     rcount = (long)(reqp->mp - reqp->data);
712     if (rcount <= 0) {
713         if ( IoctlDebug() )
714             fprintf(stderr, "pioctl Transceive rcount <= 0: %d\r\n",rcount);
715         return EINVAL;          /* not supposed to happen */
716     }
717
718     if (!WriteFile(handle, reqp->data, rcount, &ioCount, NULL)) {
719         /* failed to write */
720         gle = GetLastError();
721
722         if ( IoctlDebug() )
723             fprintf(stderr, "pioctl Transceive WriteFile failed: 0x%X\r\n",gle);
724         return gle;
725     }
726
727     if (!ReadFile(handle, reqp->data, sizeof(reqp->data), &ioCount, NULL)) {
728         /* failed to read */
729         gle = GetLastError();
730
731         if ( IoctlDebug() )
732             fprintf(stderr, "pioctl Transceive ReadFile failed: 0x%X\r\n",gle);
733         return gle;
734     }
735
736     reqp->nbytes = ioCount;     /* set # of bytes available */
737     reqp->mp = reqp->data;      /* restart marshalling */
738
739     /* return success */
740     return 0;
741 }
742
743 static long
744 MarshallLong(fs_ioctlRequest_t * reqp, long val)
745 {
746     memcpy(reqp->mp, &val, 4);
747     reqp->mp += 4;
748     return 0;
749 }
750
751 static long
752 UnmarshallLong(fs_ioctlRequest_t * reqp, long *valp)
753 {
754     /* not enough data left */
755     if (reqp->nbytes < 4) {
756         if ( IoctlDebug() )
757             fprintf(stderr, "pioctl UnmarshallLong reqp->nbytes < 4: %d\r\n",
758                      reqp->nbytes);
759         return -1;
760     }
761
762     memcpy(valp, reqp->mp, 4);
763     reqp->mp += 4;
764     reqp->nbytes -= 4;
765     return 0;
766 }
767
768 /* includes marshalling NULL pointer as a null (0 length) string */
769 static long
770 MarshallString(fs_ioctlRequest_t * reqp, char *stringp, int is_utf8)
771 {
772     int count;
773
774     if (stringp)
775         count = (int)strlen(stringp) + 1;/* space required including null */
776     else
777         count = 1;
778
779     if (is_utf8) {
780         count += utf8_prefix_size;
781     }
782
783     /* watch for buffer overflow */
784     if ((reqp->mp - reqp->data) + count > sizeof(reqp->data)) {
785         if ( IoctlDebug() )
786             fprintf(stderr, "pioctl MarshallString buffer overflow\r\n");
787         return -1;
788     }
789
790     if (is_utf8) {
791         memcpy(reqp->mp, utf8_prefix, utf8_prefix_size);
792         reqp->mp += utf8_prefix_size;
793         count -= utf8_prefix_size;
794     }
795
796     if (stringp)
797         memcpy(reqp->mp, stringp, count);
798     else
799         *(reqp->mp) = 0;
800     reqp->mp += count;
801     return 0;
802 }
803
804 /* take a path with a drive letter, possibly relative, and return a full path
805  * without the drive letter.  This is the full path relative to the working
806  * dir for that drive letter.  The input and output paths can be the same.
807  */
808 static long
809 fs_GetFullPath(char *pathp, char *outPathp, long outSize)
810 {
811     char tpath[1000];
812     char origPath[1000];
813     char *firstp;
814     long code;
815     int pathHasDrive;
816     int doSwitch;
817     char newPath[3];
818     char * p;
819
820     if (pathp[0] != 0 && pathp[1] == ':') {
821         /* there's a drive letter there */
822         firstp = pathp + 2;
823         pathHasDrive = 1;
824     } else {
825         firstp = pathp;
826         pathHasDrive = 0;
827     }
828
829     if ( firstp[0] == '\\' && firstp[1] == '\\' || 
830          firstp[0] == '/' && firstp[1] == '/') {
831         /* UNC path - strip off the server and sharename */
832         int i, count;
833         for ( i=2,count=2; count < 4 && firstp[i]; i++ ) {
834             if ( firstp[i] == '\\' || firstp[i] == '/' ) {
835                 count++;
836             }
837         }
838         if ( firstp[i] == 0 ) {
839             strcpy(outPathp,"\\");
840         } else {
841             strcpy(outPathp,&firstp[--i]);
842         }
843         for (p=outPathp ;*p; p++) {
844             if (*p == '/')
845                 *p = '\\';
846         }
847         return 0;
848     } else if (firstp[0] == '\\' || firstp[0] == '/') {
849         /* already an absolute pathname, just copy it back */
850         strcpy(outPathp, firstp);
851         for (p=outPathp ;*p; p++) {
852             if (*p == '/')
853                 *p = '\\';
854         }
855         return 0;
856     }
857
858     GetCurrentDirectory(sizeof(origPath), origPath);
859
860     doSwitch = 0;
861     if (pathHasDrive && (*pathp & ~0x20) != (origPath[0] & ~0x20)) {
862         /* a drive has been specified and it isn't our current drive.
863          * to get path, switch to it first.  Must case-fold drive letters
864          * for user convenience.
865          */
866         doSwitch = 1;
867         newPath[0] = *pathp;
868         newPath[1] = ':';
869         newPath[2] = 0;
870         if (!SetCurrentDirectory(newPath)) {
871             code = GetLastError();
872
873             if ( IoctlDebug() )
874                 fprintf(stderr, "pioctl fs_GetFullPath SetCurrentDirectory(%s) failed: 0x%X\r\n",
875                          newPath, code);
876             return code;
877         }
878     }
879
880     /* now get the absolute path to the current wdir in this drive */
881     GetCurrentDirectory(sizeof(tpath), tpath);
882     if (tpath[1] == ':')
883         strcpy(outPathp, tpath + 2);    /* skip drive letter */
884     else if ( tpath[0] == '\\' && tpath[1] == '\\'||
885               tpath[0] == '/' && tpath[1] == '/') {
886         /* UNC path - strip off the server and sharename */
887         int i, count;
888         for ( i=2,count=2; count < 4 && tpath[i]; i++ ) {
889             if ( tpath[i] == '\\' || tpath[i] == '/' ) {
890                 count++;
891             }
892         }
893         if ( tpath[i] == 0 ) {
894             strcpy(outPathp,"\\");
895         } else {
896             strcpy(outPathp,&tpath[--i]);
897         }
898     } else {
899         /* this should never happen */
900         strcpy(outPathp, tpath);
901     }
902
903     /* if there is a non-null name after the drive, append it */
904     if (*firstp != 0) {
905         int len = (int)strlen(outPathp);
906         if (outPathp[len-1] != '\\' && outPathp[len-1] != '/') 
907             strcat(outPathp, "\\");
908         strcat(outPathp, firstp);
909     }
910
911     /* finally, if necessary, switch back to our home drive letter */
912     if (doSwitch) {
913         SetCurrentDirectory(origPath);
914     }
915
916     for (p=outPathp ;*p; p++) {
917         if (*p == '/')
918             *p = '\\';
919     }
920     return 0;
921 }
922
923 static long
924 pioctl_int(char *pathp, long opcode, struct ViceIoctl *blobp, int follow, int is_utf8)
925 {
926     fs_ioctlRequest_t preq;
927     long code;
928     long temp;
929     char fullPath[1000];
930     HANDLE reqHandle;
931
932     code = GetIoctlHandle(pathp, &reqHandle);
933     if (code) {
934         if (pathp)
935             errno = EINVAL;
936         else
937             errno = ENODEV;
938         return code;
939     }
940
941     /* init the request structure */
942     InitFSRequest(&preq);
943
944     /* marshall the opcode, the path name and the input parameters */
945     MarshallLong(&preq, opcode);
946     /* when marshalling the path, remove the drive letter, since we already
947      * used the drive letter to find the AFS daemon; we don't need it any more.
948      * Eventually we'll expand relative path names here, too, since again, only
949      * we understand those.
950      */
951     if (pathp) {
952         code = fs_GetFullPath(pathp, fullPath, sizeof(fullPath));
953         if (code) {
954             CloseHandle(reqHandle);
955             errno = EINVAL;
956             return code;
957         }
958     } else {
959         strcpy(fullPath, "");
960     }
961
962     MarshallString(&preq, fullPath, is_utf8);
963     if (blobp->in_size) {
964         if (blobp->in_size > sizeof(preq.data) - (preq.mp - preq.data)*sizeof(char)) {
965             errno = E2BIG;
966             return -1;
967         }
968         memcpy(preq.mp, blobp->in, blobp->in_size);
969         preq.mp += blobp->in_size;
970     }
971
972     /* now make the call */
973     code = Transceive(reqHandle, &preq);
974     if (code) {
975         CloseHandle(reqHandle);
976         return code;
977     }
978
979     /* now unmarshall the return value */
980     if (UnmarshallLong(&preq, &temp) != 0) {
981         CloseHandle(reqHandle);
982         return -1;
983     }
984
985     if (temp != 0) {
986         CloseHandle(reqHandle);
987         errno = CMtoUNIXerror(temp);
988         if ( IoctlDebug() )
989             fprintf(stderr, "pioctl temp != 0: 0x%X\r\n",temp);
990         return -1;
991     }
992
993     /* otherwise, unmarshall the output parameters */
994     if (blobp->out_size) {
995         temp = blobp->out_size;
996         if (preq.nbytes < temp)
997             temp = preq.nbytes;
998         memcpy(blobp->out, preq.mp, temp);
999         blobp->out_size = temp;
1000     }
1001
1002     /* and return success */
1003     CloseHandle(reqHandle);
1004     return 0;
1005 }
1006
1007 long
1008 pioctl_utf8(char * pathp, long opcode, struct ViceIoctl * blobp, int follow)
1009 {
1010     return pioctl_int(pathp, opcode, blobp, follow, TRUE);
1011 }
1012
1013 long
1014 pioctl(char * pathp, long opcode, struct ViceIoctl * blobp, int follow)
1015 {
1016     return pioctl_int(pathp, opcode, blobp, follow, FALSE);
1017 }
1018