1d09f9c58decb7a047b07df96e28a051fdc93713
[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             if (cm_GetRootCellName(ioctlp->outDatap))
1218                 StringCbCopyA(ioctlp->outDatap, 999999, "Freelance.Local.Root");
1219             ioctlp->outDatap += strlen(ioctlp->outDatap) +1;
1220         } else if (cm_data.rootCellp) {
1221             /* return the default cellname to the caller */
1222             StringCbCopyA(ioctlp->outDatap, 999999, cm_data.rootCellp->name);
1223             ioctlp->outDatap += strlen(ioctlp->outDatap) +1;
1224         } else {
1225             /* if we don't know our default cell, return failure */
1226             code = CM_ERROR_NOSUCHCELL;
1227     }
1228
1229     return code;
1230 }
1231
1232 long cm_IoctlSysName(struct smb_ioctl *ioctlp, struct cm_user *userp)
1233 {
1234     long setSysName, foundname = 0;
1235     char *cp, *cp2, inname[MAXSYSNAME], outname[MAXSYSNAME];
1236     int t, count, num = 0;
1237     char **sysnamelist[MAXSYSNAME];
1238         
1239     cm_SkipIoctlPath(ioctlp);
1240
1241     memcpy(&setSysName, ioctlp->inDatap, sizeof(long));
1242     ioctlp->inDatap += sizeof(long);
1243         
1244     if (setSysName) {
1245         /* check my args */
1246         if ( setSysName < 0 || setSysName > MAXNUMSYSNAMES )
1247             return EINVAL;
1248         cp2 = ioctlp->inDatap;
1249         for ( cp=ioctlp->inDatap, count = 0; count < setSysName; count++ ) {
1250             /* won't go past end of ioctlp->inDatap since maxsysname*num < ioctlp->inDatap length */
1251             t = strlen(cp);
1252             if (t >= MAXSYSNAME || t <= 0)
1253                 return EINVAL;
1254             /* check for names that can shoot us in the foot */
1255             if (*cp == '.' && (cp[1] == 0 || (cp[1] == '.' && cp[2] == 0)))
1256                 return EINVAL;
1257             cp += t + 1;
1258         }
1259         /* args ok */
1260
1261         /* inname gets first entry in case we're being a translator */
1262         /* (we are never a translator) */
1263         t = strlen(ioctlp->inDatap);
1264         memcpy(inname, ioctlp->inDatap, t + 1);
1265         ioctlp->inDatap += t + 1;
1266         num = count;
1267     }
1268
1269     /* Not xlating, so local case */
1270     if (!cm_sysName)
1271         osi_panic("cm_IoctlSysName: !cm_sysName\n", __FILE__, __LINE__);
1272
1273     if (!setSysName) {      /* user just wants the info */
1274         StringCbCopyA(outname, sizeof(outname), cm_sysName);
1275         foundname = cm_sysNameCount;
1276         *sysnamelist = cm_sysNameList;
1277     } else {        
1278         /* Local guy; only root can change sysname */
1279         /* clear @sys entries from the dnlc, once afs_lookup can
1280          * do lookups of @sys entries and thinks it can trust them */
1281         /* privs ok, store the entry, ... */
1282         StringCbCopyA(cm_sysName, sizeof(cm_sysName), inname);
1283         StringCbCopyA(cm_sysNameList[0], MAXSYSNAME, inname);
1284         if (setSysName > 1) {       /* ... or list */
1285             cp = ioctlp->inDatap;
1286             for (count = 1; count < setSysName; ++count) {
1287                 if (!cm_sysNameList[count])
1288                     osi_panic("cm_IoctlSysName: no cm_sysNameList entry to write\n",
1289                                __FILE__, __LINE__);
1290                 t = strlen(cp);
1291                 StringCbCopyA(cm_sysNameList[count], MAXSYSNAME, cp);
1292                 cp += t + 1;
1293             }
1294         }
1295         cm_sysNameCount = setSysName;
1296     }
1297
1298     if (!setSysName) {
1299         /* return the sysname to the caller */
1300         cp = ioctlp->outDatap;
1301         memcpy(cp, (char *)&foundname, sizeof(afs_int32));
1302         cp += sizeof(afs_int32);        /* skip found flag */
1303         if (foundname) {
1304             StringCbCopyA(cp, 999999, outname);
1305             cp += strlen(outname) + 1;  /* skip name and terminating null char */
1306             for ( count=1; count < foundname ; ++count) {   /* ... or list */
1307                 if ( !(*sysnamelist)[count] )
1308                     osi_panic("cm_IoctlSysName: no cm_sysNameList entry to read\n", 
1309                                __FILE__, __LINE__);
1310                 t = strlen((*sysnamelist)[count]);
1311                 if (t >= MAXSYSNAME)
1312                     osi_panic("cm_IoctlSysName: sysname entry garbled\n", 
1313                                __FILE__, __LINE__);
1314                 StringCbCopyA(cp, 999999, (*sysnamelist)[count]);
1315                 cp += t + 1;
1316             }
1317         }
1318         ioctlp->outDatap = cp;
1319     }
1320         
1321     /* done: success */
1322     return 0;
1323 }
1324
1325 long cm_IoctlGetCellStatus(struct smb_ioctl *ioctlp, struct cm_user *userp)
1326 {
1327     long temp;
1328     cm_cell_t *cellp;
1329
1330     cm_SkipIoctlPath(ioctlp);
1331
1332     cellp = cm_GetCell(ioctlp->inDatap, 0);
1333     if (!cellp) 
1334         return CM_ERROR_NOSUCHCELL;
1335
1336     temp = 0;
1337     lock_ObtainMutex(&cellp->mx);
1338     if (cellp->flags & CM_CELLFLAG_SUID)
1339         temp |= CM_SETCELLFLAG_SUID;
1340     lock_ReleaseMutex(&cellp->mx);
1341         
1342     /* now copy out parm */
1343     memcpy(ioctlp->outDatap, &temp, sizeof(long));
1344     ioctlp->outDatap += sizeof(long);
1345
1346     return 0;
1347 }
1348
1349 long cm_IoctlSetCellStatus(struct smb_ioctl *ioctlp, struct cm_user *userp)
1350 {
1351     long temp;
1352     cm_cell_t *cellp;
1353
1354     cm_SkipIoctlPath(ioctlp);
1355
1356     cellp = cm_GetCell(ioctlp->inDatap + 2*sizeof(long), 0);
1357     if (!cellp) 
1358         return CM_ERROR_NOSUCHCELL;
1359
1360     memcpy((char *)&temp, ioctlp->inDatap, sizeof(long));
1361
1362     lock_ObtainMutex(&cellp->mx);
1363     if (temp & CM_SETCELLFLAG_SUID)
1364         cellp->flags |= CM_CELLFLAG_SUID;
1365     else
1366         cellp->flags &= ~CM_CELLFLAG_SUID;
1367     lock_ReleaseMutex(&cellp->mx);
1368
1369     return 0;
1370 }
1371
1372 long cm_IoctlSetSPrefs(struct smb_ioctl *ioctlp, struct cm_user *userp)
1373 {
1374     cm_SSetPref_t         *spin; /* input */
1375     cm_SPref_t        *srvin;   /* one input component */
1376     cm_server_t       *tsp;
1377     int                   i, vlonly, noServers, type;
1378     struct sockaddr_in  tmp;
1379     unsigned short        rank;
1380
1381     cm_SkipIoctlPath(ioctlp);       /* we don't care about the path */
1382
1383     spin           = (cm_SSetPref_t *)ioctlp->inDatap;
1384     noServers  = spin->num_servers;
1385     vlonly     = spin->flags;
1386     if ( vlonly )
1387         type = CM_SERVER_VLDB;
1388     else    
1389         type = CM_SERVER_FILE;
1390
1391     for ( i=0; i < noServers; i++) 
1392     {
1393         srvin          = &(spin->servers[i]);
1394         rank           = srvin->rank + (rand() & 0x000f);
1395         tmp.sin_addr   = srvin->host;
1396         tmp.sin_family = AF_INET;
1397
1398         tsp = cm_FindServer(&tmp, type);
1399         if ( tsp )              /* an existing server - ref count increased */
1400         {
1401             tsp->ipRank = rank; /* no need to protect by mutex*/
1402
1403             if (type == CM_SERVER_FILE)
1404             {   /* fileserver */
1405                 /* find volumes which might have RO copy 
1406                 /* on server and change the ordering of 
1407                  * their RO list 
1408                  */
1409                 cm_ChangeRankVolume(tsp);
1410             }
1411             else        
1412             {
1413                 /* set preferences for an existing vlserver */
1414                 cm_ChangeRankCellVLServer(tsp);
1415             }
1416             cm_PutServer(tsp);  /* decrease refcount */
1417         }
1418         else    /* add a new server without a cell */
1419         {
1420             tsp = cm_NewServer(&tmp, type, NULL); /* refcount = 1 */
1421             tsp->ipRank = rank;
1422         }
1423     }
1424     return 0;
1425 }
1426
1427 long cm_IoctlGetSPrefs(struct smb_ioctl *ioctlp, struct cm_user *userp)
1428 {
1429     cm_SPrefRequest_t *spin; /* input */
1430     cm_SPrefInfo_t    *spout;   /* output */
1431     cm_SPref_t        *srvout;   /* one output component */
1432     cm_server_t       *tsp;
1433     int                   i, vlonly, noServers;
1434
1435     cm_SkipIoctlPath(ioctlp);       /* we don't care about the path */
1436
1437     spin      = (cm_SPrefRequest_t *)ioctlp->inDatap;
1438     spout     = (cm_SPrefInfo_t *) ioctlp->outDatap;
1439     srvout    = spout->servers;
1440     noServers = spin->num_servers; 
1441     vlonly    = spin->flags & CM_SPREF_VLONLY;
1442     spout->num_servers = 0;
1443
1444     lock_ObtainRead(&cm_serverLock); /* get server lock */
1445
1446     for (tsp=cm_allServersp, i=0; tsp && noServers; tsp=tsp->allNextp,i++){
1447         if (spin->offset > i) {
1448             continue;    /* catch up to where we left off */
1449         }
1450
1451         if ( vlonly && (tsp->type == CM_SERVER_FILE) )
1452             continue;   /* ignore fileserver for -vlserver option*/
1453         if ( !vlonly && (tsp->type == CM_SERVER_VLDB) )
1454             continue;   /* ignore vlservers */
1455
1456         srvout->host = tsp->addr.sin_addr;
1457         srvout->rank = tsp->ipRank;
1458         srvout++;       
1459         spout->num_servers++;
1460         noServers--;
1461     }
1462     lock_ReleaseRead(&cm_serverLock); /* release server lock */
1463
1464     if ( tsp )  /* we ran out of space in the output buffer */
1465         spout->next_offset = i;
1466     else    
1467         spout->next_offset = 0; 
1468     ioctlp->outDatap += sizeof(cm_SPrefInfo_t) + 
1469         (spout->num_servers -1 ) * sizeof(cm_SPref_t) ;
1470     return 0;
1471 }
1472
1473 long cm_IoctlStoreBehind(struct smb_ioctl *ioctlp, struct cm_user *userp)
1474 {
1475     /* we ignore default asynchrony since we only have one way
1476      * of doing this today.
1477      */
1478     return 0;
1479 }       
1480
1481 long cm_IoctlCreateMountPoint(struct smb_ioctl *ioctlp, struct cm_user *userp)
1482 {
1483     char leaf[LEAF_SIZE];
1484     long code;
1485     cm_scache_t *dscp;
1486     cm_attr_t tattr;
1487     char *cp;
1488     cm_req_t req;
1489     char mpInfo[256];
1490     char fullCell[256];
1491     char volume[256];
1492     char cell[256];
1493     int ttl;
1494
1495     cm_InitReq(&req);
1496         
1497     code = cm_ParseIoctlParent(ioctlp, userp, &req, &dscp, leaf);
1498     if (code) return code;
1499
1500     /* Translate chars for the mount point name */
1501     TranslateExtendedChars(leaf);
1502
1503     /* 
1504      * The fs command allows the user to specify partial cell names on NT.  These must
1505      * be expanded to the full cell name for mount points so that the mount points will
1506      * work on UNIX clients.
1507      */
1508
1509     /* Extract the possibly partial cell name */
1510     StringCbCopyA(cell, sizeof(cell), ioctlp->inDatap + 1);      /* Skip the mp type character */
1511         
1512     if (cp = strchr(cell, ':')) {
1513         /* Extract the volume name */
1514         *cp = 0;
1515         StringCbCopyA(volume,  sizeof(volume), cp + 1);
1516         
1517         /* Get the full name for this cell */
1518         code = cm_SearchCellFile(cell, fullCell, 0, 0);
1519 #ifdef AFS_AFSDB_ENV
1520         if (code && cm_dnsEnabled)
1521             code = cm_SearchCellByDNS(cell, fullCell, &ttl, 0, 0);
1522 #endif
1523         if (code)
1524             return CM_ERROR_NOSUCHCELL;
1525         
1526         StringCbPrintfA(mpInfo, sizeof(mpInfo), "%c%s:%s", *ioctlp->inDatap, fullCell, volume);
1527     } else {
1528         /* No cell name specified */
1529         StringCbCopyA(mpInfo, sizeof(mpInfo), ioctlp->inDatap);
1530     }
1531
1532 #ifdef AFS_FREELANCE_CLIENT
1533     if (cm_freelanceEnabled && dscp == cm_data.rootSCachep) {
1534         /* we are adding the mount point to the root dir., so call
1535          * the freelance code to do the add. */
1536         osi_Log0(afsd_logp,"IoctlCreateMountPoint within Freelance root dir");
1537         code = cm_FreelanceAddMount(leaf, fullCell, volume, 
1538                                     *ioctlp->inDatap == '%', NULL);
1539         return code;
1540     }
1541 #endif
1542     /* create the symlink with mode 644.  The lack of X bits tells
1543      * us that it is a mount point.
1544      */
1545     tattr.mask = CM_ATTRMASK_UNIXMODEBITS | CM_ATTRMASK_CLIENTMODTIME;
1546     tattr.unixModeBits = 0644;
1547     tattr.clientModTime = time(NULL);
1548
1549     code = cm_SymLink(dscp, leaf, mpInfo, 0, &tattr, userp, &req);
1550     if (code == 0 && (dscp->flags & CM_SCACHEFLAG_ANYWATCH))
1551         smb_NotifyChange(FILE_ACTION_ADDED,
1552                          FILE_NOTIFY_CHANGE_DIR_NAME,
1553                          dscp, leaf, NULL, TRUE);
1554
1555     cm_ReleaseSCache(dscp);
1556     return code;
1557 }
1558
1559 long cm_IoctlSymlink(struct smb_ioctl *ioctlp, struct cm_user *userp)
1560 {
1561     char leaf[LEAF_SIZE];
1562     long code;
1563     cm_scache_t *dscp;
1564     cm_attr_t tattr;
1565     char *cp;
1566     cm_req_t req;
1567
1568     cm_InitReq(&req);
1569
1570     code = cm_ParseIoctlParent(ioctlp, userp, &req, &dscp, leaf);
1571     if (code) return code;
1572
1573     /* Translate chars for the link name */
1574     TranslateExtendedChars(leaf);
1575
1576     /* Translate chars for the linked to name */
1577     TranslateExtendedChars(ioctlp->inDatap);
1578
1579     cp = ioctlp->inDatap;               /* contents of link */
1580
1581 #ifdef AFS_FREELANCE_CLIENT
1582     if (cm_freelanceEnabled && dscp == cm_data.rootSCachep) {
1583         /* we are adding the symlink to the root dir., so call
1584          * the freelance code to do the add. */
1585         if (cp[0] == cp[1] && cp[1] == '\\' && 
1586             !_strnicmp(cm_NetbiosName,cp+2,strlen(cm_NetbiosName))) 
1587         {
1588             /* skip \\AFS\ or \\AFS\all\ */
1589             char * p;
1590             p = cp + 2 + strlen(cm_NetbiosName) + 1;
1591             if ( !_strnicmp("all", p, 3) )
1592                 p += 4;
1593             cp = p;
1594         }
1595         osi_Log0(afsd_logp,"IoctlCreateSymlink within Freelance root dir");
1596         code = cm_FreelanceAddSymlink(leaf, cp, NULL);
1597         return code;
1598     }
1599 #endif
1600
1601     /* Create symlink with mode 0755. */
1602     tattr.mask = CM_ATTRMASK_UNIXMODEBITS;
1603     tattr.unixModeBits = 0755;
1604
1605     code = cm_SymLink(dscp, leaf, cp, 0, &tattr, userp, &req);
1606     if (code == 0 && (dscp->flags & CM_SCACHEFLAG_ANYWATCH))
1607         smb_NotifyChange(FILE_ACTION_ADDED,
1608                           FILE_NOTIFY_CHANGE_FILE_NAME
1609                           | FILE_NOTIFY_CHANGE_DIR_NAME,
1610                           dscp, leaf, NULL, TRUE);
1611
1612     cm_ReleaseSCache(dscp);
1613
1614     return code;
1615 }
1616
1617
1618 long cm_IoctlListlink(struct smb_ioctl *ioctlp, struct cm_user *userp)
1619 {
1620     long code;
1621     cm_scache_t *dscp;
1622     cm_scache_t *scp;
1623     char *cp;
1624     cm_space_t *spacep;
1625     cm_scache_t *newRootScp;
1626     cm_req_t req;
1627
1628     cm_InitReq(&req);
1629
1630     code = cm_ParseIoctlPath(ioctlp, userp, &req, &dscp);
1631     if (code) return code;
1632
1633     cp = ioctlp->inDatap;
1634
1635     code = cm_Lookup(dscp, cp, CM_FLAG_NOMOUNTCHASE, userp, &req, &scp);
1636     cm_ReleaseSCache(dscp);
1637     if (code) return code;
1638
1639     /* Check that it's a real symlink */
1640     if (scp->fileType != CM_SCACHETYPE_SYMLINK &&
1641         scp->fileType != CM_SCACHETYPE_DFSLINK &&
1642         scp->fileType != CM_SCACHETYPE_INVALID) {
1643         cm_ReleaseSCache(scp);
1644         return CM_ERROR_INVAL;
1645     }
1646
1647     code = cm_AssembleLink(scp, "", &newRootScp, &spacep, userp, &req);
1648     cm_ReleaseSCache(scp);
1649     if (code == 0) {
1650         cp = ioctlp->outDatap;
1651         if (newRootScp != NULL) {
1652             StringCbCopyA(cp, 999999, cm_mountRoot);
1653             StringCbCatA(cp, 999999, "/");
1654             cp += strlen(cp);
1655         }
1656         StringCbCopyA(cp, 999999, spacep->data);
1657         cp += strlen(cp) + 1;
1658         ioctlp->outDatap = cp;
1659         cm_FreeSpace(spacep);
1660         if (newRootScp != NULL)
1661             cm_ReleaseSCache(newRootScp);
1662         code = 0;
1663     } else if (code == CM_ERROR_PATH_NOT_COVERED && 
1664                 scp->fileType == CM_SCACHETYPE_DFSLINK ||
1665                code == CM_ERROR_NOSUCHPATH &&
1666                 scp->fileType == CM_SCACHETYPE_INVALID) {
1667         cp = ioctlp->outDatap;
1668         StringCbCopyA(cp, 999999, spacep->data);
1669         cp += strlen(cp) + 1;
1670         ioctlp->outDatap = cp;
1671         cm_FreeSpace(spacep);
1672         if (newRootScp != NULL)
1673             cm_ReleaseSCache(newRootScp);
1674         code = 0;
1675     }
1676
1677     return code;
1678 }
1679
1680 long cm_IoctlIslink(struct smb_ioctl *ioctlp, struct cm_user *userp)
1681 {/*CHECK FOR VALID SYMLINK*/
1682     long code;
1683     cm_scache_t *dscp;
1684     cm_scache_t *scp;
1685     char *cp;
1686     cm_req_t req;
1687
1688     cm_InitReq(&req);
1689
1690     code = cm_ParseIoctlPath(ioctlp, userp, &req, &dscp);
1691     if (code) return code;
1692
1693     cp = ioctlp->inDatap;
1694     osi_LogEvent("cm_IoctlListlink",NULL," name[%s]",cp);
1695
1696     code = cm_Lookup(dscp, cp, CM_FLAG_NOMOUNTCHASE, userp, &req, &scp);
1697     cm_ReleaseSCache(dscp);
1698     if (code) return code;
1699
1700     /* Check that it's a real symlink */
1701     if (scp->fileType != CM_SCACHETYPE_SYMLINK &&
1702         scp->fileType != CM_SCACHETYPE_DFSLINK &&
1703         scp->fileType != CM_SCACHETYPE_INVALID)
1704         code = CM_ERROR_INVAL;
1705     cm_ReleaseSCache(scp);
1706     return code;
1707 }
1708
1709 long cm_IoctlDeletelink(struct smb_ioctl *ioctlp, struct cm_user *userp)
1710 {
1711     long code;
1712     cm_scache_t *dscp;
1713     cm_scache_t *scp;
1714     char *cp;
1715     cm_req_t req;
1716
1717     cm_InitReq(&req);
1718
1719     code = cm_ParseIoctlPath(ioctlp, userp, &req, &dscp);
1720     if (code) return code;
1721
1722     cp = ioctlp->inDatap;
1723
1724 #ifdef AFS_FREELANCE_CLIENT
1725     if (cm_freelanceEnabled && dscp == cm_data.rootSCachep) {
1726         /* we are adding the mount point to the root dir., so call
1727          * the freelance code to do the add. */
1728         osi_Log0(afsd_logp,"IoctlDeletelink from Freelance root dir");
1729         code = cm_FreelanceRemoveSymlink(cp);
1730         return code;
1731     }
1732 #endif
1733
1734     code = cm_Lookup(dscp, cp, CM_FLAG_NOMOUNTCHASE, userp, &req, &scp);
1735         
1736     /* if something went wrong, bail out now */
1737     if (code) {
1738         goto done;
1739     }
1740         
1741     lock_ObtainMutex(&scp->mx);
1742     code = cm_SyncOp(scp, NULL, userp, &req, 0,
1743                       CM_SCACHESYNC_NEEDCALLBACK | CM_SCACHESYNC_GETSTATUS);
1744     if (code) {     
1745         lock_ReleaseMutex(&scp->mx);
1746         cm_ReleaseSCache(scp);
1747         goto done;
1748     }
1749         
1750     /* now check that this is a real symlink */
1751     if (scp->fileType != CM_SCACHETYPE_SYMLINK &&
1752         scp->fileType != CM_SCACHETYPE_DFSLINK &&
1753         scp->fileType != CM_SCACHETYPE_INVALID) {
1754         lock_ReleaseMutex(&scp->mx);
1755         cm_ReleaseSCache(scp);
1756         code = CM_ERROR_INVAL;
1757         goto done;
1758     }
1759         
1760     /* time to make the RPC, so drop the lock */
1761     lock_ReleaseMutex(&scp->mx);
1762     cm_ReleaseSCache(scp);
1763         
1764     /* easier to do it this way */
1765     code = cm_Unlink(dscp, cp, userp, &req);
1766     if (code == 0 && (dscp->flags & CM_SCACHEFLAG_ANYWATCH))
1767         smb_NotifyChange(FILE_ACTION_REMOVED,
1768                           FILE_NOTIFY_CHANGE_FILE_NAME
1769                           | FILE_NOTIFY_CHANGE_DIR_NAME,
1770                           dscp, cp, NULL, TRUE);
1771
1772   done:
1773     cm_ReleaseSCache(dscp);
1774     return code;
1775 }
1776
1777 long cm_IoctlSetToken(struct smb_ioctl *ioctlp, struct cm_user *userp)
1778 {
1779     char *saveDataPtr;
1780     char *tp;
1781     int ticketLen;
1782     char *ticket;
1783     int ctSize;
1784     struct ClearToken ct;
1785     cm_cell_t *cellp;
1786     cm_ucell_t *ucellp;
1787     char *uname = NULL;
1788     afs_uuid_t uuid;
1789     int flags;
1790     char sessionKey[8];
1791     char *smbname;
1792
1793     saveDataPtr = ioctlp->inDatap;
1794
1795     cm_SkipIoctlPath(ioctlp);
1796
1797     tp = ioctlp->inDatap;
1798
1799     /* ticket length */
1800     memcpy(&ticketLen, tp, sizeof(ticketLen));
1801     tp += sizeof(ticketLen);
1802     if (ticketLen < MINKTCTICKETLEN || ticketLen > MAXKTCTICKETLEN)
1803         return CM_ERROR_INVAL;
1804
1805     /* remember ticket and skip over it for now */
1806     ticket = tp;
1807     tp += ticketLen;
1808
1809     /* clear token size */
1810     memcpy(&ctSize, tp, sizeof(ctSize));
1811     tp += sizeof(ctSize);
1812     if (ctSize != sizeof(struct ClearToken))
1813         return CM_ERROR_INVAL;
1814
1815     /* clear token */
1816     memcpy(&ct, tp, ctSize);
1817     tp += ctSize;
1818     if (ct.AuthHandle == -1)
1819         ct.AuthHandle = 999;    /* more rxvab compat stuff */
1820
1821     /* more stuff, if any */
1822     if (ioctlp->inCopied > tp - saveDataPtr) {
1823         /* flags:  logon flag */
1824         memcpy(&flags, tp, sizeof(int));
1825         tp += sizeof(int);
1826
1827         /* cell name */
1828         cellp = cm_GetCell(tp, CM_FLAG_CREATE);
1829         if (!cellp) return CM_ERROR_NOSUCHCELL;
1830         tp += strlen(tp) + 1;
1831
1832         /* user name */
1833         uname = tp;
1834         tp += strlen(tp) + 1;
1835
1836 #ifndef AFSIFS                  /* no SMB username */
1837         if (flags & PIOCTL_LOGON) {
1838             /* SMB user name with which to associate tokens */
1839             smbname = tp;
1840             osi_Log2(smb_logp,"cm_IoctlSetToken for user [%s] smbname [%s]",
1841                      osi_LogSaveString(smb_logp,uname), osi_LogSaveString(smb_logp,smbname));
1842             fprintf(stderr, "SMB name = %s\n", smbname);
1843             tp += strlen(tp) + 1;
1844         } else {
1845             osi_Log1(smb_logp,"cm_IoctlSetToken for user [%s]",
1846                      osi_LogSaveString(smb_logp,uname));
1847         }
1848 #endif
1849
1850 #ifndef DJGPP   /* for win95, session key is back in pioctl */
1851                 /* uuid */
1852         memcpy(&uuid, tp, sizeof(uuid));
1853         if (!cm_FindTokenEvent(uuid, sessionKey))
1854             return CM_ERROR_INVAL;
1855 #endif /* !DJGPP */
1856     } else {
1857         cellp = cm_data.rootCellp;
1858         osi_Log0(smb_logp,"cm_IoctlSetToken - no name specified");
1859     }
1860
1861     if (flags & PIOCTL_LOGON) {
1862         userp = smb_FindCMUserByName(smbname, ioctlp->fidp->vcp->rname);
1863     }
1864
1865     /* store the token */
1866     lock_ObtainMutex(&userp->mx);
1867     ucellp = cm_GetUCell(userp, cellp);
1868     osi_Log1(smb_logp,"cm_IoctlSetToken ucellp %lx", ucellp);
1869     ucellp->ticketLen = ticketLen;
1870     if (ucellp->ticketp)
1871         free(ucellp->ticketp);  /* Discard old token if any */
1872     ucellp->ticketp = malloc(ticketLen);
1873     memcpy(ucellp->ticketp, ticket, ticketLen);
1874 #ifndef DJGPP
1875     /*
1876      * Get the session key from the RPC, rather than from the pioctl.
1877      */
1878     /*
1879     memcpy(&ucellp->sessionKey, ct.HandShakeKey, sizeof(ct.HandShakeKey));
1880     */
1881     memcpy(ucellp->sessionKey.data, sessionKey, sizeof(sessionKey));
1882 #else
1883     /* for win95, we are getting the session key from the pioctl */
1884     memcpy(&ucellp->sessionKey, ct.HandShakeKey, sizeof(ct.HandShakeKey));
1885 #endif /* !DJGPP */
1886     ucellp->kvno = ct.AuthHandle;
1887     ucellp->expirationTime = ct.EndTimestamp;
1888     ucellp->gen++;
1889     if (uname) 
1890         StringCbCopyA(ucellp->userName, MAXKTCNAMELEN, uname);
1891     ucellp->flags |= CM_UCELLFLAG_RXKAD;
1892     lock_ReleaseMutex(&userp->mx);
1893
1894     if (flags & PIOCTL_LOGON) {
1895         ioctlp->flags |= SMB_IOCTLFLAG_LOGON;
1896     }
1897
1898     cm_ResetACLCache(userp);
1899
1900     return 0;
1901 }
1902
1903 long cm_IoctlGetTokenIter(struct smb_ioctl *ioctlp, struct cm_user *userp)
1904 {
1905     char *tp, *cp;
1906     int iterator;
1907     int temp;
1908     cm_ucell_t *ucellp;
1909     struct ClearToken ct;
1910
1911     cm_SkipIoctlPath(ioctlp);
1912
1913     tp = ioctlp->inDatap;
1914     cp = ioctlp->outDatap;
1915
1916     /* iterator */
1917     memcpy(&iterator, tp, sizeof(iterator));
1918     tp += sizeof(iterator);
1919
1920     lock_ObtainMutex(&userp->mx);
1921
1922     /* look for token */
1923     for (;;iterator++) {
1924         ucellp = cm_FindUCell(userp, iterator);
1925         if (!ucellp) {
1926             lock_ReleaseMutex(&userp->mx);
1927             return CM_ERROR_NOMORETOKENS;
1928         }
1929         if (ucellp->flags & CM_UCELLFLAG_RXKAD)
1930             break;
1931     }       
1932
1933     /* new iterator */
1934     temp = ucellp->iterator + 1;
1935     memcpy(cp, &temp, sizeof(temp));
1936     cp += sizeof(temp);
1937
1938     /* ticket length */
1939     memcpy(cp, &ucellp->ticketLen, sizeof(ucellp->ticketLen));
1940     cp += sizeof(ucellp->ticketLen);
1941
1942     /* ticket */
1943     memcpy(cp, ucellp->ticketp, ucellp->ticketLen);
1944     cp += ucellp->ticketLen;
1945
1946     /* clear token size */
1947     temp = sizeof(ct);
1948     memcpy(cp, &temp, sizeof(temp));
1949     cp += sizeof(temp);
1950
1951     /* clear token */
1952     ct.AuthHandle = ucellp->kvno;
1953 #ifndef DJGPP
1954     /*
1955      * Don't give out a real session key here
1956      */
1957     /*
1958     memcpy(ct.HandShakeKey, &ucellp->sessionKey, sizeof(ct.HandShakeKey));
1959     */
1960     memset(ct.HandShakeKey, 0, sizeof(ct.HandShakeKey));
1961 #else
1962     memcpy(ct.HandShakeKey, &ucellp->sessionKey, sizeof(ct.HandShakeKey));
1963 #endif /* !DJGPP */
1964     ct.ViceId = 37;                     /* XXX */
1965     ct.BeginTimestamp = 0;              /* XXX */
1966     ct.EndTimestamp = ucellp->expirationTime;
1967     memcpy(cp, &ct, sizeof(ct));
1968     cp += sizeof(ct);
1969
1970     /* Primary flag (unused) */
1971     temp = 0;
1972     memcpy(cp, &temp, sizeof(temp));
1973     cp += sizeof(temp);
1974
1975     /* cell name */
1976     StringCbCopyA(cp, 999999, ucellp->cellp->name);
1977     cp += strlen(cp) + 1;
1978
1979     /* user name */
1980     StringCbCopyA(cp, 999999, ucellp->userName);
1981     cp += strlen(cp) + 1;
1982
1983     ioctlp->outDatap = cp;
1984
1985     lock_ReleaseMutex(&userp->mx);
1986
1987     return 0;
1988 }
1989
1990 long cm_IoctlGetToken(struct smb_ioctl *ioctlp, struct cm_user *userp)
1991 {
1992     char *cp;
1993     int temp;
1994     cm_cell_t *cellp;
1995     cm_ucell_t *ucellp;
1996     struct ClearToken ct;
1997     char *tp;
1998 #ifndef DJGPP
1999     afs_uuid_t uuid;
2000 #endif /* !DJGPP */
2001
2002     cm_SkipIoctlPath(ioctlp);
2003
2004     tp = ioctlp->inDatap;
2005
2006     cp = ioctlp->outDatap;
2007
2008     /* cell name is right here */
2009     cellp = cm_GetCell(tp, 0);
2010     if (!cellp) 
2011         return CM_ERROR_NOSUCHCELL;
2012     tp += strlen(tp) + 1;
2013
2014 #ifndef DJGPP
2015     /* uuid */
2016     memcpy(&uuid, tp, sizeof(uuid));
2017 #endif /* !DJGPP */
2018
2019     lock_ObtainMutex(&userp->mx);
2020
2021     ucellp = cm_GetUCell(userp, cellp);
2022     if (!ucellp || !(ucellp->flags & CM_UCELLFLAG_RXKAD)) {
2023         lock_ReleaseMutex(&userp->mx);
2024         return CM_ERROR_NOMORETOKENS;
2025     }
2026
2027     /* ticket length */
2028     memcpy(cp, &ucellp->ticketLen, sizeof(ucellp->ticketLen));
2029     cp += sizeof(ucellp->ticketLen);
2030
2031     /* ticket */
2032     memcpy(cp, ucellp->ticketp, ucellp->ticketLen);
2033     cp += ucellp->ticketLen;
2034
2035     /* clear token size */
2036     temp = sizeof(ct);
2037     memcpy(cp, &temp, sizeof(temp));
2038     cp += sizeof(temp);
2039
2040     /* clear token */
2041     ct.AuthHandle = ucellp->kvno;
2042 #ifndef DJGPP
2043     /*
2044      * Don't give out a real session key here
2045      */
2046     /*
2047     memcpy(ct.HandShakeKey, &ucellp->sessionKey, sizeof(ct.HandShakeKey));
2048     */
2049     memset(ct.HandShakeKey, 0, sizeof(ct.HandShakeKey));
2050 #else
2051     memcpy(ct.HandShakeKey, &ucellp->sessionKey, sizeof(ct.HandShakeKey));
2052 #endif /* !DJGPP */
2053     ct.ViceId = 37;                     /* XXX */
2054     ct.BeginTimestamp = 0;              /* XXX */
2055     ct.EndTimestamp = ucellp->expirationTime;
2056     memcpy(cp, &ct, sizeof(ct));
2057     cp += sizeof(ct);
2058
2059     /* Primary flag (unused) */
2060     temp = 0;
2061     memcpy(cp, &temp, sizeof(temp));
2062     cp += sizeof(temp);
2063
2064     /* cell name */
2065     StringCbCopyA(cp, 999999, ucellp->cellp->name);
2066     cp += strlen(cp) + 1;
2067
2068     /* user name */
2069     StringCbCopyA(cp, 999999, ucellp->userName);
2070     cp += strlen(cp) + 1;
2071
2072     ioctlp->outDatap = cp;
2073
2074     lock_ReleaseMutex(&userp->mx);
2075
2076 #ifndef DJGPP
2077     cm_RegisterNewTokenEvent(uuid, ucellp->sessionKey.data);
2078 #endif /* !DJGPP */
2079
2080     return 0;
2081 }
2082
2083 long cm_IoctlDelToken(struct smb_ioctl *ioctlp, struct cm_user *userp)
2084 {
2085     char *cp;
2086     cm_cell_t *cellp;
2087     cm_ucell_t *ucellp;
2088
2089     cm_SkipIoctlPath(ioctlp);
2090
2091     cp = ioctlp->outDatap;
2092
2093     /* cell name is right here */
2094     cellp = cm_GetCell(ioctlp->inDatap, 0);
2095     if (!cellp) return CM_ERROR_NOSUCHCELL;
2096
2097     lock_ObtainMutex(&userp->mx);
2098
2099     ucellp = cm_GetUCell(userp, cellp);
2100     if (!ucellp) {
2101         lock_ReleaseMutex(&userp->mx);
2102         return CM_ERROR_NOMORETOKENS;
2103     }
2104
2105     osi_Log1(smb_logp,"cm_IoctlDelToken ucellp %lx", ucellp);
2106
2107     if (ucellp->ticketp) {
2108         free(ucellp->ticketp);
2109         ucellp->ticketp = NULL;
2110     }
2111     ucellp->flags &= ~CM_UCELLFLAG_RXKAD;
2112     ucellp->gen++;
2113
2114     lock_ReleaseMutex(&userp->mx);
2115
2116     cm_ResetACLCache(userp);
2117
2118     return 0;
2119 }
2120
2121 long cm_IoctlDelAllToken(struct smb_ioctl *ioctlp, struct cm_user *userp)
2122 {
2123     cm_ucell_t *ucellp;
2124
2125     lock_ObtainMutex(&userp->mx);
2126
2127     for (ucellp = userp->cellInfop; ucellp; ucellp = ucellp->nextp) {
2128         osi_Log1(smb_logp,"cm_IoctlDelAllToken ucellp %lx", ucellp);
2129         ucellp->flags &= ~CM_UCELLFLAG_RXKAD;
2130         ucellp->gen++;
2131     }
2132
2133     lock_ReleaseMutex(&userp->mx);
2134
2135     cm_ResetACLCache(userp);
2136
2137     return 0;
2138 }
2139
2140 long cm_IoctlMakeSubmount(smb_ioctl_t *ioctlp, cm_user_t *userp)
2141 {
2142     char afspath[MAX_PATH];
2143     char *submountreqp;
2144     int nextAutoSubmount;
2145     HKEY hkSubmounts;
2146     DWORD dwType, dwSize;
2147     DWORD status;
2148     DWORD dwIndex;
2149     DWORD dwSubmounts;
2150
2151     cm_SkipIoctlPath(ioctlp);
2152
2153     /* Serialize this one, to prevent simultaneous mods
2154      * to afsdsbmt.ini
2155      */
2156     lock_ObtainMutex(&cm_Afsdsbmt_Lock);
2157
2158     /* Parse the input parameters--first the required afs path,
2159      * then the requested submount name (which may be "").
2160      */
2161     cm_NormalizeAfsPath (afspath, sizeof(afspath), ioctlp->inDatap);
2162     submountreqp = ioctlp->inDatap + (strlen(ioctlp->inDatap)+1);
2163
2164     /* If the caller supplied a suggested submount name, see if
2165      * that submount name is in use... if so, the submount's path
2166      * has to match our path.
2167      */
2168
2169     RegCreateKeyEx( HKEY_LOCAL_MACHINE, 
2170                     AFSREG_CLT_OPENAFS_SUBKEY "\\Submounts",
2171                     0, 
2172                     "AFS", 
2173                     REG_OPTION_NON_VOLATILE,
2174                     KEY_READ|KEY_WRITE|KEY_QUERY_VALUE,
2175                     NULL, 
2176                     &hkSubmounts,
2177                     NULL );
2178
2179     if (submountreqp && *submountreqp) {
2180         char submountPathNormalized[MAX_PATH];
2181         char submountPath[MAX_PATH];
2182
2183         dwSize = sizeof(submountPath);
2184         status = RegQueryValueEx( hkSubmounts, submountreqp, 0,
2185                                   &dwType, submountPath, &dwSize);
2186
2187         if (status != ERROR_SUCCESS) {
2188
2189             /* The suggested submount name isn't in use now--
2190              * so we can safely map the requested submount name
2191              * to the supplied path. Remember not to write the
2192              * leading "/afs" when writing out the submount.
2193              */
2194             RegSetValueEx( hkSubmounts, submountreqp, 0,
2195                            REG_EXPAND_SZ, 
2196                            (strlen(&afspath[strlen(cm_mountRoot)])) ?
2197                            &afspath[strlen(cm_mountRoot)]:"/",
2198                            (strlen(&afspath[strlen(cm_mountRoot)])) ?
2199                            strlen(&afspath[strlen(cm_mountRoot)])+1:2);
2200
2201             RegCloseKey( hkSubmounts );
2202             StringCbCopyA(ioctlp->outDatap, 999999, submountreqp);
2203             ioctlp->outDatap += strlen(ioctlp->outDatap) +1;
2204             lock_ReleaseMutex(&cm_Afsdsbmt_Lock);
2205             return 0;
2206         }
2207
2208         /* The suggested submount name is already in use--if the
2209          * supplied path matches the submount's path, we can still
2210          * use the suggested submount name.
2211          */
2212         cm_NormalizeAfsPath (submountPathNormalized, sizeof(submountPathNormalized), submountPath);
2213         if (!strcmp (submountPathNormalized, afspath)) {
2214             StringCbCopyA(ioctlp->outDatap, 999999, submountreqp);
2215             ioctlp->outDatap += strlen(ioctlp->outDatap) +1;
2216             RegCloseKey( hkSubmounts );
2217             lock_ReleaseMutex(&cm_Afsdsbmt_Lock);
2218             return 0;
2219         }
2220     }
2221
2222     RegQueryInfoKey( hkSubmounts,
2223                      NULL,  /* lpClass */
2224                      NULL,  /* lpcClass */
2225                      NULL,  /* lpReserved */
2226                      NULL,  /* lpcSubKeys */
2227                      NULL,  /* lpcMaxSubKeyLen */
2228                      NULL,  /* lpcMaxClassLen */
2229                      &dwSubmounts, /* lpcValues */
2230                      NULL,  /* lpcMaxValueNameLen */
2231                      NULL,  /* lpcMaxValueLen */
2232                      NULL,  /* lpcbSecurityDescriptor */
2233                      NULL   /* lpftLastWriteTime */
2234                      );
2235
2236
2237     /* Having obtained a list of all available submounts, start
2238      * searching that list for a path which matches the requested
2239      * AFS path. We'll also keep track of the highest "auto15"/"auto47"
2240      * submount, in case we need to add a new one later.
2241      */
2242
2243     nextAutoSubmount = 1;
2244
2245     for ( dwIndex = 0; dwIndex < dwSubmounts; dwIndex ++ ) {
2246         char submountPathNormalized[MAX_PATH];
2247         char submountPath[MAX_PATH] = "";
2248         DWORD submountPathLen = sizeof(submountPath);
2249         char submountName[MAX_PATH];
2250         DWORD submountNameLen = sizeof(submountName);
2251
2252         dwType = 0;
2253         RegEnumValue( hkSubmounts, dwIndex, submountName, &submountNameLen, NULL,
2254                       &dwType, submountPath, &submountPathLen);
2255         if (dwType == REG_EXPAND_SZ) {
2256             char buf[MAX_PATH];
2257             StringCbCopyA(buf, MAX_PATH, submountPath);
2258             submountPathLen = ExpandEnvironmentStrings(buf, submountPath, MAX_PATH);
2259             if (submountPathLen > MAX_PATH)
2260                 continue;
2261         }
2262
2263         /* If this is an Auto### submount, remember its ### value */
2264         if ((!strnicmp (submountName, "auto", 4)) &&
2265              (isdigit (submountName[strlen("auto")]))) {
2266             int thisAutoSubmount;
2267             thisAutoSubmount = atoi (&submountName[strlen("auto")]);
2268             nextAutoSubmount = max (nextAutoSubmount,
2269                                      thisAutoSubmount+1);
2270         }       
2271
2272         if ((submountPathLen == 0) ||
2273              (submountPathLen == sizeof(submountPath) - 1)) {
2274             continue;
2275         }
2276
2277         /* See if the path for this submount matches the path
2278          * that our caller specified. If so, we can return
2279          * this submount.
2280          */
2281         cm_NormalizeAfsPath (submountPathNormalized, sizeof(submountPathNormalized), submountPath);
2282         if (!strcmp (submountPathNormalized, afspath)) {
2283             StringCbCopyA(ioctlp->outDatap, 999999, submountName);
2284             ioctlp->outDatap += strlen(ioctlp->outDatap) +1;
2285             RegCloseKey(hkSubmounts);
2286             lock_ReleaseMutex(&cm_Afsdsbmt_Lock);
2287             return 0;
2288
2289         }
2290     }
2291
2292     /* We've been through the entire list of existing submounts, and
2293      * didn't find any which matched the specified path. So, we'll
2294      * just have to add one. Remember not to write the leading "/afs"
2295      * when writing out the submount.
2296      */
2297
2298     StringCbPrintfA(ioctlp->outDatap, 999999, "auto%ld", nextAutoSubmount);
2299
2300     RegSetValueEx( hkSubmounts, 
2301                    ioctlp->outDatap,
2302                    0,
2303                    REG_EXPAND_SZ, 
2304                    (strlen(&afspath[strlen(cm_mountRoot)])) ?
2305                    &afspath[strlen(cm_mountRoot)]:"/",
2306                    (strlen(&afspath[strlen(cm_mountRoot)])) ?
2307                    strlen(&afspath[strlen(cm_mountRoot)])+1:2);
2308
2309     ioctlp->outDatap += strlen(ioctlp->outDatap) +1;
2310     RegCloseKey(hkSubmounts);
2311     lock_ReleaseMutex(&cm_Afsdsbmt_Lock);
2312     return 0;
2313 }
2314
2315 long cm_IoctlGetRxkcrypt(smb_ioctl_t *ioctlp, cm_user_t *userp)
2316 {
2317     memcpy(ioctlp->outDatap, &cryptall, sizeof(cryptall));
2318     ioctlp->outDatap += sizeof(cryptall);
2319
2320     return 0;
2321 }
2322
2323 long cm_IoctlSetRxkcrypt(smb_ioctl_t *ioctlp, cm_user_t *userp)
2324 {
2325     cm_SkipIoctlPath(ioctlp);
2326
2327     memcpy(&cryptall, ioctlp->inDatap, sizeof(cryptall));
2328
2329     return 0;
2330 }
2331
2332 #ifdef DJGPP
2333 extern int afsd_shutdown(int);
2334 extern int afs_shutdown;
2335
2336 long cm_IoctlShutdown(smb_ioctl_t *ioctlp, cm_user_t *userp) {
2337   afs_shutdown = 1;   /* flag to shut down */
2338   return 0;
2339 }
2340 #endif /* DJGPP */
2341
2342 long cm_IoctlGetSMBName(smb_ioctl_t *ioctlp, cm_user_t *userp)
2343 {
2344   smb_user_t *uidp = ioctlp->uidp;
2345
2346   if (uidp && uidp->unp) {
2347     memcpy(ioctlp->outDatap, uidp->unp->name, strlen(uidp->unp->name));
2348     ioctlp->outDatap += strlen(uidp->unp->name);
2349   }
2350
2351   return 0;
2352 }
2353
2354 /* 
2355  * functions to dump contents of various structures. 
2356  * In debug build (linked with crt debug library) will dump allocated but not freed memory
2357  */
2358 extern int cm_DumpSCache(FILE *outputFile, char *cookie, int lock);
2359 extern int cm_DumpBufHashTable(FILE *outputFile, char *cookie, int lock);
2360 extern int smb_DumpVCP(FILE *outputFile, char *cookie, int lock);
2361
2362 long cm_IoctlMemoryDump(struct smb_ioctl *ioctlp, struct cm_user *userp)
2363 {
2364     long inValue = 0;
2365     HANDLE hLogFile;
2366     char logfileName[MAX_PATH+1];
2367     char *cookie;
2368     DWORD dwSize;
2369   
2370 #ifdef _DEBUG  
2371     static _CrtMemState memstate;
2372 #endif
2373   
2374     cm_SkipIoctlPath(ioctlp);
2375     memcpy(&inValue, ioctlp->inDatap, sizeof(long));
2376   
2377     dwSize = GetEnvironmentVariable("TEMP", logfileName, sizeof(logfileName));
2378     if ( dwSize == 0 || dwSize > sizeof(logfileName) )
2379     {
2380         GetWindowsDirectory(logfileName, sizeof(logfileName));
2381     }
2382     strncat(logfileName, "\\afsd_alloc.log", sizeof(logfileName));
2383
2384     hLogFile = CreateFile(logfileName, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2385   
2386     if (!hLogFile)
2387     {
2388       /* error */
2389       inValue = -1;
2390       memcpy(ioctlp->outDatap, &inValue, sizeof(long));
2391       ioctlp->outDatap += sizeof(long);
2392       
2393       return 0;               
2394     }
2395   
2396     SetFilePointer(hLogFile, 0, NULL, FILE_END);
2397   
2398     cookie = inValue ? "b" : "e";
2399   
2400 #ifdef _DEBUG  
2401   
2402     if (inValue)
2403     {
2404       _CrtMemCheckpoint(&memstate);           
2405     }
2406     else
2407     {
2408         _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
2409         _CrtSetReportFile(_CRT_WARN, hLogFile);
2410         _CrtMemDumpAllObjectsSince(&memstate);
2411     }
2412 #endif
2413   
2414     /* dump all interesting data */
2415     cm_DumpSCache(hLogFile, cookie, 1);
2416     cm_DumpBufHashTable(hLogFile, cookie, 1);
2417     smb_DumpVCP(hLogFile, cookie, 1);
2418
2419     CloseHandle(hLogFile);                          
2420   
2421     memcpy(ioctlp->outDatap, &inValue, sizeof(long));
2422     ioctlp->outDatap += sizeof(long);
2423   
2424     return 0;
2425 }