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