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