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