window-afsifs-20050617
[openafs.git] / src / WINNT / afsd / cm_ioctl.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 <afs/param.h>
11 #include <afs/stds.h>
12
13 #ifndef DJGPP
14 #include <windows.h>
15 #else
16 #include <sys/socket.h>
17 #endif /* !DJGPP */
18 #include <errno.h>
19 #include <stdlib.h>
20 #include <malloc.h>
21 #include <string.h>
22 #include <stdio.h>
23 #include <time.h>
24
25 #include <osi.h>
26
27 #include "afsd.h"
28 #include "afsd_init.h"
29 #include <WINNT\afsreg.h>
30
31 #include "smb.h"
32 #include "cm_server.h"
33
34 #ifndef DJGPP
35 #include <rx/rxkad.h>
36 #include "afsrpc.h"
37 #else
38 #include <rx/rxkad.h>
39 #include "afsrpc95.h"
40 #endif
41
42 #include "cm_rpc.h"
43 #include <strsafe.h>
44 #include <winioctl.h>
45 #include <..\afsrdr\kif.h>
46
47 #ifdef _DEBUG
48 #include <crtdbg.h>
49 #endif
50
51 /* Copied from afs_tokens.h */
52 #define PIOCTL_LOGON    0x1
53 #define MAX_PATH 260
54
55 osi_mutex_t cm_Afsdsbmt_Lock;
56
57 extern afs_int32 cryptall;
58 extern char cm_NetbiosName[];
59
60 extern void afsi_log(char *pattern, ...);
61
62 void cm_InitIoctl(void)
63 {
64     lock_InitializeMutex(&cm_Afsdsbmt_Lock, "AFSDSBMT.INI Access Lock");
65 }
66
67 long cm_FlushFile(cm_scache_t *scp, cm_user_t *userp, cm_req_t *reqp)
68 {
69     long code;
70
71     lock_ObtainWrite(&scp->bufCreateLock);
72     code = buf_FlushCleanPages(scp, userp, reqp);
73         
74     lock_ObtainMutex(&scp->mx);
75     scp->cbServerp = NULL;
76     scp->cbExpires = 0;
77     cm_dnlcPurgedp(scp);
78     cm_dnlcPurgevp(scp);
79     cm_FreeAllACLEnts(scp);
80     lock_ReleaseMutex(&scp->mx);
81
82     lock_ReleaseWrite(&scp->bufCreateLock);
83     return code;
84 }
85
86 /*
87  * cm_ResetACLCache -- invalidate ACL info for a user that has just
88  *                      obtained or lost tokens
89  */
90 void cm_ResetACLCache(cm_user_t *userp)
91 {
92     cm_scache_t *scp;
93     int hash;
94
95     lock_ObtainWrite(&cm_scacheLock);
96     for (hash=0; hash < cm_data.hashTableSize; hash++) {
97         for (scp=cm_data.hashTablep[hash]; scp; scp=scp->nextp) {
98             cm_HoldSCacheNoLock(scp);
99             lock_ReleaseWrite(&cm_scacheLock);
100             lock_ObtainMutex(&scp->mx);
101             cm_InvalidateACLUser(scp, userp);
102             lock_ReleaseMutex(&scp->mx);
103             lock_ObtainWrite(&cm_scacheLock);
104             cm_ReleaseSCacheNoLock(scp);
105         }
106     }
107     lock_ReleaseWrite(&cm_scacheLock);
108 }       
109
110 /*
111  *  TranslateExtendedChars - This is a fix for TR 54482.
112  *
113  *  If an extended character (80 - FF) is entered into a file
114  *  or directory name in Windows, the character is translated
115  *  into the OEM character map before being passed to us.  Why
116  *  this occurs is unknown.  Our pioctl functions must match
117  *  this translation for paths given via our own commands (like
118  *  fs).  If we do not do this, then we will try to perform an
119  *  operation on a non-translated path, which we will fail to 
120  *  find, since the path was created with the translated chars.
121  *  This function performs the required translation.
122  */
123 void TranslateExtendedChars(char *str)
124 {
125 #ifdef DJGPP
126     char *p;
127 #endif
128
129     if (!str || !*str)
130         return;
131
132 #ifndef DJGPP
133     CharToOem(str, str);
134 #else
135     p = str;
136     while (*p) *p++ &= 0x7f;  /* turn off high bit; probably not right */
137 #endif
138 }
139         
140 /* parse the passed-in file name and do a namei on it.  If we fail,
141  * return an error code, otherwise return the vnode located in *scpp.
142  */
143 long cm_ParseIoctlPath(smb_ioctl_t *ioctlp, cm_user_t *userp, cm_req_t *reqp,
144         cm_scache_t **scpp)
145 {
146     long code, length;
147     cm_scache_t *substRootp;
148     char * relativePath = ioctlp->inDatap, absRoot[100];
149         wchar_t absRoot_w[100];
150         HANDLE rootDir;
151
152     /* This is usually the file name, but for StatMountPoint it is the path. */
153     /* ioctlp->inDatap can be either of the form:
154      *    \path\.
155      *    \path\file
156      *    \\netbios-name\submount\path\.
157      *    \\netbios-name\submount\path\file
158      */
159     TranslateExtendedChars(relativePath);
160
161 #ifdef AFSIFS
162     /* we have passed the whole path, including the afs prefix (pioctl_nt.c modified) */
163 #if 0
164     /*_asm int 3; */
165     sprintf(absRoot, "%c:", relativePath[0]);
166     rootDir = CreateFile(absRoot, 0, 0, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
167
168     if (!DeviceIoControl(rootDir, IOCTL_AFSRDR_GET_PATH, NULL, 0, absRoot_w, 100*sizeof(wchar_t), &length, NULL))
169     {
170     CloseHandle(rootDir);
171     return CM_ERROR_NOSUCHPATH;
172     }
173     CloseHandle(rootDir);
174
175     ifs_ConvertFileName(absRoot_w, length/sizeof(wchar_t), absRoot, 100);
176 #endif
177 #if 0
178     switch (relativePath[0])                                    /* FIXFIX */
179     {
180     case 'y':
181     case 'Y':
182         absRoot = "\\ericjw\\test";                     /* should use drivemap */
183     }
184 #endif
185     code = cm_NameI(cm_data.rootSCachep, relativePath,
186                      CM_FLAG_CASEFOLD | CM_FLAG_FOLLOW,
187                      userp, ""/*absRoot*//*ioctlp->tidPathp*/, reqp, scpp);
188
189     if (code)
190         return code;
191
192     /* # of bytes of path */
193     code = strlen(ioctlp->inDatap) + 1;
194     ioctlp->inDatap += code;
195
196     /* This is usually nothing, but for StatMountPoint it is the file name. */
197     TranslateExtendedChars(ioctlp->inDatap);
198
199     return 0;
200 #endif /* AFSIFS */
201
202     if (relativePath[0] == relativePath[1] &&
203          relativePath[1] == '\\' && 
204          !_strnicmp(cm_NetbiosName,relativePath+2,strlen(cm_NetbiosName))) 
205     {
206         char shareName[256];
207         char *sharePath;
208         int shareFound, i;
209
210         /* We may have found a UNC path. 
211          * If the first component is the NetbiosName,
212          * then throw out the second component (the submount)
213          * since it had better expand into the value of ioctl->tidPathp
214          */
215         char * p;
216         p = relativePath + 2 + strlen(cm_NetbiosName) + 1;
217         if ( !_strnicmp("all", p, 3) )
218             p += 4;
219
220         for (i = 0; *p && *p != '\\'; i++,p++ ) {
221             shareName[i] = *p;
222         }
223         p++;                    /* skip past trailing slash */
224         shareName[i] = 0;       /* terminate string */
225
226         shareFound = smb_FindShare(ioctlp->fidp->vcp, ioctlp->uidp, shareName, &sharePath);
227         if ( shareFound ) {
228             /* we found a sharename, therefore use the resulting path */
229             code = cm_NameI(cm_data.rootSCachep, ioctlp->prefix->data,
230                              CM_FLAG_CASEFOLD | CM_FLAG_FOLLOW,
231                              userp, sharePath, reqp, &substRootp);
232             free(sharePath);
233             if (code) 
234                 return code;
235
236             code = cm_NameI(substRootp, p, CM_FLAG_CASEFOLD | CM_FLAG_FOLLOW,
237                              userp, NULL, reqp, scpp);
238             if (code) 
239                 return code;
240         } else {
241             /* otherwise, treat the name as a cellname mounted off the afs root.
242              * This requires that we reconstruct the shareName string with 
243              * leading and trailing slashes.
244              */
245             p = relativePath + 2 + strlen(cm_NetbiosName) + 1;
246             if ( !_strnicmp("all", p, 3) )
247                 p += 4;
248
249             shareName[0] = '/';
250             for (i = 1; *p && *p != '\\'; i++,p++ ) {
251                 shareName[i] = *p;
252             }
253             p++;                    /* skip past trailing slash */
254             shareName[i++] = '/';       /* add trailing slash */
255             shareName[i] = 0;       /* terminate string */
256
257
258             code = cm_NameI(cm_data.rootSCachep, ioctlp->prefix->data,
259                              CM_FLAG_CASEFOLD | CM_FLAG_FOLLOW,
260                              userp, shareName, reqp, &substRootp);
261             if (code) 
262                 return code;
263
264             code = cm_NameI(substRootp, p, CM_FLAG_CASEFOLD | CM_FLAG_FOLLOW,
265                             userp, NULL, reqp, scpp);
266             if (code) 
267                 return code;
268         }
269     } else {
270         code = cm_NameI(cm_data.rootSCachep, ioctlp->prefix->data,
271                          CM_FLAG_CASEFOLD | CM_FLAG_FOLLOW,
272                          userp, ioctlp->tidPathp, reqp, &substRootp);
273         if (code) 
274             return code;
275         
276         code = cm_NameI(substRootp, relativePath, CM_FLAG_CASEFOLD | CM_FLAG_FOLLOW,
277                          userp, NULL, reqp, scpp);
278         if (code) 
279             return code;
280     }
281
282     /* # of bytes of path */
283     code = strlen(ioctlp->inDatap) + 1;
284     ioctlp->inDatap += code;
285
286     /* This is usually nothing, but for StatMountPoint it is the file name. */
287     TranslateExtendedChars(ioctlp->inDatap);
288
289     /* and return success */
290     return 0;
291 }
292
293 void cm_SkipIoctlPath(smb_ioctl_t *ioctlp)
294 {
295     long temp;
296         
297     temp = strlen(ioctlp->inDatap) + 1;
298     ioctlp->inDatap += temp;
299 }       
300
301
302 /* format the specified path to look like "/afs/<cellname>/usr", by
303  * adding "/afs" (if necessary) in front, changing any \'s to /'s, and
304  * removing any trailing "/"'s. One weirdo caveat: "/afs" will be
305  * intentionally returned as "/afs/"--this makes submount manipulation
306  * easier (because we can always jump past the initial "/afs" to find
307  * the AFS path that should be written into afsdsbmt.ini).
308  */
309 void cm_NormalizeAfsPath(char *outpathp, long outlen, char *inpathp)
310 {
311     char *cp;
312     char bslash_mountRoot[256];
313        
314     strncpy(bslash_mountRoot, cm_mountRoot, sizeof(bslash_mountRoot) - 1);
315     bslash_mountRoot[0] = '\\';
316        
317     if (!strnicmp (inpathp, cm_mountRoot, strlen(cm_mountRoot)))
318         StringCbCopy(outpathp, outlen, inpathp);
319     else if (!strnicmp (inpathp, bslash_mountRoot, strlen(bslash_mountRoot)))
320         StringCbCopy(outpathp, outlen, inpathp);
321     else if ((inpathp[0] == '/') || (inpathp[0] == '\\'))
322         StringCbPrintfA(outpathp, outlen, "%s%s", cm_mountRoot, inpathp);
323     else // inpathp looks like "<cell>/usr"
324         StringCbPrintfA(outpathp, outlen, "%s/%s", cm_mountRoot, inpathp);
325
326     for (cp = outpathp; *cp != 0; ++cp) {
327         if (*cp == '\\')
328             *cp = '/';
329     }       
330
331     if (strlen(outpathp) && (outpathp[strlen(outpathp)-1] == '/')) {
332         outpathp[strlen(outpathp)-1] = 0;
333     }
334
335     if (!strcmpi (outpathp, cm_mountRoot)) {
336         StringCbCopy(outpathp, outlen, cm_mountRoot);
337     }
338 }
339
340 #define LEAF_SIZE 256
341 /* parse the passed-in file name and do a namei on its parent.  If we fail,
342  * return an error code, otherwise return the vnode located in *scpp.
343  */
344 long cm_ParseIoctlParent(smb_ioctl_t *ioctlp, cm_user_t *userp, cm_req_t *reqp,
345                          cm_scache_t **scpp, char *leafp)
346 {
347     long code;
348     char tbuffer[1024];
349     char *tp, *jp;
350     cm_scache_t *substRootp;
351
352     StringCbCopyA(tbuffer, sizeof(tbuffer), ioctlp->inDatap);
353     tp = strrchr(tbuffer, '\\');
354     jp = strrchr(tbuffer, '/');
355     if (!tp)
356         tp = jp;
357     else if (jp && (tp - tbuffer) < (jp - tbuffer))
358         tp = jp;
359     if (!tp) {
360         StringCbCopyA(tbuffer, sizeof(tbuffer), "\\");
361         if (leafp) 
362             StringCbCopyA(leafp, LEAF_SIZE, ioctlp->inDatap);
363     }
364     else {
365         *tp = 0;
366         if (leafp) 
367             StringCbCopyA(leafp, LEAF_SIZE, tp+1);
368     }   
369
370     if (tbuffer[0] == tbuffer[1] &&
371         tbuffer[1] == '\\' && 
372         !_strnicmp(cm_NetbiosName,tbuffer+2,strlen(cm_NetbiosName))) 
373     {
374         char shareName[256];
375         char *sharePath;
376         int shareFound, i;
377
378         /* We may have found a UNC path. 
379          * If the first component is the NetbiosName,
380          * then throw out the second component (the submount)
381          * since it had better expand into the value of ioctl->tidPathp
382          */
383         char * p;
384         p = tbuffer + 2 + strlen(cm_NetbiosName) + 1;
385         if ( !_strnicmp("all", p, 3) )
386             p += 4;
387
388         for (i = 0; *p && *p != '\\'; i++,p++ ) {
389             shareName[i] = *p;
390         }
391         p++;                    /* skip past trailing slash */
392         shareName[i] = 0;       /* terminate string */
393
394         shareFound = smb_FindShare(ioctlp->fidp->vcp, ioctlp->uidp, shareName, &sharePath);
395         if ( shareFound ) {
396             /* we found a sharename, therefore use the resulting path */
397             code = cm_NameI(cm_data.rootSCachep, ioctlp->prefix->data,
398                              CM_FLAG_CASEFOLD | CM_FLAG_FOLLOW,
399                              userp, sharePath, reqp, &substRootp);
400             free(sharePath);
401             if (code) return code;
402
403             code = cm_NameI(substRootp, p, CM_FLAG_CASEFOLD | CM_FLAG_FOLLOW,
404                              userp, NULL, reqp, scpp);
405             if (code) return code;
406         } else {
407             /* otherwise, treat the name as a cellname mounted off the afs root.
408              * This requires that we reconstruct the shareName string with 
409              * leading and trailing slashes.
410              */
411             p = tbuffer + 2 + strlen(cm_NetbiosName) + 1;
412             if ( !_strnicmp("all", p, 3) )
413                 p += 4;
414
415             shareName[0] = '/';
416             for (i = 1; *p && *p != '\\'; i++,p++ ) {
417                 shareName[i] = *p;
418             }
419             p++;                    /* skip past trailing slash */
420             shareName[i++] = '/';       /* add trailing slash */
421             shareName[i] = 0;       /* terminate string */
422
423             code = cm_NameI(cm_data.rootSCachep, ioctlp->prefix->data,
424                              CM_FLAG_CASEFOLD | CM_FLAG_FOLLOW,
425                              userp, shareName, reqp, &substRootp);
426             if (code) return code;
427
428             code = cm_NameI(substRootp, p, CM_FLAG_CASEFOLD | CM_FLAG_FOLLOW,
429                             userp, NULL, reqp, scpp);
430             if (code) return code;
431         }
432     } else {
433         code = cm_NameI(cm_data.rootSCachep, ioctlp->prefix->data,
434                         CM_FLAG_CASEFOLD | CM_FLAG_FOLLOW,
435                         userp, ioctlp->tidPathp, reqp, &substRootp);
436         if (code) return code;
437
438         code = cm_NameI(substRootp, tbuffer, CM_FLAG_FOLLOW,
439                         userp, NULL, reqp, scpp);
440         if (code) return code;
441     }
442
443     /* # of bytes of path */
444     code = strlen(ioctlp->inDatap) + 1;
445     ioctlp->inDatap += code;
446
447     /* and return success */
448     return 0;
449 }
450
451 long cm_IoctlGetACL(smb_ioctl_t *ioctlp, cm_user_t *userp)
452 {
453     cm_conn_t *connp;
454     cm_scache_t *scp;
455     AFSOpaque acl;
456     AFSFetchStatus fileStatus;
457     AFSVolSync volSync;
458     long code;
459     AFSFid fid;
460     int tlen;
461     cm_req_t req;
462     struct rx_connection * callp;
463
464     cm_InitReq(&req);
465
466     code = cm_ParseIoctlPath(ioctlp, userp, &req, &scp);
467     if (code) return code;
468
469     /* now make the get acl call */
470     fid.Volume = scp->fid.volume;
471     fid.Vnode = scp->fid.vnode;
472     fid.Unique = scp->fid.unique;
473     do {
474         acl.AFSOpaque_val = ioctlp->outDatap;
475         acl.AFSOpaque_len = 0;
476         code = cm_Conn(&scp->fid, userp, &req, &connp);
477         if (code) continue;
478
479         callp = cm_GetRxConn(connp);
480         code = RXAFS_FetchACL(callp, &fid, &acl, &fileStatus, &volSync);
481         rx_PutConnection(callp);
482
483     } while (cm_Analyze(connp, userp, &req, &scp->fid, &volSync, NULL, NULL, code));
484     code = cm_MapRPCError(code, &req);
485     cm_ReleaseSCache(scp);
486
487     if (code) return code;
488
489     /* skip over return data */
490     tlen = strlen(ioctlp->outDatap) + 1;
491     ioctlp->outDatap += tlen;
492
493     /* and return success */
494     return 0;
495 }
496
497 long cm_IoctlGetFileCellName(struct smb_ioctl *ioctlp, struct cm_user *userp)
498 {
499     long code;
500     cm_scache_t *scp;
501     cm_cell_t *cellp;
502     cm_req_t req;
503
504     cm_InitReq(&req);
505
506     code = cm_ParseIoctlPath(ioctlp, userp, &req, &scp);
507     if (code) return code;
508
509 #ifdef AFS_FREELANCE_CLIENT
510     if ( cm_freelanceEnabled && 
511          scp->fid.cell==AFS_FAKE_ROOT_CELL_ID &&
512          scp->fid.volume==AFS_FAKE_ROOT_VOL_ID &&
513          scp->fid.vnode==0x1 && scp->fid.unique==0x1 ) {
514         StringCbCopyA(ioctlp->outDatap, 999999, "Freelance.Local.Root");
515         ioctlp->outDatap += strlen(ioctlp->outDatap) + 1;
516         code = 0;
517     } else 
518 #endif /* AFS_FREELANCE_CLIENT */
519     {
520         cellp = cm_FindCellByID(scp->fid.cell);
521         if (cellp) {
522             StringCbCopyA(ioctlp->outDatap, 999999, cellp->name);
523             ioctlp->outDatap += strlen(ioctlp->outDatap) + 1;
524             code = 0;
525         }
526         else 
527             code = CM_ERROR_NOSUCHCELL;
528     }
529
530     cm_ReleaseSCache(scp);
531     return code;
532 }
533
534 long cm_IoctlSetACL(struct smb_ioctl *ioctlp, struct cm_user *userp)
535 {
536     cm_conn_t *connp;
537     cm_scache_t *scp;
538     AFSOpaque acl;
539     AFSFetchStatus fileStatus;
540     AFSVolSync volSync;
541     long code;
542     AFSFid fid;
543     cm_req_t req;
544     struct rx_connection * callp;
545
546     cm_InitReq(&req);
547
548     code = cm_ParseIoctlPath(ioctlp, userp, &req, &scp);
549     if (code) return code;
550         
551     /* now make the get acl call */
552     fid.Volume = scp->fid.volume;
553     fid.Vnode = scp->fid.vnode;
554     fid.Unique = scp->fid.unique;
555     do {
556         acl.AFSOpaque_val = ioctlp->inDatap;
557         acl.AFSOpaque_len = strlen(ioctlp->inDatap)+1;
558         code = cm_Conn(&scp->fid, userp, &req, &connp);
559         if (code) continue;
560
561         callp = cm_GetRxConn(connp);
562         code = RXAFS_StoreACL(callp, &fid, &acl, &fileStatus, &volSync);
563         rx_PutConnection(callp);
564
565     } while (cm_Analyze(connp, userp, &req, &scp->fid, &volSync, NULL, NULL, code));
566     code = cm_MapRPCError(code, &req);
567
568     /* invalidate cache info, since we just trashed the ACL cache */
569     lock_ObtainMutex(&scp->mx);
570     cm_DiscardSCache(scp);
571     lock_ReleaseMutex(&scp->mx);
572
573     cm_ReleaseSCache(scp);
574
575     return code;
576 }
577
578 long cm_IoctlFlushVolume(struct smb_ioctl *ioctlp, struct cm_user *userp)
579 {
580     long code;
581     cm_scache_t *scp;
582     unsigned long volume;
583     int i;
584     cm_req_t req;
585
586     cm_InitReq(&req);
587
588     code = cm_ParseIoctlPath(ioctlp, userp, &req, &scp);
589     if (code) return code;
590         
591     volume = scp->fid.volume;
592     cm_ReleaseSCache(scp);
593
594     lock_ObtainWrite(&cm_scacheLock);
595     for (i=0; i<cm_data.hashTableSize; i++) {
596         for (scp = cm_data.hashTablep[i]; scp; scp = scp->nextp) {
597             if (scp->fid.volume == volume) {
598                 cm_HoldSCacheNoLock(scp);
599                 lock_ReleaseWrite(&cm_scacheLock);
600
601                 /* now flush the file */
602                 code = cm_FlushFile(scp, userp, &req);
603                 if ( code )
604                     afsi_log("cm_FlushFile returns error: [%x]",code);
605                 lock_ObtainWrite(&cm_scacheLock);
606                 cm_ReleaseSCacheNoLock(scp);
607             }
608         }
609     }
610     lock_ReleaseWrite(&cm_scacheLock);
611
612     return code;
613 }
614
615 long cm_IoctlFlushFile(struct smb_ioctl *ioctlp, struct cm_user *userp)
616 {
617     long code;
618     cm_scache_t *scp;
619     cm_req_t req;
620
621     cm_InitReq(&req);
622
623     code = cm_ParseIoctlPath(ioctlp, userp, &req, &scp);
624     if (code) return code;
625         
626     cm_FlushFile(scp, userp, &req);
627     cm_ReleaseSCache(scp);
628
629     return 0;
630 }
631
632 long cm_IoctlSetVolumeStatus(struct smb_ioctl *ioctlp, struct cm_user *userp)
633 {
634     cm_scache_t *scp;
635     char volName[32];
636     char offLineMsg[256];
637     char motd[256];
638     cm_conn_t *tcp;
639     long code;
640     AFSFetchVolumeStatus volStat;
641     AFSStoreVolumeStatus storeStat;
642     cm_volume_t *tvp;
643     char *cp;
644     cm_cell_t *cellp;
645     cm_req_t req;
646     struct rx_connection * callp;
647
648     cm_InitReq(&req);
649
650     code = cm_ParseIoctlPath(ioctlp, userp, &req, &scp);
651     if (code) return code;
652
653     cellp = cm_FindCellByID(scp->fid.cell);
654     osi_assert(cellp);
655
656     if (scp->flags & CM_SCACHEFLAG_RO) {
657         cm_ReleaseSCache(scp);
658         return CM_ERROR_READONLY;
659     }
660
661     code = cm_GetVolumeByID(cellp, scp->fid.volume, userp, &req, &tvp);
662     if (code) {
663         cm_ReleaseSCache(scp);
664         return code;
665     }
666
667     /* Copy the junk out, using cp as a roving pointer. */
668     cp = ioctlp->inDatap;
669     memcpy((char *)&volStat, cp, sizeof(AFSFetchVolumeStatus));
670     cp += sizeof(AFSFetchVolumeStatus);
671     StringCbCopyA(volName, sizeof(volName), cp);
672     cp += strlen(volName)+1;
673     StringCbCopyA(offLineMsg, sizeof(offLineMsg), cp);
674     cp +=  strlen(offLineMsg)+1;
675     StringCbCopyA(motd, sizeof(motd), cp);
676     storeStat.Mask = 0;
677     if (volStat.MinQuota != -1) {
678         storeStat.MinQuota = volStat.MinQuota;
679         storeStat.Mask |= AFS_SETMINQUOTA;
680     }
681     if (volStat.MaxQuota != -1) {
682         storeStat.MaxQuota = volStat.MaxQuota;
683         storeStat.Mask |= AFS_SETMAXQUOTA;
684     }
685
686     do {
687         code = cm_Conn(&scp->fid, userp, &req, &tcp);
688         if (code) continue;
689
690         callp = cm_GetRxConn(tcp);
691         code = RXAFS_SetVolumeStatus(callp, scp->fid.volume,
692                                       &storeStat, volName, offLineMsg, motd);
693         rx_PutConnection(callp);
694
695     } while (cm_Analyze(tcp, userp, &req, &scp->fid, NULL, NULL, NULL, code));
696     code = cm_MapRPCError(code, &req);
697
698     /* return on failure */
699     cm_ReleaseSCache(scp);
700     if (code) {
701         return code;
702     }
703
704     /* we are sending parms back to make compat. with prev system.  should
705      * change interface later to not ask for current status, just set
706      * new status
707      */
708     cp = ioctlp->outDatap;
709     memcpy(cp, (char *)&volStat, sizeof(VolumeStatus));
710     cp += sizeof(VolumeStatus);
711     StringCbCopyA(cp, 999999, volName);
712     cp += strlen(volName)+1;
713     StringCbCopyA(cp, 999999, offLineMsg);
714     cp += strlen(offLineMsg)+1;
715     StringCbCopyA(cp, 999999, motd);
716     cp += strlen(motd)+1;
717
718     /* now return updated return data pointer */
719     ioctlp->outDatap = cp;
720
721     return 0;
722 }       
723
724 long cm_IoctlGetVolumeStatus(struct smb_ioctl *ioctlp, struct cm_user *userp)
725 {
726     char volName[32];
727     cm_scache_t *scp;
728     char offLineMsg[256];
729     char motd[256];
730     cm_conn_t *tcp;
731     register long code;
732     AFSFetchVolumeStatus volStat;
733     register char *cp;
734     char *Name;
735     char *OfflineMsg;
736     char *MOTD;
737     cm_req_t req;
738     struct rx_connection * callp;
739
740     cm_InitReq(&req);
741
742     code = cm_ParseIoctlPath(ioctlp, userp, &req, &scp);
743     if (code) return code;
744
745     Name = volName;
746     OfflineMsg = offLineMsg;
747     MOTD = motd;
748     do {
749         code = cm_Conn(&scp->fid, userp, &req, &tcp);
750         if (code) continue;
751
752         callp = cm_GetRxConn(tcp);
753         code = RXAFS_GetVolumeStatus(callp, scp->fid.volume,
754                                       &volStat, &Name, &OfflineMsg, &MOTD);
755         rx_PutConnection(callp);
756
757     } while (cm_Analyze(tcp, userp, &req, &scp->fid, NULL, NULL, NULL, code));
758     code = cm_MapRPCError(code, &req);
759
760     cm_ReleaseSCache(scp);
761     if (code) return code;
762
763     /* Copy all this junk into msg->im_data, keeping track of the lengths. */
764     cp = ioctlp->outDatap;
765     memcpy(cp, (char *)&volStat, sizeof(AFSFetchVolumeStatus));
766     cp += sizeof(AFSFetchVolumeStatus);
767     StringCbCopyA(cp, 999999, volName);
768     cp += strlen(volName)+1;
769     StringCbCopyA(cp, 999999, offLineMsg);
770     cp += strlen(offLineMsg)+1;
771     StringCbCopyA(cp, 999999, motd);
772     cp += strlen(motd)+1;
773
774     /* return new size */
775     ioctlp->outDatap = cp;
776
777     return 0;
778 }
779
780 long cm_IoctlWhereIs(struct smb_ioctl *ioctlp, struct cm_user *userp)
781 {
782     long code;
783     cm_scache_t *scp;
784     cm_cell_t *cellp;
785     cm_volume_t *tvp;
786     cm_serverRef_t **tsrpp, *current;
787     cm_server_t *tsp;
788     unsigned long volume;
789     char *cp;
790     cm_req_t req;
791
792     cm_InitReq(&req);
793
794     code = cm_ParseIoctlPath(ioctlp, userp, &req, &scp);
795     if (code) return code;
796         
797     volume = scp->fid.volume;
798
799     cellp = cm_FindCellByID(scp->fid.cell);
800     osi_assert(cellp);
801
802     cm_ReleaseSCache(scp);
803
804     code = cm_GetVolumeByID(cellp, volume, userp, &req, &tvp);
805     if (code) return code;
806         
807     cp = ioctlp->outDatap;
808         
809     lock_ObtainMutex(&tvp->mx);
810     tsrpp = cm_GetVolServers(tvp, volume);
811     lock_ObtainRead(&cm_serverLock);
812     for (current = *tsrpp; current; current = current->next) {
813         tsp = current->server;
814         memcpy(cp, (char *)&tsp->addr.sin_addr.s_addr, sizeof(long));
815         cp += sizeof(long);
816     }
817     lock_ReleaseRead(&cm_serverLock);
818     cm_FreeServerList(tsrpp);
819     lock_ReleaseMutex(&tvp->mx);
820
821     /* still room for terminating NULL, add it on */
822     volume = 0; /* reuse vbl */
823     memcpy(cp, (char *)&volume, sizeof(long));
824     cp += sizeof(long);
825
826     ioctlp->outDatap = cp;
827     cm_PutVolume(tvp);
828     return 0;
829 }       
830
831 long cm_IoctlStatMountPoint(struct smb_ioctl *ioctlp, struct cm_user *userp)
832 {
833     long code;
834     cm_scache_t *dscp;
835     cm_scache_t *scp;
836     char *cp;
837     cm_req_t req;
838
839     cm_InitReq(&req);
840
841     code = cm_ParseIoctlPath(ioctlp, userp, &req, &dscp);
842     if (code) return code;
843
844     cp = ioctlp->inDatap;
845
846     code = cm_Lookup(dscp, cp, CM_FLAG_NOMOUNTCHASE, userp, &req, &scp);
847     cm_ReleaseSCache(dscp);
848     if (code) return code;
849         
850     lock_ObtainMutex(&scp->mx);
851
852     /* now check that this is a real mount point */
853     if (scp->fileType != CM_SCACHETYPE_MOUNTPOINT) {
854         lock_ReleaseMutex(&scp->mx);
855         cm_ReleaseSCache(scp);
856         return CM_ERROR_INVAL;
857     }
858
859     code = cm_ReadMountPoint(scp, userp, &req);
860     if (code == 0) {
861         cp = ioctlp->outDatap;
862         StringCbCopyA(cp, 999999, scp->mountPointStringp);
863         cp += strlen(cp) + 1;
864         ioctlp->outDatap = cp;
865     }
866     lock_ReleaseMutex(&scp->mx);
867     cm_ReleaseSCache(scp);
868
869     return code;
870 }       
871
872 long cm_IoctlDeleteMountPoint(struct smb_ioctl *ioctlp, struct cm_user *userp)
873 {
874     long code;
875     cm_scache_t *dscp;
876     cm_scache_t *scp;
877     char *cp;
878     cm_req_t req;
879
880     cm_InitReq(&req);
881
882     code = cm_ParseIoctlPath(ioctlp, userp, &req, &dscp);
883     if (code) return code;
884
885     cp = ioctlp->inDatap;
886
887     code = cm_Lookup(dscp, cp, CM_FLAG_NOMOUNTCHASE, userp, &req, &scp);
888         
889     /* if something went wrong, bail out now */
890     if (code) {
891         goto done;
892     }
893         
894     lock_ObtainMutex(&scp->mx);
895     code = cm_SyncOp(scp, NULL, userp, &req, 0,
896                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
897     if (code) {     
898         lock_ReleaseMutex(&scp->mx);
899         cm_ReleaseSCache(scp);
900         goto done;
901     }
902
903     /* now check that this is a real mount point */
904     if (scp->fileType != CM_SCACHETYPE_MOUNTPOINT) {
905         lock_ReleaseMutex(&scp->mx);
906         cm_ReleaseSCache(scp);
907         code = CM_ERROR_INVAL;
908         goto done;
909     }
910
911     /* time to make the RPC, so drop the lock */
912     lock_ReleaseMutex(&scp->mx);
913     cm_ReleaseSCache(scp);
914
915     /* easier to do it this way */
916     code = cm_Unlink(dscp, cp, userp, &req);
917     if (code == 0 && (dscp->flags & CM_SCACHEFLAG_ANYWATCH))
918         smb_NotifyChange(FILE_ACTION_REMOVED,
919                           FILE_NOTIFY_CHANGE_DIR_NAME,
920                           dscp, cp, NULL, TRUE);
921
922   done:
923     cm_ReleaseSCache(dscp);
924     return code;
925 }
926
927 long cm_IoctlCheckServers(struct smb_ioctl *ioctlp, struct cm_user *userp)
928 {
929     cm_cell_t *cellp;
930     chservinfo_t csi;
931     char *tp;
932     char *cp;
933     long temp;
934     cm_server_t *tsp;
935     int haveCell;
936         
937     cm_SkipIoctlPath(ioctlp);   /* we don't care about the path */
938     tp = ioctlp->inDatap;
939     haveCell = 0;
940
941     memcpy(&temp, tp, sizeof(temp));
942     if (temp == 0x12345678) {   /* For afs3.3 version */
943         memcpy(&csi, tp, sizeof(csi));
944         if (csi.tinterval >= 0) {
945             cp = ioctlp->outDatap;
946             memcpy(cp, (char *)&cm_daemonCheckInterval, sizeof(long));
947             ioctlp->outDatap += sizeof(long);
948             if (csi.tinterval > 0) {
949                 if (!smb_SUser(userp))
950                     return CM_ERROR_NOACCESS;
951                 cm_daemonCheckInterval = csi.tinterval;
952             }
953             return 0;
954         }
955         if (csi.tsize)
956             haveCell = 1;
957         temp = csi.tflags;
958         cp = csi.tbuffer;
959     } else {    /* For pre afs3.3 versions */
960         memcpy((char *)&temp, ioctlp->inDatap, sizeof(long));
961         ioctlp->inDatap = cp = ioctlp->inDatap + sizeof(long);
962         if (cp - ioctlp->inAllocp < ioctlp->inCopied)   /* still more data available */
963             haveCell = 1;
964     }       
965
966     /* 
967      * 1: fast check, don't contact servers.
968      * 2: local cell only.
969      */
970     if (haveCell) {
971         /* have cell name, too */
972         cellp = cm_GetCell(cp, 0);
973         if (!cellp) return CM_ERROR_NOSUCHCELL;
974     }
975     else cellp = (cm_cell_t *) 0;
976     if (!cellp && (temp & 2)) {
977         /* use local cell */
978         cellp = cm_FindCellByID(1);
979     }
980     if (!(temp & 1)) {  /* if not fast, call server checker routine */
981         /* check down servers */
982         cm_CheckServers(CM_FLAG_CHECKDOWNSERVERS | CM_FLAG_CHECKUPSERVERS,
983                          cellp);
984     }       
985
986     /* now return the current down server list */
987     cp = ioctlp->outDatap;
988     lock_ObtainRead(&cm_serverLock);
989     for (tsp = cm_allServersp; tsp; tsp=tsp->allNextp) {
990         if (cellp && tsp->cellp != cellp) continue;     /* cell spec'd and wrong */
991         if ((tsp->flags & CM_SERVERFLAG_DOWN)
992              && tsp->type == CM_SERVER_FILE) {
993             memcpy(cp, (char *)&tsp->addr.sin_addr.s_addr, sizeof(long));
994             cp += sizeof(long);
995         }
996     }
997     lock_ReleaseRead(&cm_serverLock);
998
999     ioctlp->outDatap = cp;
1000     return 0;
1001 }
1002
1003 long cm_IoctlGag(struct smb_ioctl *ioctlp, struct cm_user *userp)
1004 {
1005     /* we don't print anything superfluous, so we don't support the gag call */
1006     return CM_ERROR_INVAL;
1007 }
1008
1009 long cm_IoctlCheckVolumes(struct smb_ioctl *ioctlp, struct cm_user *userp)
1010 {
1011     cm_CheckVolumes();
1012     return 0;
1013 }       
1014
1015 long cm_IoctlSetCacheSize(struct smb_ioctl *ioctlp, struct cm_user *userp)
1016 {
1017     long temp;
1018     long code;
1019
1020     cm_SkipIoctlPath(ioctlp);
1021
1022     memcpy(&temp, ioctlp->inDatap, sizeof(temp));
1023     if (temp == 0) 
1024         temp = cm_data.buf_nOrigBuffers;
1025     else {
1026         /* temp is in 1K units, convert to # of buffers */
1027         temp = temp / (cm_data.buf_blockSize / 1024);
1028     }       
1029
1030     /* now adjust the cache size */
1031     code = buf_SetNBuffers(temp);
1032
1033     return code;
1034 }
1035
1036 long cm_IoctlTraceControl(struct smb_ioctl *ioctlp, struct cm_user *userp)
1037 {
1038     long inValue;
1039         
1040     cm_SkipIoctlPath(ioctlp);
1041         
1042     memcpy(&inValue, ioctlp->inDatap, sizeof(long));
1043
1044     /* print trace */
1045     if (inValue & 8) {
1046         afsd_ForceTrace(FALSE);
1047         buf_ForceTrace(FALSE);
1048     }
1049         
1050     if (inValue & 2) {
1051         /* set tracing value to low order bit */
1052         if ((inValue & 1) == 0) {
1053             /* disable tracing */
1054             osi_LogDisable(afsd_logp);
1055         }
1056         else {
1057             /* enable tracing */
1058             osi_LogEnable(afsd_logp);
1059         }
1060     }
1061
1062     /* see if we're supposed to do a reset, too */
1063     if (inValue & 4) {
1064         osi_LogReset(afsd_logp);
1065     }
1066
1067     /* and copy out tracing flag */
1068     inValue = afsd_logp->enabled;       /* use as a temp vbl */
1069     memcpy(ioctlp->outDatap, &inValue, sizeof(long));
1070     ioctlp->outDatap += sizeof(long);
1071     return 0;
1072 }       
1073
1074 long cm_IoctlGetCacheParms(struct smb_ioctl *ioctlp, struct cm_user *userp)
1075 {
1076     cm_cacheParms_t parms;
1077
1078     memset(&parms, 0, sizeof(parms));
1079
1080     /* first we get, in 1K units, the cache size */
1081     parms.parms[0] = cm_data.buf_nbuffers * (cm_data.buf_blockSize / 1024);
1082
1083     /* and then the actual # of buffers in use (not in the free list, I guess,
1084      * will be what we do).
1085      */
1086     parms.parms[1] = (cm_data.buf_nbuffers - buf_CountFreeList()) * (cm_data.buf_blockSize / 1024);
1087
1088     memcpy(ioctlp->outDatap, &parms, sizeof(parms));
1089     ioctlp->outDatap += sizeof(parms);
1090
1091     return 0;
1092 }
1093
1094 long cm_IoctlGetCell(struct smb_ioctl *ioctlp, struct cm_user *userp)
1095 {
1096     long whichCell;
1097     long magic = 0;
1098     cm_cell_t *tcellp;
1099     cm_serverRef_t *serverRefp;
1100     cm_server_t *serverp;
1101     long i;
1102     char *cp;
1103     char *tp;
1104     char *basep;
1105
1106     cm_SkipIoctlPath(ioctlp);
1107
1108     tp = ioctlp->inDatap;
1109
1110     memcpy((char *)&whichCell, tp, sizeof(long));
1111     tp += sizeof(long);
1112
1113     /* see if more than one long passed in, ignoring the null pathname (the -1) */
1114     if (ioctlp->inCopied-1 > sizeof(long)) {
1115         memcpy((char *)&magic, tp, sizeof(long));
1116     }
1117
1118     lock_ObtainRead(&cm_cellLock);
1119     for (tcellp = cm_data.allCellsp; tcellp; tcellp = tcellp->nextp) {
1120         if (whichCell == 0) break;
1121         whichCell--;
1122     }
1123     lock_ReleaseRead(&cm_cellLock);
1124     if (tcellp) {
1125         int max = 8;
1126
1127         cp = ioctlp->outDatap;
1128
1129         if (magic == 0x12345678) {
1130             memcpy(cp, (char *)&magic, sizeof(long));
1131             max = 13;
1132         }
1133         memset(cp, 0, max * sizeof(long));
1134         basep = cp;
1135         lock_ObtainRead(&cm_serverLock);        /* for going down server list */
1136         /* jaltman - do the reference counts to serverRefp contents need to be increased? */
1137         serverRefp = tcellp->vlServersp;
1138         for (i=0; i<max; i++) {
1139             if (!serverRefp) break;
1140             serverp = serverRefp->server;
1141             memcpy(cp, &serverp->addr.sin_addr.s_addr, sizeof(long));
1142             cp += sizeof(long);
1143             serverRefp = serverRefp->next;
1144         }
1145         lock_ReleaseRead(&cm_serverLock);
1146         cp = basep + max * sizeof(afs_int32);
1147         StringCbCopyA(cp, 999999, tcellp->name);
1148         cp += strlen(tcellp->name)+1;
1149         ioctlp->outDatap = cp;
1150     }
1151
1152     if (tcellp) 
1153         return 0;
1154     else 
1155         return CM_ERROR_NOMORETOKENS;   /* mapped to EDOM */
1156 }
1157
1158 extern long cm_AddCellProc(void *rockp, struct sockaddr_in *addrp, char *namep);
1159
1160 long cm_IoctlNewCell(struct smb_ioctl *ioctlp, struct cm_user *userp)
1161 {
1162     /* NT cache manager will read cell information from CellServDB each time
1163      * cell is accessed. So, this call is necessary only if list of server for a cell 
1164      * changes (or IP addresses of cell servers changes).
1165      * All that needs to be done is to refresh server information for all cells that 
1166      * are already loaded.
1167   
1168      * cell list will be cm_CellLock and cm_ServerLock will be held for write.
1169      */  
1170   
1171     cm_cell_t *cp;
1172   
1173     cm_SkipIoctlPath(ioctlp);
1174     lock_ObtainWrite(&cm_cellLock);
1175   
1176     for (cp = cm_data.allCellsp; cp; cp=cp->nextp) 
1177     {
1178         long code;
1179         /* delete all previous server lists - cm_FreeServerList will ask for write on cm_ServerLock*/
1180         cm_FreeServerList(&cp->vlServersp);
1181         cp->vlServersp = NULL;
1182         code = cm_SearchCellFile(cp->name, cp->name, cm_AddCellProc, cp);
1183 #ifdef AFS_AFSDB_ENV
1184         if (code) {
1185             if (cm_dnsEnabled) {
1186                 int ttl;
1187                 code = cm_SearchCellByDNS(cp->name, cp->name, &ttl, cm_AddCellProc, cp);
1188                 if ( code == 0 ) { /* got cell from DNS */
1189                     cp->flags |= CM_CELLFLAG_DNS;
1190                     cp->flags &= ~CM_CELLFLAG_VLSERVER_INVALID;
1191                     cp->timeout = time(0) + ttl;
1192                 }
1193             }
1194         } 
1195         else {
1196             cp->flags &= ~CM_CELLFLAG_DNS;
1197         }
1198 #endif /* AFS_AFSDB_ENV */
1199         if (code) {
1200             cp->flags |= CM_CELLFLAG_VLSERVER_INVALID;
1201         }
1202         else {
1203             cp->flags &= ~CM_CELLFLAG_VLSERVER_INVALID;
1204             cm_RandomizeServer(&cp->vlServersp);
1205         }
1206     }
1207     
1208     lock_ReleaseWrite(&cm_cellLock);
1209     return 0;       
1210 }
1211
1212 long cm_IoctlGetWsCell(smb_ioctl_t *ioctlp, cm_user_t *userp)
1213 {
1214         long code = 0;
1215
1216         if (cm_freelanceEnabled) {
1217             StringCbCopyA(ioctlp->outDatap, 999999, "Freelance.Local.Root");
1218                 ioctlp->outDatap += strlen(ioctlp->outDatap) +1;
1219         } else if (cm_data.rootCellp) {
1220             /* return the default cellname to the caller */
1221             StringCbCopyA(ioctlp->outDatap, 999999, cm_data.rootCellp->name);
1222             ioctlp->outDatap += strlen(ioctlp->outDatap) +1;
1223         } else {
1224             /* if we don't know our default cell, return failure */
1225                 code = CM_ERROR_NOSUCHCELL;
1226     }
1227
1228     return code;
1229 }
1230
1231 long cm_IoctlSysName(struct smb_ioctl *ioctlp, struct cm_user *userp)
1232 {
1233     long setSysName, foundname = 0;
1234     char *cp, *cp2, inname[MAXSYSNAME], outname[MAXSYSNAME];
1235     int t, count, num = 0;
1236     char **sysnamelist[MAXSYSNAME];
1237         
1238     cm_SkipIoctlPath(ioctlp);
1239
1240     memcpy(&setSysName, ioctlp->inDatap, sizeof(long));
1241     ioctlp->inDatap += sizeof(long);
1242         
1243     if (setSysName) {
1244         /* check my args */
1245         if ( setSysName < 0 || setSysName > MAXNUMSYSNAMES )
1246             return EINVAL;
1247         cp2 = ioctlp->inDatap;
1248         for ( cp=ioctlp->inDatap, count = 0; count < setSysName; count++ ) {
1249             /* won't go past end of ioctlp->inDatap since maxsysname*num < ioctlp->inDatap length */
1250             t = strlen(cp);
1251             if (t >= MAXSYSNAME || t <= 0)
1252                 return EINVAL;
1253             /* check for names that can shoot us in the foot */
1254             if (*cp == '.' && (cp[1] == 0 || (cp[1] == '.' && cp[2] == 0)))
1255                 return EINVAL;
1256             cp += t + 1;
1257         }
1258         /* args ok */
1259
1260         /* inname gets first entry in case we're being a translator */
1261         /* (we are never a translator) */
1262         t = strlen(ioctlp->inDatap);
1263         memcpy(inname, ioctlp->inDatap, t + 1);
1264         ioctlp->inDatap += t + 1;
1265         num = count;
1266     }
1267
1268     /* Not xlating, so local case */
1269     if (!cm_sysName)
1270         osi_panic("cm_IoctlSysName: !cm_sysName\n", __FILE__, __LINE__);
1271
1272     if (!setSysName) {      /* user just wants the info */
1273         StringCbCopyA(outname, sizeof(outname), cm_sysName);
1274         foundname = cm_sysNameCount;
1275         *sysnamelist = cm_sysNameList;
1276     } else {        
1277         /* Local guy; only root can change sysname */
1278         /* clear @sys entries from the dnlc, once afs_lookup can
1279          * do lookups of @sys entries and thinks it can trust them */
1280         /* privs ok, store the entry, ... */
1281         StringCbCopyA(cm_sysName, sizeof(cm_sysName), inname);
1282         StringCbCopyA(cm_sysNameList[0], MAXSYSNAME, inname);
1283         if (setSysName > 1) {       /* ... or list */
1284             cp = ioctlp->inDatap;
1285             for (count = 1; count < setSysName; ++count) {
1286                 if (!cm_sysNameList[count])
1287                     osi_panic("cm_IoctlSysName: no cm_sysNameList entry to write\n",
1288                                __FILE__, __LINE__);
1289                 t = strlen(cp);
1290                 StringCbCopyA(cm_sysNameList[count], MAXSYSNAME, cp);
1291                 cp += t + 1;
1292             }
1293         }
1294         cm_sysNameCount = setSysName;
1295     }
1296
1297     if (!setSysName) {
1298         /* return the sysname to the caller */
1299         cp = ioctlp->outDatap;
1300         memcpy(cp, (char *)&foundname, sizeof(afs_int32));
1301         cp += sizeof(afs_int32);        /* skip found flag */
1302         if (foundname) {
1303             StringCbCopyA(cp, 999999, outname);
1304             cp += strlen(outname) + 1;  /* skip name and terminating null char */
1305             for ( count=1; count < foundname ; ++count) {   /* ... or list */
1306                 if ( !(*sysnamelist)[count] )
1307                     osi_panic("cm_IoctlSysName: no cm_sysNameList entry to read\n", 
1308                                __FILE__, __LINE__);
1309                 t = strlen((*sysnamelist)[count]);
1310                 if (t >= MAXSYSNAME)
1311                     osi_panic("cm_IoctlSysName: sysname entry garbled\n", 
1312                                __FILE__, __LINE__);
1313                 StringCbCopyA(cp, 999999, (*sysnamelist)[count]);
1314                 cp += t + 1;
1315             }
1316         }
1317         ioctlp->outDatap = cp;
1318     }
1319         
1320     /* done: success */
1321     return 0;
1322 }
1323
1324 long cm_IoctlGetCellStatus(struct smb_ioctl *ioctlp, struct cm_user *userp)
1325 {
1326     long temp;
1327     cm_cell_t *cellp;
1328
1329     cm_SkipIoctlPath(ioctlp);
1330
1331     cellp = cm_GetCell(ioctlp->inDatap, 0);
1332     if (!cellp) 
1333         return CM_ERROR_NOSUCHCELL;
1334
1335     temp = 0;
1336     lock_ObtainMutex(&cellp->mx);
1337     if (cellp->flags & CM_CELLFLAG_SUID)
1338         temp |= CM_SETCELLFLAG_SUID;
1339     lock_ReleaseMutex(&cellp->mx);
1340         
1341     /* now copy out parm */
1342     memcpy(ioctlp->outDatap, &temp, sizeof(long));
1343     ioctlp->outDatap += sizeof(long);
1344
1345     return 0;
1346 }
1347
1348 long cm_IoctlSetCellStatus(struct smb_ioctl *ioctlp, struct cm_user *userp)
1349 {
1350     long temp;
1351     cm_cell_t *cellp;
1352
1353     cm_SkipIoctlPath(ioctlp);
1354
1355     cellp = cm_GetCell(ioctlp->inDatap + 2*sizeof(long), 0);
1356     if (!cellp) 
1357         return CM_ERROR_NOSUCHCELL;
1358
1359     memcpy((char *)&temp, ioctlp->inDatap, sizeof(long));
1360
1361     lock_ObtainMutex(&cellp->mx);
1362     if (temp & CM_SETCELLFLAG_SUID)
1363         cellp->flags |= CM_CELLFLAG_SUID;
1364     else
1365         cellp->flags &= ~CM_CELLFLAG_SUID;
1366     lock_ReleaseMutex(&cellp->mx);
1367
1368     return 0;
1369 }
1370
1371 long cm_IoctlSetSPrefs(struct smb_ioctl *ioctlp, struct cm_user *userp)
1372 {
1373     cm_SSetPref_t         *spin; /* input */
1374     cm_SPref_t        *srvin;   /* one input component */
1375     cm_server_t       *tsp;
1376     int                   i, vlonly, noServers, type;
1377     struct sockaddr_in  tmp;
1378     unsigned short        rank;
1379
1380     cm_SkipIoctlPath(ioctlp);       /* we don't care about the path */
1381
1382     spin           = (cm_SSetPref_t *)ioctlp->inDatap;
1383     noServers  = spin->num_servers;
1384     vlonly     = spin->flags;
1385     if ( vlonly )
1386         type = CM_SERVER_VLDB;
1387     else    
1388         type = CM_SERVER_FILE;
1389
1390     for ( i=0; i < noServers; i++) 
1391     {
1392         srvin          = &(spin->servers[i]);
1393         rank           = srvin->rank + (rand() & 0x000f);
1394         tmp.sin_addr   = srvin->host;
1395         tmp.sin_family = AF_INET;
1396
1397         tsp = cm_FindServer(&tmp, type);
1398         if ( tsp )              /* an existing server - ref count increased */
1399         {
1400             tsp->ipRank = rank; /* no need to protect by mutex*/
1401
1402             if (type == CM_SERVER_FILE)
1403             {   /* fileserver */
1404                 /* find volumes which might have RO copy 
1405                 /* on server and change the ordering of 
1406                  * their RO list 
1407                  */
1408                 cm_ChangeRankVolume(tsp);
1409             }
1410             else        
1411             {
1412                 /* set preferences for an existing vlserver */
1413                 cm_ChangeRankCellVLServer(tsp);
1414             }
1415             cm_PutServer(tsp);  /* decrease refcount */
1416         }
1417         else    /* add a new server without a cell */
1418         {
1419             tsp = cm_NewServer(&tmp, type, NULL); /* refcount = 1 */
1420             tsp->ipRank = rank;
1421         }
1422     }
1423     return 0;
1424 }
1425
1426 long cm_IoctlGetSPrefs(struct smb_ioctl *ioctlp, struct cm_user *userp)
1427 {
1428     cm_SPrefRequest_t *spin; /* input */
1429     cm_SPrefInfo_t    *spout;   /* output */
1430     cm_SPref_t        *srvout;   /* one output component */
1431     cm_server_t       *tsp;
1432     int                   i, vlonly, noServers;
1433
1434     cm_SkipIoctlPath(ioctlp);       /* we don't care about the path */
1435
1436     spin      = (cm_SPrefRequest_t *)ioctlp->inDatap;
1437     spout     = (cm_SPrefInfo_t *) ioctlp->outDatap;
1438     srvout    = spout->servers;
1439     noServers = spin->num_servers; 
1440     vlonly    = spin->flags & CM_SPREF_VLONLY;
1441     spout->num_servers = 0;
1442
1443     lock_ObtainRead(&cm_serverLock); /* get server lock */
1444
1445     for (tsp=cm_allServersp, i=0; tsp && noServers; tsp=tsp->allNextp,i++){
1446         if (spin->offset > i) {
1447             continue;    /* catch up to where we left off */
1448         }
1449
1450         if ( vlonly && (tsp->type == CM_SERVER_FILE) )
1451             continue;   /* ignore fileserver for -vlserver option*/
1452         if ( !vlonly && (tsp->type == CM_SERVER_VLDB) )
1453             continue;   /* ignore vlservers */
1454
1455         srvout->host = tsp->addr.sin_addr;
1456         srvout->rank = tsp->ipRank;
1457         srvout++;       
1458         spout->num_servers++;
1459         noServers--;
1460     }
1461     lock_ReleaseRead(&cm_serverLock); /* release server lock */
1462
1463     if ( tsp )  /* we ran out of space in the output buffer */
1464         spout->next_offset = i;
1465     else    
1466         spout->next_offset = 0; 
1467     ioctlp->outDatap += sizeof(cm_SPrefInfo_t) + 
1468         (spout->num_servers -1 ) * sizeof(cm_SPref_t) ;
1469     return 0;
1470 }
1471
1472 long cm_IoctlStoreBehind(struct smb_ioctl *ioctlp, struct cm_user *userp)
1473 {
1474     /* we ignore default asynchrony since we only have one way
1475      * of doing this today.
1476      */
1477     return 0;
1478 }       
1479
1480 long cm_IoctlCreateMountPoint(struct smb_ioctl *ioctlp, struct cm_user *userp)
1481 {
1482     char leaf[LEAF_SIZE];
1483     long code;
1484     cm_scache_t *dscp;
1485     cm_attr_t tattr;
1486     char *cp;
1487     cm_req_t req;
1488     char mpInfo[256];
1489     char fullCell[256];
1490     char volume[256];
1491     char cell[256];
1492     int ttl;
1493
1494     cm_InitReq(&req);
1495         
1496     code = cm_ParseIoctlParent(ioctlp, userp, &req, &dscp, leaf);
1497     if (code) return code;
1498
1499     /* Translate chars for the mount point name */
1500     TranslateExtendedChars(leaf);
1501
1502     /* 
1503      * The fs command allows the user to specify partial cell names on NT.  These must
1504      * be expanded to the full cell name for mount points so that the mount points will
1505      * work on UNIX clients.
1506      */
1507
1508     /* Extract the possibly partial cell name */
1509     StringCbCopyA(cell, sizeof(cell), ioctlp->inDatap + 1);      /* Skip the mp type character */
1510         
1511     if (cp = strchr(cell, ':')) {
1512         /* Extract the volume name */
1513         *cp = 0;
1514         StringCbCopyA(volume,  sizeof(volume), cp + 1);
1515         
1516         /* Get the full name for this cell */
1517         code = cm_SearchCellFile(cell, fullCell, 0, 0);
1518 #ifdef AFS_AFSDB_ENV
1519         if (code && cm_dnsEnabled)
1520             code = cm_SearchCellByDNS(cell, fullCell, &ttl, 0, 0);
1521 #endif
1522         if (code)
1523             return CM_ERROR_NOSUCHCELL;
1524         
1525         StringCbPrintfA(mpInfo, sizeof(mpInfo), "%c%s:%s", *ioctlp->inDatap, fullCell, volume);
1526     } else {
1527         /* No cell name specified */
1528         StringCbCopyA(mpInfo, sizeof(mpInfo), ioctlp->inDatap);
1529     }
1530
1531 #ifdef AFS_FREELANCE_CLIENT
1532     if (cm_freelanceEnabled && dscp == cm_data.rootSCachep) {
1533         /* we are adding the mount point to the root dir., so call
1534          * the freelance code to do the add. */
1535         osi_Log0(afsd_logp,"IoctlCreateMountPoint within Freelance root dir");
1536         code = cm_FreelanceAddMount(leaf, fullCell, volume, 
1537                                     *ioctlp->inDatap == '%', NULL);
1538         return code;
1539     }
1540 #endif
1541     /* create the symlink with mode 644.  The lack of X bits tells
1542      * us that it is a mount point.
1543      */
1544     tattr.mask = CM_ATTRMASK_UNIXMODEBITS | CM_ATTRMASK_CLIENTMODTIME;
1545     tattr.unixModeBits = 0644;
1546     tattr.clientModTime = time(NULL);
1547
1548     code = cm_SymLink(dscp, leaf, mpInfo, 0, &tattr, userp, &req);
1549     if (code == 0 && (dscp->flags & CM_SCACHEFLAG_ANYWATCH))
1550         smb_NotifyChange(FILE_ACTION_ADDED,
1551                          FILE_NOTIFY_CHANGE_DIR_NAME,
1552                          dscp, leaf, NULL, TRUE);
1553
1554     cm_ReleaseSCache(dscp);
1555     return code;
1556 }
1557
1558 long cm_IoctlSymlink(struct smb_ioctl *ioctlp, struct cm_user *userp)
1559 {
1560     char leaf[LEAF_SIZE];
1561     long code;
1562     cm_scache_t *dscp;
1563     cm_attr_t tattr;
1564     char *cp;
1565     cm_req_t req;
1566
1567     cm_InitReq(&req);
1568
1569     code = cm_ParseIoctlParent(ioctlp, userp, &req, &dscp, leaf);
1570     if (code) return code;
1571
1572     /* Translate chars for the link name */
1573     TranslateExtendedChars(leaf);
1574
1575     /* Translate chars for the linked to name */
1576     TranslateExtendedChars(ioctlp->inDatap);
1577
1578     cp = ioctlp->inDatap;               /* contents of link */
1579
1580 #ifdef AFS_FREELANCE_CLIENT
1581     if (cm_freelanceEnabled && dscp == cm_data.rootSCachep) {
1582         /* we are adding the symlink to the root dir., so call
1583          * the freelance code to do the add. */
1584         if (cp[0] == cp[1] && cp[1] == '\\' && 
1585             !_strnicmp(cm_NetbiosName,cp+2,strlen(cm_NetbiosName))) 
1586         {
1587             /* skip \\AFS\ or \\AFS\all\ */
1588             char * p;
1589             p = cp + 2 + strlen(cm_NetbiosName) + 1;
1590             if ( !_strnicmp("all", p, 3) )
1591                 p += 4;
1592             cp = p;
1593         }
1594         osi_Log0(afsd_logp,"IoctlCreateSymlink within Freelance root dir");
1595         code = cm_FreelanceAddSymlink(leaf, cp, NULL);
1596         return code;
1597     }
1598 #endif
1599
1600     /* Create symlink with mode 0755. */
1601     tattr.mask = CM_ATTRMASK_UNIXMODEBITS;
1602     tattr.unixModeBits = 0755;
1603
1604     code = cm_SymLink(dscp, leaf, cp, 0, &tattr, userp, &req);
1605     if (code == 0 && (dscp->flags & CM_SCACHEFLAG_ANYWATCH))
1606         smb_NotifyChange(FILE_ACTION_ADDED,
1607                           FILE_NOTIFY_CHANGE_FILE_NAME
1608                           | FILE_NOTIFY_CHANGE_DIR_NAME,
1609                           dscp, leaf, NULL, TRUE);
1610
1611     cm_ReleaseSCache(dscp);
1612
1613     return code;
1614 }
1615
1616
1617 long cm_IoctlListlink(struct smb_ioctl *ioctlp, struct cm_user *userp)
1618 {
1619     long code;
1620     cm_scache_t *dscp;
1621     cm_scache_t *scp;
1622     char *cp;
1623     cm_space_t *spacep;
1624     cm_scache_t *newRootScp;
1625     cm_req_t req;
1626
1627     cm_InitReq(&req);
1628
1629     code = cm_ParseIoctlPath(ioctlp, userp, &req, &dscp);
1630     if (code) return code;
1631
1632     cp = ioctlp->inDatap;
1633
1634     code = cm_Lookup(dscp, cp, CM_FLAG_NOMOUNTCHASE, userp, &req, &scp);
1635     cm_ReleaseSCache(dscp);
1636     if (code) return code;
1637
1638     /* Check that it's a real symlink */
1639     if (scp->fileType != CM_SCACHETYPE_SYMLINK &&
1640         scp->fileType != CM_SCACHETYPE_DFSLINK &&
1641         scp->fileType != CM_SCACHETYPE_INVALID) {
1642         cm_ReleaseSCache(scp);
1643         return CM_ERROR_INVAL;
1644     }
1645
1646     code = cm_AssembleLink(scp, "", &newRootScp, &spacep, userp, &req);
1647     cm_ReleaseSCache(scp);
1648     if (code == 0) {
1649         cp = ioctlp->outDatap;
1650         if (newRootScp != NULL) {
1651             StringCbCopyA(cp, 999999, cm_mountRoot);
1652             StringCbCatA(cp, 999999, "/");
1653             cp += strlen(cp);
1654         }
1655         StringCbCopyA(cp, 999999, spacep->data);
1656         cp += strlen(cp) + 1;
1657         ioctlp->outDatap = cp;
1658         cm_FreeSpace(spacep);
1659         if (newRootScp != NULL)
1660             cm_ReleaseSCache(newRootScp);
1661         code = 0;
1662     } else if (code == CM_ERROR_PATH_NOT_COVERED && 
1663                 scp->fileType == CM_SCACHETYPE_DFSLINK ||
1664                code == CM_ERROR_NOSUCHPATH &&
1665                 scp->fileType == CM_SCACHETYPE_INVALID) {
1666         cp = ioctlp->outDatap;
1667         StringCbCopyA(cp, 999999, spacep->data);
1668         cp += strlen(cp) + 1;
1669         ioctlp->outDatap = cp;
1670         cm_FreeSpace(spacep);
1671         if (newRootScp != NULL)
1672             cm_ReleaseSCache(newRootScp);
1673         code = 0;
1674     }
1675
1676     return code;
1677 }
1678
1679 long cm_IoctlIslink(struct smb_ioctl *ioctlp, struct cm_user *userp)
1680 {/*CHECK FOR VALID SYMLINK*/
1681     long code;
1682     cm_scache_t *dscp;
1683     cm_scache_t *scp;
1684     char *cp;
1685     cm_req_t req;
1686
1687     cm_InitReq(&req);
1688
1689     code = cm_ParseIoctlPath(ioctlp, userp, &req, &dscp);
1690     if (code) return code;
1691
1692     cp = ioctlp->inDatap;
1693     osi_LogEvent("cm_IoctlListlink",NULL," name[%s]",cp);
1694
1695     code = cm_Lookup(dscp, cp, CM_FLAG_NOMOUNTCHASE, userp, &req, &scp);
1696     cm_ReleaseSCache(dscp);
1697     if (code) return code;
1698
1699     /* Check that it's a real symlink */
1700     if (scp->fileType != CM_SCACHETYPE_SYMLINK &&
1701         scp->fileType != CM_SCACHETYPE_DFSLINK &&
1702         scp->fileType != CM_SCACHETYPE_INVALID)
1703         code = CM_ERROR_INVAL;
1704     cm_ReleaseSCache(scp);
1705     return code;
1706 }
1707
1708 long cm_IoctlDeletelink(struct smb_ioctl *ioctlp, struct cm_user *userp)
1709 {
1710     long code;
1711     cm_scache_t *dscp;
1712     cm_scache_t *scp;
1713     char *cp;
1714     cm_req_t req;
1715
1716     cm_InitReq(&req);
1717
1718     code = cm_ParseIoctlPath(ioctlp, userp, &req, &dscp);
1719     if (code) return code;
1720
1721     cp = ioctlp->inDatap;
1722
1723 #ifdef AFS_FREELANCE_CLIENT
1724     if (cm_freelanceEnabled && dscp == cm_data.rootSCachep) {
1725         /* we are adding the mount point to the root dir., so call
1726          * the freelance code to do the add. */
1727         osi_Log0(afsd_logp,"IoctlDeletelink from Freelance root dir");
1728         code = cm_FreelanceRemoveSymlink(cp);
1729         return code;
1730     }
1731 #endif
1732
1733     code = cm_Lookup(dscp, cp, CM_FLAG_NOMOUNTCHASE, userp, &req, &scp);
1734         
1735     /* if something went wrong, bail out now */
1736     if (code) {
1737         goto done;
1738     }
1739         
1740     lock_ObtainMutex(&scp->mx);
1741     code = cm_SyncOp(scp, NULL, userp, &req, 0,
1742                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1743     if (code) {     
1744         lock_ReleaseMutex(&scp->mx);
1745         cm_ReleaseSCache(scp);
1746         goto done;
1747     }
1748         
1749     /* now check that this is a real symlink */
1750     if (scp->fileType != CM_SCACHETYPE_SYMLINK &&
1751         scp->fileType != CM_SCACHETYPE_DFSLINK &&
1752         scp->fileType != CM_SCACHETYPE_INVALID) {
1753         lock_ReleaseMutex(&scp->mx);
1754         cm_ReleaseSCache(scp);
1755         code = CM_ERROR_INVAL;
1756         goto done;
1757     }
1758         
1759     /* time to make the RPC, so drop the lock */
1760     lock_ReleaseMutex(&scp->mx);
1761     cm_ReleaseSCache(scp);
1762         
1763     /* easier to do it this way */
1764     code = cm_Unlink(dscp, cp, userp, &req);
1765     if (code == 0 && (dscp->flags & CM_SCACHEFLAG_ANYWATCH))
1766         smb_NotifyChange(FILE_ACTION_REMOVED,
1767                           FILE_NOTIFY_CHANGE_FILE_NAME
1768                           | FILE_NOTIFY_CHANGE_DIR_NAME,
1769                           dscp, cp, NULL, TRUE);
1770
1771   done:
1772     cm_ReleaseSCache(dscp);
1773     return code;
1774 }
1775
1776 long cm_IoctlSetToken(struct smb_ioctl *ioctlp, struct cm_user *userp)
1777 {
1778     char *saveDataPtr;
1779     char *tp;
1780     int ticketLen;
1781     char *ticket;
1782     int ctSize;
1783     struct ClearToken ct;
1784     cm_cell_t *cellp;
1785     cm_ucell_t *ucellp;
1786     char *uname = NULL;
1787     afs_uuid_t uuid;
1788     int flags;
1789     char sessionKey[8];
1790     char *smbname;
1791
1792     saveDataPtr = ioctlp->inDatap;
1793
1794     cm_SkipIoctlPath(ioctlp);
1795
1796     tp = ioctlp->inDatap;
1797
1798     /* ticket length */
1799     memcpy(&ticketLen, tp, sizeof(ticketLen));
1800     tp += sizeof(ticketLen);
1801     if (ticketLen < MINKTCTICKETLEN || ticketLen > MAXKTCTICKETLEN)
1802         return CM_ERROR_INVAL;
1803
1804     /* remember ticket and skip over it for now */
1805     ticket = tp;
1806     tp += ticketLen;
1807
1808     /* clear token size */
1809     memcpy(&ctSize, tp, sizeof(ctSize));
1810     tp += sizeof(ctSize);
1811     if (ctSize != sizeof(struct ClearToken))
1812         return CM_ERROR_INVAL;
1813
1814     /* clear token */
1815     memcpy(&ct, tp, ctSize);
1816     tp += ctSize;
1817     if (ct.AuthHandle == -1)
1818         ct.AuthHandle = 999;    /* more rxvab compat stuff */
1819
1820     /* more stuff, if any */
1821     if (ioctlp->inCopied > tp - saveDataPtr) {
1822         /* flags:  logon flag */
1823         memcpy(&flags, tp, sizeof(int));
1824         tp += sizeof(int);
1825
1826         /* cell name */
1827         cellp = cm_GetCell(tp, CM_FLAG_CREATE);
1828         if (!cellp) return CM_ERROR_NOSUCHCELL;
1829         tp += strlen(tp) + 1;
1830
1831         /* user name */
1832         uname = tp;
1833         tp += strlen(tp) + 1;
1834
1835 #ifndef AFSIFS                  /* no SMB username */
1836         if (flags & PIOCTL_LOGON) {
1837             /* SMB user name with which to associate tokens */
1838             smbname = tp;
1839             osi_Log2(smb_logp,"cm_IoctlSetToken for user [%s] smbname [%s]",
1840                      osi_LogSaveString(smb_logp,uname), osi_LogSaveString(smb_logp,smbname));
1841             fprintf(stderr, "SMB name = %s\n", smbname);
1842             tp += strlen(tp) + 1;
1843         } else {
1844             osi_Log1(smb_logp,"cm_IoctlSetToken for user [%s]",
1845                      osi_LogSaveString(smb_logp,uname));
1846         }
1847 #endif
1848
1849 #ifndef DJGPP   /* for win95, session key is back in pioctl */
1850                 /* uuid */
1851         memcpy(&uuid, tp, sizeof(uuid));
1852         if (!cm_FindTokenEvent(uuid, sessionKey))
1853             return CM_ERROR_INVAL;
1854 #endif /* !DJGPP */
1855     } else {
1856         cellp = cm_data.rootCellp;
1857         osi_Log0(smb_logp,"cm_IoctlSetToken - no name specified");
1858     }
1859
1860     if (flags & PIOCTL_LOGON) {
1861         userp = smb_FindCMUserByName(smbname, ioctlp->fidp->vcp->rname);
1862     }
1863
1864     /* store the token */
1865     lock_ObtainMutex(&userp->mx);
1866     ucellp = cm_GetUCell(userp, cellp);
1867     osi_Log1(smb_logp,"cm_IoctlSetToken ucellp %lx", ucellp);
1868     ucellp->ticketLen = ticketLen;
1869     if (ucellp->ticketp)
1870         free(ucellp->ticketp);  /* Discard old token if any */
1871     ucellp->ticketp = malloc(ticketLen);
1872     memcpy(ucellp->ticketp, ticket, ticketLen);
1873 #ifndef DJGPP
1874     /*
1875      * Get the session key from the RPC, rather than from the pioctl.
1876      */
1877     /*
1878     memcpy(&ucellp->sessionKey, ct.HandShakeKey, sizeof(ct.HandShakeKey));
1879     */
1880     memcpy(ucellp->sessionKey.data, sessionKey, sizeof(sessionKey));
1881 #else
1882     /* for win95, we are getting the session key from the pioctl */
1883     memcpy(&ucellp->sessionKey, ct.HandShakeKey, sizeof(ct.HandShakeKey));
1884 #endif /* !DJGPP */
1885     ucellp->kvno = ct.AuthHandle;
1886     ucellp->expirationTime = ct.EndTimestamp;
1887     ucellp->gen++;
1888     if (uname) 
1889         StringCbCopyA(ucellp->userName, MAXKTCNAMELEN, uname);
1890     ucellp->flags |= CM_UCELLFLAG_RXKAD;
1891     lock_ReleaseMutex(&userp->mx);
1892
1893     if (flags & PIOCTL_LOGON) {
1894         ioctlp->flags |= SMB_IOCTLFLAG_LOGON;
1895     }
1896
1897     cm_ResetACLCache(userp);
1898
1899     return 0;
1900 }
1901
1902 long cm_IoctlGetTokenIter(struct smb_ioctl *ioctlp, struct cm_user *userp)
1903 {
1904     char *tp, *cp;
1905     int iterator;
1906     int temp;
1907     cm_ucell_t *ucellp;
1908     struct ClearToken ct;
1909
1910     cm_SkipIoctlPath(ioctlp);
1911
1912     tp = ioctlp->inDatap;
1913     cp = ioctlp->outDatap;
1914
1915     /* iterator */
1916     memcpy(&iterator, tp, sizeof(iterator));
1917     tp += sizeof(iterator);
1918
1919     lock_ObtainMutex(&userp->mx);
1920
1921     /* look for token */
1922     for (;;iterator++) {
1923         ucellp = cm_FindUCell(userp, iterator);
1924         if (!ucellp) {
1925             lock_ReleaseMutex(&userp->mx);
1926             return CM_ERROR_NOMORETOKENS;
1927         }
1928         if (ucellp->flags & CM_UCELLFLAG_RXKAD)
1929             break;
1930     }       
1931
1932     /* new iterator */
1933     temp = ucellp->iterator + 1;
1934     memcpy(cp, &temp, sizeof(temp));
1935     cp += sizeof(temp);
1936
1937     /* ticket length */
1938     memcpy(cp, &ucellp->ticketLen, sizeof(ucellp->ticketLen));
1939     cp += sizeof(ucellp->ticketLen);
1940
1941     /* ticket */
1942     memcpy(cp, ucellp->ticketp, ucellp->ticketLen);
1943     cp += ucellp->ticketLen;
1944
1945     /* clear token size */
1946     temp = sizeof(ct);
1947     memcpy(cp, &temp, sizeof(temp));
1948     cp += sizeof(temp);
1949
1950     /* clear token */
1951     ct.AuthHandle = ucellp->kvno;
1952 #ifndef DJGPP
1953     /*
1954      * Don't give out a real session key here
1955      */
1956     /*
1957     memcpy(ct.HandShakeKey, &ucellp->sessionKey, sizeof(ct.HandShakeKey));
1958     */
1959     memset(ct.HandShakeKey, 0, sizeof(ct.HandShakeKey));
1960 #else
1961     memcpy(ct.HandShakeKey, &ucellp->sessionKey, sizeof(ct.HandShakeKey));
1962 #endif /* !DJGPP */
1963     ct.ViceId = 37;                     /* XXX */
1964     ct.BeginTimestamp = 0;              /* XXX */
1965     ct.EndTimestamp = ucellp->expirationTime;
1966     memcpy(cp, &ct, sizeof(ct));
1967     cp += sizeof(ct);
1968
1969     /* Primary flag (unused) */
1970     temp = 0;
1971     memcpy(cp, &temp, sizeof(temp));
1972     cp += sizeof(temp);
1973
1974     /* cell name */
1975     StringCbCopyA(cp, 999999, ucellp->cellp->name);
1976     cp += strlen(cp) + 1;
1977
1978     /* user name */
1979     StringCbCopyA(cp, 999999, ucellp->userName);
1980     cp += strlen(cp) + 1;
1981
1982     ioctlp->outDatap = cp;
1983
1984     lock_ReleaseMutex(&userp->mx);
1985
1986     return 0;
1987 }
1988
1989 long cm_IoctlGetToken(struct smb_ioctl *ioctlp, struct cm_user *userp)
1990 {
1991     char *cp;
1992     int temp;
1993     cm_cell_t *cellp;
1994     cm_ucell_t *ucellp;
1995     struct ClearToken ct;
1996     char *tp;
1997 #ifndef DJGPP
1998     afs_uuid_t uuid;
1999 #endif /* !DJGPP */
2000
2001     cm_SkipIoctlPath(ioctlp);
2002
2003     tp = ioctlp->inDatap;
2004
2005     cp = ioctlp->outDatap;
2006
2007     /* cell name is right here */
2008     cellp = cm_GetCell(tp, 0);
2009     if (!cellp) 
2010         return CM_ERROR_NOSUCHCELL;
2011     tp += strlen(tp) + 1;
2012
2013 #ifndef DJGPP
2014     /* uuid */
2015     memcpy(&uuid, tp, sizeof(uuid));
2016 #endif /* !DJGPP */
2017
2018     lock_ObtainMutex(&userp->mx);
2019
2020     ucellp = cm_GetUCell(userp, cellp);
2021     if (!ucellp || !(ucellp->flags & CM_UCELLFLAG_RXKAD)) {
2022         lock_ReleaseMutex(&userp->mx);
2023         return CM_ERROR_NOMORETOKENS;
2024     }
2025
2026     /* ticket length */
2027     memcpy(cp, &ucellp->ticketLen, sizeof(ucellp->ticketLen));
2028     cp += sizeof(ucellp->ticketLen);
2029
2030     /* ticket */
2031     memcpy(cp, ucellp->ticketp, ucellp->ticketLen);
2032     cp += ucellp->ticketLen;
2033
2034     /* clear token size */
2035     temp = sizeof(ct);
2036     memcpy(cp, &temp, sizeof(temp));
2037     cp += sizeof(temp);
2038
2039     /* clear token */
2040     ct.AuthHandle = ucellp->kvno;
2041 #ifndef DJGPP
2042     /*
2043      * Don't give out a real session key here
2044      */
2045     /*
2046     memcpy(ct.HandShakeKey, &ucellp->sessionKey, sizeof(ct.HandShakeKey));
2047     */
2048     memset(ct.HandShakeKey, 0, sizeof(ct.HandShakeKey));
2049 #else
2050     memcpy(ct.HandShakeKey, &ucellp->sessionKey, sizeof(ct.HandShakeKey));
2051 #endif /* !DJGPP */
2052     ct.ViceId = 37;                     /* XXX */
2053     ct.BeginTimestamp = 0;              /* XXX */
2054     ct.EndTimestamp = ucellp->expirationTime;
2055     memcpy(cp, &ct, sizeof(ct));
2056     cp += sizeof(ct);
2057
2058     /* Primary flag (unused) */
2059     temp = 0;
2060     memcpy(cp, &temp, sizeof(temp));
2061     cp += sizeof(temp);
2062
2063     /* cell name */
2064     StringCbCopyA(cp, 999999, ucellp->cellp->name);
2065     cp += strlen(cp) + 1;
2066
2067     /* user name */
2068     StringCbCopyA(cp, 999999, ucellp->userName);
2069     cp += strlen(cp) + 1;
2070
2071     ioctlp->outDatap = cp;
2072
2073     lock_ReleaseMutex(&userp->mx);
2074
2075 #ifndef DJGPP
2076     cm_RegisterNewTokenEvent(uuid, ucellp->sessionKey.data);
2077 #endif /* !DJGPP */
2078
2079     return 0;
2080 }
2081
2082 long cm_IoctlDelToken(struct smb_ioctl *ioctlp, struct cm_user *userp)
2083 {
2084     char *cp;
2085     cm_cell_t *cellp;
2086     cm_ucell_t *ucellp;
2087
2088     cm_SkipIoctlPath(ioctlp);
2089
2090     cp = ioctlp->outDatap;
2091
2092     /* cell name is right here */
2093     cellp = cm_GetCell(ioctlp->inDatap, 0);
2094     if (!cellp) return CM_ERROR_NOSUCHCELL;
2095
2096     lock_ObtainMutex(&userp->mx);
2097
2098     ucellp = cm_GetUCell(userp, cellp);
2099     if (!ucellp) {
2100         lock_ReleaseMutex(&userp->mx);
2101         return CM_ERROR_NOMORETOKENS;
2102     }
2103
2104     osi_Log1(smb_logp,"cm_IoctlDelToken ucellp %lx", ucellp);
2105
2106     if (ucellp->ticketp) {
2107         free(ucellp->ticketp);
2108         ucellp->ticketp = NULL;
2109     }
2110     ucellp->flags &= ~CM_UCELLFLAG_RXKAD;
2111     ucellp->gen++;
2112
2113     lock_ReleaseMutex(&userp->mx);
2114
2115     cm_ResetACLCache(userp);
2116
2117     return 0;
2118 }
2119
2120 long cm_IoctlDelAllToken(struct smb_ioctl *ioctlp, struct cm_user *userp)
2121 {
2122     cm_ucell_t *ucellp;
2123
2124     lock_ObtainMutex(&userp->mx);
2125
2126     for (ucellp = userp->cellInfop; ucellp; ucellp = ucellp->nextp) {
2127         osi_Log1(smb_logp,"cm_IoctlDelAllToken ucellp %lx", ucellp);
2128         ucellp->flags &= ~CM_UCELLFLAG_RXKAD;
2129         ucellp->gen++;
2130     }
2131
2132     lock_ReleaseMutex(&userp->mx);
2133
2134     cm_ResetACLCache(userp);
2135
2136     return 0;
2137 }
2138
2139 long cm_IoctlMakeSubmount(smb_ioctl_t *ioctlp, cm_user_t *userp)
2140 {
2141     char afspath[MAX_PATH];
2142     char *submountreqp;
2143     int nextAutoSubmount;
2144     HKEY hkSubmounts;
2145     DWORD dwType, dwSize;
2146     DWORD status;
2147     DWORD dwIndex;
2148     DWORD dwSubmounts;
2149
2150     cm_SkipIoctlPath(ioctlp);
2151
2152     /* Serialize this one, to prevent simultaneous mods
2153      * to afsdsbmt.ini
2154      */
2155     lock_ObtainMutex(&cm_Afsdsbmt_Lock);
2156
2157     /* Parse the input parameters--first the required afs path,
2158      * then the requested submount name (which may be "").
2159      */
2160     cm_NormalizeAfsPath (afspath, sizeof(afspath), ioctlp->inDatap);
2161     submountreqp = ioctlp->inDatap + (strlen(ioctlp->inDatap)+1);
2162
2163     /* If the caller supplied a suggested submount name, see if
2164      * that submount name is in use... if so, the submount's path
2165      * has to match our path.
2166      */
2167
2168     RegCreateKeyEx( HKEY_LOCAL_MACHINE, 
2169                     AFSREG_CLT_OPENAFS_SUBKEY "\\Submounts",
2170                     0, 
2171                     "AFS", 
2172                     REG_OPTION_NON_VOLATILE,
2173                     KEY_READ|KEY_WRITE|KEY_QUERY_VALUE,
2174                     NULL, 
2175                     &hkSubmounts,
2176                     NULL );
2177
2178     if (submountreqp && *submountreqp) {
2179         char submountPathNormalized[MAX_PATH];
2180         char submountPath[MAX_PATH];
2181
2182         dwSize = sizeof(submountPath);
2183         status = RegQueryValueEx( hkSubmounts, submountreqp, 0,
2184                                   &dwType, submountPath, &dwSize);
2185
2186         if (status != ERROR_SUCCESS) {
2187
2188             /* The suggested submount name isn't in use now--
2189              * so we can safely map the requested submount name
2190              * to the supplied path. Remember not to write the
2191              * leading "/afs" when writing out the submount.
2192              */
2193             RegSetValueEx( hkSubmounts, submountreqp, 0,
2194                            REG_EXPAND_SZ, 
2195                            (strlen(&afspath[strlen(cm_mountRoot)])) ?
2196                            &afspath[strlen(cm_mountRoot)]:"/",
2197                            (strlen(&afspath[strlen(cm_mountRoot)])) ?
2198                            strlen(&afspath[strlen(cm_mountRoot)])+1:2);
2199
2200             RegCloseKey( hkSubmounts );
2201             StringCbCopyA(ioctlp->outDatap, 999999, submountreqp);
2202             ioctlp->outDatap += strlen(ioctlp->outDatap) +1;
2203             lock_ReleaseMutex(&cm_Afsdsbmt_Lock);
2204             return 0;
2205         }
2206
2207         /* The suggested submount name is already in use--if the
2208          * supplied path matches the submount's path, we can still
2209          * use the suggested submount name.
2210          */
2211         cm_NormalizeAfsPath (submountPathNormalized, sizeof(submountPathNormalized), submountPath);
2212         if (!strcmp (submountPathNormalized, afspath)) {
2213             StringCbCopyA(ioctlp->outDatap, 999999, submountreqp);
2214             ioctlp->outDatap += strlen(ioctlp->outDatap) +1;
2215             RegCloseKey( hkSubmounts );
2216             lock_ReleaseMutex(&cm_Afsdsbmt_Lock);
2217             return 0;
2218         }
2219     }
2220
2221     RegQueryInfoKey( hkSubmounts,
2222                      NULL,  /* lpClass */
2223                      NULL,  /* lpcClass */
2224                      NULL,  /* lpReserved */
2225                      NULL,  /* lpcSubKeys */
2226                      NULL,  /* lpcMaxSubKeyLen */
2227                      NULL,  /* lpcMaxClassLen */
2228                      &dwSubmounts, /* lpcValues */
2229                      NULL,  /* lpcMaxValueNameLen */
2230                      NULL,  /* lpcMaxValueLen */
2231                      NULL,  /* lpcbSecurityDescriptor */
2232                      NULL   /* lpftLastWriteTime */
2233                      );
2234
2235
2236     /* Having obtained a list of all available submounts, start
2237      * searching that list for a path which matches the requested
2238      * AFS path. We'll also keep track of the highest "auto15"/"auto47"
2239      * submount, in case we need to add a new one later.
2240      */
2241
2242     nextAutoSubmount = 1;
2243
2244     for ( dwIndex = 0; dwIndex < dwSubmounts; dwIndex ++ ) {
2245         char submountPathNormalized[MAX_PATH];
2246         char submountPath[MAX_PATH] = "";
2247         DWORD submountPathLen = sizeof(submountPath);
2248         char submountName[MAX_PATH];
2249         DWORD submountNameLen = sizeof(submountName);
2250
2251         dwType = 0;
2252         RegEnumValue( hkSubmounts, dwIndex, submountName, &submountNameLen, NULL,
2253                       &dwType, submountPath, &submountPathLen);
2254         if (dwType == REG_EXPAND_SZ) {
2255             char buf[MAX_PATH];
2256             StringCbCopyA(buf, MAX_PATH, submountPath);
2257             submountPathLen = ExpandEnvironmentStrings(buf, submountPath, MAX_PATH);
2258             if (submountPathLen > MAX_PATH)
2259                 continue;
2260         }
2261
2262         /* If this is an Auto### submount, remember its ### value */
2263         if ((!strnicmp (submountName, "auto", 4)) &&
2264              (isdigit (submountName[strlen("auto")]))) {
2265             int thisAutoSubmount;
2266             thisAutoSubmount = atoi (&submountName[strlen("auto")]);
2267             nextAutoSubmount = max (nextAutoSubmount,
2268                                      thisAutoSubmount+1);
2269         }       
2270
2271         if ((submountPathLen == 0) ||
2272              (submountPathLen == sizeof(submountPath) - 1)) {
2273             continue;
2274         }
2275
2276         /* See if the path for this submount matches the path
2277          * that our caller specified. If so, we can return
2278          * this submount.
2279          */
2280         cm_NormalizeAfsPath (submountPathNormalized, sizeof(submountPathNormalized), submountPath);
2281         if (!strcmp (submountPathNormalized, afspath)) {
2282             StringCbCopyA(ioctlp->outDatap, 999999, submountName);
2283             ioctlp->outDatap += strlen(ioctlp->outDatap) +1;
2284             RegCloseKey(hkSubmounts);
2285             lock_ReleaseMutex(&cm_Afsdsbmt_Lock);
2286             return 0;
2287
2288         }
2289     }
2290
2291     /* We've been through the entire list of existing submounts, and
2292      * didn't find any which matched the specified path. So, we'll
2293      * just have to add one. Remember not to write the leading "/afs"
2294      * when writing out the submount.
2295      */
2296
2297     StringCbPrintfA(ioctlp->outDatap, 999999, "auto%ld", nextAutoSubmount);
2298
2299     RegSetValueEx( hkSubmounts, 
2300                    ioctlp->outDatap,
2301                    0,
2302                    REG_EXPAND_SZ, 
2303                    (strlen(&afspath[strlen(cm_mountRoot)])) ?
2304                    &afspath[strlen(cm_mountRoot)]:"/",
2305                    (strlen(&afspath[strlen(cm_mountRoot)])) ?
2306                    strlen(&afspath[strlen(cm_mountRoot)])+1:2);
2307
2308     ioctlp->outDatap += strlen(ioctlp->outDatap) +1;
2309     RegCloseKey(hkSubmounts);
2310     lock_ReleaseMutex(&cm_Afsdsbmt_Lock);
2311     return 0;
2312 }
2313
2314 long cm_IoctlGetRxkcrypt(smb_ioctl_t *ioctlp, cm_user_t *userp)
2315 {
2316     memcpy(ioctlp->outDatap, &cryptall, sizeof(cryptall));
2317     ioctlp->outDatap += sizeof(cryptall);
2318
2319     return 0;
2320 }
2321
2322 long cm_IoctlSetRxkcrypt(smb_ioctl_t *ioctlp, cm_user_t *userp)
2323 {
2324     cm_SkipIoctlPath(ioctlp);
2325
2326     memcpy(&cryptall, ioctlp->inDatap, sizeof(cryptall));
2327
2328     return 0;
2329 }
2330
2331 #ifdef DJGPP
2332 extern int afsd_shutdown(int);
2333 extern int afs_shutdown;
2334
2335 long cm_IoctlShutdown(smb_ioctl_t *ioctlp, cm_user_t *userp) {
2336   afs_shutdown = 1;   /* flag to shut down */
2337   return 0;
2338 }
2339 #endif /* DJGPP */
2340
2341 long cm_IoctlGetSMBName(smb_ioctl_t *ioctlp, cm_user_t *userp)
2342 {
2343   smb_user_t *uidp = ioctlp->uidp;
2344
2345   if (uidp && uidp->unp) {
2346     memcpy(ioctlp->outDatap, uidp->unp->name, strlen(uidp->unp->name));
2347     ioctlp->outDatap += strlen(uidp->unp->name);
2348   }
2349
2350   return 0;
2351 }
2352
2353 /* 
2354  * functions to dump contents of various structures. 
2355  * In debug build (linked with crt debug library) will dump allocated but not freed memory
2356  */
2357 extern int cm_DumpSCache(FILE *outputFile, char *cookie, int lock);
2358 extern int cm_DumpBufHashTable(FILE *outputFile, char *cookie, int lock);
2359 extern int smb_DumpVCP(FILE *outputFile, char *cookie, int lock);
2360
2361 long cm_IoctlMemoryDump(struct smb_ioctl *ioctlp, struct cm_user *userp)
2362 {
2363     long inValue = 0;
2364     HANDLE hLogFile;
2365     char logfileName[MAX_PATH+1];
2366     char *cookie;
2367     DWORD dwSize;
2368   
2369 #ifdef _DEBUG  
2370     static _CrtMemState memstate;
2371 #endif
2372   
2373     cm_SkipIoctlPath(ioctlp);
2374     memcpy(&inValue, ioctlp->inDatap, sizeof(long));
2375   
2376     dwSize = GetEnvironmentVariable("TEMP", logfileName, sizeof(logfileName));
2377     if ( dwSize == 0 || dwSize > sizeof(logfileName) )
2378     {
2379         GetWindowsDirectory(logfileName, sizeof(logfileName));
2380     }
2381     strncat(logfileName, "\\afsd_alloc.log", sizeof(logfileName));
2382
2383     hLogFile = CreateFile(logfileName, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2384   
2385     if (!hLogFile)
2386     {
2387       /* error */
2388       inValue = -1;
2389       memcpy(ioctlp->outDatap, &inValue, sizeof(long));
2390       ioctlp->outDatap += sizeof(long);
2391       
2392       return 0;               
2393     }
2394   
2395     SetFilePointer(hLogFile, 0, NULL, FILE_END);
2396   
2397     cookie = inValue ? "b" : "e";
2398   
2399 #ifdef _DEBUG  
2400   
2401     if (inValue)
2402     {
2403       _CrtMemCheckpoint(&memstate);           
2404     }
2405     else
2406     {
2407         _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
2408         _CrtSetReportFile(_CRT_WARN, hLogFile);
2409         _CrtMemDumpAllObjectsSince(&memstate);
2410     }
2411 #endif
2412   
2413     /* dump all interesting data */
2414     cm_DumpSCache(hLogFile, cookie, 1);
2415     cm_DumpBufHashTable(hLogFile, cookie, 1);
2416     smb_DumpVCP(hLogFile, cookie, 1);
2417
2418     CloseHandle(hLogFile);                          
2419   
2420     memcpy(ioctlp->outDatap, &inValue, sizeof(long));
2421     ioctlp->outDatap += sizeof(long);
2422   
2423     return 0;
2424 }