bozo: Introduce bnode_Wait()
[openafs.git] / src / WINNT / afsd / cm_freelance.c
1 #include <afsconfig.h>
2 #include <afs/param.h>
3 #include <roken.h>
4
5 #include <afs/stds.h>
6
7 #include <windows.h>
8 #include <winreg.h>
9 #include <winsock2.h>
10 #include <stdlib.h>
11 #include <malloc.h>
12 #include <string.h>
13 #include <cm_nls.h>
14
15 #include <WINNT/afsreg.h>
16 #include "afsd.h"
17 #include <rx/rx.h>
18
19 #ifdef AFS_FREELANCE_CLIENT
20 #include "cm_freelance.h"
21 #include <stdio.h>
22 #define STRSAFE_NO_DEPRECATE
23 #include <strsafe.h>
24
25 extern void afsi_log(char *pattern, ...);
26
27 static unsigned int cm_noLocalMountPoints = 0;
28 char * cm_FakeRootDir = NULL;
29 int cm_fakeDirSize = 0;
30 static cm_localMountPoint_t* cm_localMountPoints;
31 osi_mutex_t cm_Freelance_Lock;
32 static int cm_localMountPointChangeFlag = 0;
33 int cm_freelanceEnabled = 1;
34 int cm_freelanceDiscovery = 1;
35 int cm_freelanceImportCellServDB = 0;
36 time_t FakeFreelanceModTime = 0x3b49f6e2;
37
38 static int freelance_ShutdownFlag = 0;
39 static HANDLE hFreelanceChangeEvent = 0;
40 static HANDLE hFreelanceSymlinkChangeEvent = 0;
41
42 void cm_InitFakeRootDir();
43
44 void cm_FreelanceChangeNotifier(void * parmp) {
45     HKEY   hkFreelance = 0;
46
47     if (RegOpenKeyEx( HKEY_LOCAL_MACHINE,
48                       AFSREG_CLT_OPENAFS_SUBKEY "\\Freelance",
49                       0,
50                       KEY_NOTIFY,
51                       &hkFreelance) == ERROR_SUCCESS) {
52
53         hFreelanceChangeEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
54         if (hFreelanceChangeEvent == NULL) {
55             RegCloseKey(hkFreelance);
56             return;
57         }
58     }
59
60     while ( TRUE ) {
61     /* check hFreelanceChangeEvent to see if it is set.
62      * if so, call cm_noteLocalMountPointChange()
63      */
64         if (RegNotifyChangeKeyValue( hkFreelance,   /* hKey */
65                                      FALSE,         /* bWatchSubtree */
66                                      REG_NOTIFY_CHANGE_LAST_SET, /* dwNotifyFilter */
67                                      hFreelanceChangeEvent, /* hEvent */
68                                      TRUE          /* fAsynchronous */
69                                      ) != ERROR_SUCCESS) {
70             RegCloseKey(hkFreelance);
71             CloseHandle(hFreelanceChangeEvent);
72             hFreelanceChangeEvent = 0;
73             return;
74         }
75
76         if (WaitForSingleObject(hFreelanceChangeEvent, INFINITE) == WAIT_OBJECT_0)
77         {
78             if (freelance_ShutdownFlag == 1) {
79                 RegCloseKey(hkFreelance);
80                 CloseHandle(hFreelanceChangeEvent);
81                 hFreelanceChangeEvent = 0;
82                 return;
83             }
84             cm_noteLocalMountPointChange(FALSE);
85         }
86     }
87 }
88
89 void cm_FreelanceSymlinkChangeNotifier(void * parmp) {
90     HKEY   hkFreelance = 0;
91
92     if (RegOpenKeyEx( HKEY_LOCAL_MACHINE,
93                       AFSREG_CLT_OPENAFS_SUBKEY "\\Freelance\\Symlinks",
94                       0,
95                       KEY_NOTIFY,
96                       &hkFreelance) == ERROR_SUCCESS) {
97
98         hFreelanceSymlinkChangeEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
99         if (hFreelanceSymlinkChangeEvent == NULL) {
100             RegCloseKey(hkFreelance);
101             return;
102         }
103     }
104
105     while ( TRUE ) {
106     /* check hFreelanceSymlinkChangeEvent to see if it is set.
107      * if so, call cm_noteLocalMountPointSymlinkChange()
108      */
109         if (RegNotifyChangeKeyValue( hkFreelance,   /* hKey */
110                                      FALSE,         /* bWatchSubtree */
111                                      REG_NOTIFY_CHANGE_LAST_SET, /* dwNotifyFilter */
112                                      hFreelanceSymlinkChangeEvent, /* hEvent */
113                                      TRUE          /* fAsynchronous */
114                                      ) != ERROR_SUCCESS) {
115             RegCloseKey(hkFreelance);
116             CloseHandle(hFreelanceSymlinkChangeEvent);
117             hFreelanceSymlinkChangeEvent = 0;
118             return;
119         }
120
121         if (WaitForSingleObject(hFreelanceSymlinkChangeEvent, INFINITE) == WAIT_OBJECT_0)
122         {
123             if (freelance_ShutdownFlag == 1) {
124                 RegCloseKey(hkFreelance);
125                 CloseHandle(hFreelanceSymlinkChangeEvent);
126                 hFreelanceSymlinkChangeEvent = 0;
127                 return;
128             }
129             cm_noteLocalMountPointChange(FALSE);
130         }
131     }
132 }
133
134 void
135 cm_FreelanceShutdown(void)
136 {
137     freelance_ShutdownFlag = 1;
138     if (hFreelanceChangeEvent != 0)
139         thrd_SetEvent(hFreelanceChangeEvent);
140     if (hFreelanceSymlinkChangeEvent != 0)
141         thrd_SetEvent(hFreelanceSymlinkChangeEvent);
142 }
143
144 static long
145 cm_FreelanceAddCSDBMountPoints(void *rockp, char *cellNamep)
146 {
147     char szCellName[CELL_MAXNAMELEN+1] = ".";
148
149     cm_FsStrCpy( &szCellName[1], CELL_MAXNAMELEN, cellNamep);
150     /* create readonly mount point */
151     cm_FreelanceAddMount( cellNamep, cellNamep, "root.cell", 0, NULL);
152
153     /* create read/write mount point */
154     cm_FreelanceAddMount( szCellName, szCellName, "root.cell", 1, NULL);
155
156     return 0;
157 }
158
159 void
160 cm_FreelanceImportCellServDB(void)
161 {
162     cm_EnumerateCellRegistry( TRUE, cm_FreelanceAddCSDBMountPoints, NULL);
163     cm_EnumerateCellFile( TRUE, cm_FreelanceAddCSDBMountPoints, NULL);
164 }
165
166 void cm_InitFreelance() {
167     thread_t phandle;
168     int lpid;
169
170     lock_InitializeMutex(&cm_Freelance_Lock, "Freelance Lock", LOCK_HIERARCHY_FREELANCE_GLOBAL);
171
172     lock_ObtainMutex(&cm_Freelance_Lock);
173
174     // yj: first we make a call to cm_initLocalMountPoints
175     // to read all the local mount points from the registry
176     cm_InitLocalMountPoints();
177
178     // then we make a call to InitFakeRootDir to create
179     // a fake root directory based on the local mount points
180     cm_InitFakeRootDir();
181
182     // increment the fakeDirVersion to force status updates for
183     // all cached Freelance objects
184     cm_data.fakeDirVersion++;
185     // --- end of yj code
186     lock_ReleaseMutex(&cm_Freelance_Lock);
187
188     /* Start the registry monitor */
189     phandle = thrd_Create(NULL, 65536, (ThreadFunc) cm_FreelanceChangeNotifier,
190                           NULL, 0, &lpid, "cm_FreelanceChangeNotifier");
191     osi_assertx(phandle != NULL, "cm_FreelanceChangeNotifier thread create failure");
192     thrd_CloseHandle(phandle);
193
194     phandle = thrd_Create(NULL, 65536, (ThreadFunc) cm_FreelanceSymlinkChangeNotifier,
195                           NULL, 0, &lpid, "cm_FreelanceSymlinkChangeNotifier");
196     osi_assertx(phandle != NULL, "cm_FreelanceSymlinkChangeNotifier thread create failure");
197     thrd_CloseHandle(phandle);
198 }
199
200 /* yj: Initialization of the fake root directory */
201 /* to be called while holding freelance lock. */
202 void cm_InitFakeRootDir() {
203     int i, t1, t2;
204     char* currentPos;
205     int noChunks;
206
207     // allocate space for the fake info
208     cm_dirHeader_t fakeDirHeader;
209     cm_dirEntry_t fakeEntry;
210     cm_pageHeader_t fakePageHeader;
211
212     // i'm going to calculate how much space is needed for
213     // this fake root directory. we have these rules:
214     // 1. there are cm_noLocalMountPoints number of entries
215     // 2. each page is CM_DIR_PAGESIZE in size
216     // 3. the first 13 chunks of the first page are used for
217     //    some header stuff
218     // 4. the first chunk of all subsequent pages are used
219     //    for page header stuff
220     // 5. a max of CM_DIR_EPP entries are allowed per page
221     // 6. each entry takes 1 or more chunks, depending on
222     //    the size of the mount point string, as determined
223     //    by cm_NameEntries
224     // 7. each chunk is CM_DIR_CHUNKSIZE bytes
225
226     int CPP = CM_DIR_PAGESIZE / CM_DIR_CHUNKSIZE;
227     int curChunk = 13;  // chunks 0 - 12 are used for header stuff
228                         // of the first page in the directory
229     int curPage = 0;
230     unsigned int curDirEntry = 0;
231     int curDirEntryInPage = 0;
232     int sizeOfCurEntry;
233     int dirSize;
234
235     /* Increment the fake Uniquifier */
236     cm_data.fakeUnique++;
237
238     /* Reserve 2 directory chunks for "." and ".." */
239     curChunk += 2;
240
241     while (curDirEntry<cm_noLocalMountPoints) {
242         sizeOfCurEntry = cm_NameEntries((cm_localMountPoints+curDirEntry)->namep, 0);
243         if ((curChunk + sizeOfCurEntry >= CPP) ||
244              (curDirEntryInPage + 1 >= CM_DIR_EPP)) {
245             curPage++;
246             curDirEntryInPage = 0;
247             curChunk = 1;
248         }
249         curChunk += sizeOfCurEntry;
250         curDirEntry++;
251         curDirEntryInPage++;
252     }
253
254     dirSize = (curPage+1) *  CM_DIR_PAGESIZE;
255     if (cm_fakeDirSize != dirSize) {
256         if (cm_FakeRootDir)
257             free(cm_FakeRootDir);
258         cm_FakeRootDir = calloc(dirSize, 1);
259         cm_fakeDirSize = dirSize;
260     }
261
262     // yj: when we get here, we've figured out how much memory we need and
263     // allocated the appropriate space for it. we now prceed to fill
264     // it up with entries.
265     curPage = 0;
266     curDirEntry = 0;
267     curDirEntryInPage = 0;
268     curChunk = 0;
269
270     // fields in the directory entry that are unused.
271     fakeEntry.flag = 1;
272     fakeEntry.length = 0;
273     fakeEntry.next = 0;
274     fakeEntry.fid.unique = htonl(1 + cm_data.fakeUnique);
275
276     // the first page is special, it uses fakeDirHeader instead of fakePageHeader
277     // we fill up the page with dirEntries that belong there and we make changes
278     // to the fakeDirHeader.header.freeBitmap along the way. Then when we're done
279     // filling up the dirEntries in this page, we copy the fakeDirHeader into
280     // the top of the page.
281
282     // init the freeBitmap array
283     for (i=0; i<8; i++)
284         fakeDirHeader.header.freeBitmap[i]=0;
285
286     fakeDirHeader.header.freeBitmap[0] = 0xff;
287     fakeDirHeader.header.freeBitmap[1] = 0x7f;
288
289
290     // we start counting at 13 because the 0th to 12th chunks are used for header
291     curChunk = 13;
292
293     // stick the first 2 entries "." and ".." in
294     fakeEntry.fid.vnode = htonl(1);
295     strcpy(fakeEntry.name, ".");
296     currentPos = cm_FakeRootDir + curPage * CM_DIR_PAGESIZE + curChunk * CM_DIR_CHUNKSIZE;
297     memcpy(currentPos, &fakeEntry, CM_DIR_CHUNKSIZE);
298     curChunk++; curDirEntryInPage++;
299     strcpy(fakeEntry.name, "..");
300     currentPos = cm_FakeRootDir + curPage * CM_DIR_PAGESIZE + curChunk * CM_DIR_CHUNKSIZE;
301     memcpy(currentPos, &fakeEntry, CM_DIR_CHUNKSIZE);
302     curChunk++; curDirEntryInPage++;
303
304     // keep putting stuff into page 0 if
305     // 1. we're not done with all entries
306     // 2. we have less than CM_DIR_EPP entries in page 0
307     // 3. we're not out of chunks in page 0
308
309     while( (curDirEntry<cm_noLocalMountPoints) &&
310            (curDirEntryInPage < CM_DIR_EPP) &&
311            (curChunk + cm_NameEntries((cm_localMountPoints+curDirEntry)->namep, 0) <= CPP))
312     {
313
314         noChunks = cm_NameEntries((cm_localMountPoints+curDirEntry)->namep, 0);
315         /* enforce the rule that only directories have odd vnode values */
316         fakeEntry.fid.vnode = htonl((curDirEntry + 1) * 2);
317         fakeEntry.fid.unique = htonl(curDirEntry + 1 + cm_data.fakeUnique);
318         currentPos = cm_FakeRootDir + curPage * CM_DIR_PAGESIZE + curChunk * CM_DIR_CHUNKSIZE;
319
320         memcpy(currentPos, &fakeEntry, CM_DIR_CHUNKSIZE);
321         strcpy(currentPos + 12, (cm_localMountPoints+curDirEntry)->namep);
322         curDirEntry++;
323         curDirEntryInPage++;
324         for (i=0; i<noChunks; i++) {
325             t1 = (curChunk + i) / 8;
326             t2 = curChunk + i - (t1*8);
327             fakeDirHeader.header.freeBitmap[t1] |= (1 << t2);
328         }
329         curChunk+=noChunks;
330     }
331
332     // when we get here, we're done with filling in the entries for page 0
333     // copy in the header info
334
335     memcpy(cm_FakeRootDir, &fakeDirHeader, 13 * CM_DIR_CHUNKSIZE);
336
337     curPage++;
338
339     // ok, page 0's done. Move on to the next page.
340     while (curDirEntry<cm_noLocalMountPoints) {
341         // setup a new page
342         curChunk = 1;                   // the zeroth chunk is reserved for page header
343         curDirEntryInPage = 0;
344         for (i=0; i<8; i++) {
345             fakePageHeader.freeBitmap[i]=0;
346         }
347         fakePageHeader.freeCount = 0;
348         fakePageHeader.pgcount = 0;
349         fakePageHeader.tag = htons(1234);
350
351         // while we're on the same page...
352         while ( (curDirEntry<cm_noLocalMountPoints) &&
353                 (curDirEntryInPage < CM_DIR_EPP) &&
354                 (curChunk + cm_NameEntries((cm_localMountPoints+curDirEntry)->namep, 0) <= CPP))
355         {
356             // add an entry to this page
357
358             noChunks = cm_NameEntries((cm_localMountPoints+curDirEntry)->namep, 0);
359             /* enforce the rule that only directories have odd vnode values */
360             fakeEntry.fid.vnode = htonl((curDirEntry + 1) * 2);
361             fakeEntry.fid.unique = htonl(curDirEntry + 1 + cm_data.fakeUnique);
362             currentPos = cm_FakeRootDir + curPage * CM_DIR_PAGESIZE + curChunk * CM_DIR_CHUNKSIZE;
363             memcpy(currentPos, &fakeEntry, CM_DIR_CHUNKSIZE);
364             strcpy(currentPos + 12, (cm_localMountPoints+curDirEntry)->namep);
365             curDirEntry++;
366             curDirEntryInPage++;
367             for (i=0; i<noChunks; i++) {
368                 t1 = (curChunk + i) / 8;
369                 t2 = curChunk + i - (t1*8);
370                 fakePageHeader.freeBitmap[t1] |= (1 << t2);
371             }
372             curChunk+=noChunks;
373         }
374         memcpy(cm_FakeRootDir + curPage * CM_DIR_PAGESIZE, &fakePageHeader, sizeof(fakePageHeader));
375
376         curPage++;
377     }
378
379     // we know the fakeDir is setup properly, so we claim that we have callback
380     osi_Log0(afsd_logp,"cm_InitFakeRootDir completed!");
381
382     // when we get here, we've set up everything! done!
383 }
384
385 int cm_FakeRootFid(cm_fid_t *fidp)
386 {
387     cm_SetFid(fidp,
388               AFS_FAKE_ROOT_CELL_ID,            /* root cell */
389               AFS_FAKE_ROOT_VOL_ID,            /* root.afs ? */
390               1, 1);
391     return 0;
392 }
393
394 /* called directly from ioctl */
395 /* called while not holding freelance lock */
396 int cm_noteLocalMountPointChange(afs_int32 locked) {
397     if (!locked)
398         lock_ObtainMutex(&cm_Freelance_Lock);
399     cm_data.fakeDirVersion++;
400     cm_localMountPointChangeFlag = 1;
401
402     if (!locked)
403         lock_ReleaseMutex(&cm_Freelance_Lock);
404
405     if (RDR_Initialized) {
406         cm_fid_t fid;
407         cm_FakeRootFid(&fid);
408         RDR_InvalidateVolume(AFS_FAKE_ROOT_CELL_ID, AFS_FAKE_ROOT_VOL_ID,
409                              AFS_INVALIDATE_DATA_VERSION);
410     }
411     return 1;
412 }
413
414 int cm_getLocalMountPointChange() {
415     return cm_localMountPointChangeFlag;
416 }
417
418 int cm_clearLocalMountPointChange() {
419     cm_localMountPointChangeFlag = 0;
420     return 0;
421 }
422
423 int cm_reInitLocalMountPoints() {
424     cm_fid_t aFid;
425     unsigned int i, hash;
426     cm_scache_t *scp, **lscpp, *tscp;
427     cm_req_t req;
428
429     cm_InitReq(&req);
430
431     osi_Log0(afsd_logp,"----- freelance reinitialization starts ----- ");
432
433     // first we invalidate all the SCPs that were created
434     // for the local mount points
435
436     osi_Log0(afsd_logp,"Invalidating local mount point scp...  ");
437
438     lock_ObtainWrite(&cm_scacheLock);
439     lock_ObtainMutex(&cm_Freelance_Lock);  /* always scache then freelance lock */
440     for (i=0; i<=cm_noLocalMountPoints; i++) {
441         if (i == 0)
442             cm_SetFid(&aFid, AFS_FAKE_ROOT_CELL_ID, AFS_FAKE_ROOT_VOL_ID, 1, 1);
443         else
444             cm_SetFid(&aFid, AFS_FAKE_ROOT_CELL_ID, AFS_FAKE_ROOT_VOL_ID, i*2, i);
445         hash = CM_SCACHE_HASH(&aFid);
446         for (scp=cm_data.scacheHashTablep[hash]; scp; scp=scp->nextp) {
447             if (scp != cm_data.rootSCachep && cm_FidCmp(&scp->fid, &aFid) == 0) {
448                 // mark the scp to be reused
449                 cm_HoldSCacheNoLock(scp);
450                 lock_ReleaseMutex(&cm_Freelance_Lock);
451                 lock_ReleaseWrite(&cm_scacheLock);
452                 lock_ObtainWrite(&scp->rw);
453                 cm_DiscardSCache(scp);
454
455                 // take the scp out of the hash
456                 lock_ObtainWrite(&cm_scacheLock);
457                 for (lscpp = &cm_data.scacheHashTablep[hash], tscp = cm_data.scacheHashTablep[hash];
458                      tscp;
459                      lscpp = &tscp->nextp, tscp = tscp->nextp) {
460                     if (tscp == scp) {
461                         *lscpp = scp->nextp;
462                         scp->nextp = NULL;
463                         scp->flags &= ~CM_SCACHEFLAG_INHASH;
464                         break;
465                     }
466                 }
467
468                 lock_ReleaseWrite(&scp->rw);
469                 lock_ReleaseWrite(&cm_scacheLock);
470                 cm_CallbackNotifyChange(scp);
471                 lock_ObtainWrite(&cm_scacheLock);
472                 cm_ReleaseSCacheNoLock(scp);
473                 lock_ObtainMutex(&cm_Freelance_Lock);
474             }
475         }
476     }
477     lock_ReleaseWrite(&cm_scacheLock);
478     lock_ReleaseMutex(&cm_Freelance_Lock);
479     osi_Log0(afsd_logp,"\tall old scp cleared!");
480
481     lock_ObtainWrite(&cm_data.rootSCachep->rw);
482     lock_ObtainMutex(&cm_Freelance_Lock);
483     // we must free the memory that was allocated in the prev
484     // cm_InitLocalMountPoints call
485     osi_Log0(afsd_logp,"Removing old localmountpoints...  ");
486     free(cm_localMountPoints);
487     cm_localMountPoints = NULL;
488     cm_noLocalMountPoints = 0;
489     osi_Log0(afsd_logp,"\tall old localmountpoints cleared!");
490
491     // now re-init the localmountpoints
492     osi_Log0(afsd_logp,"Creating new localmountpoints...  ");
493     cm_InitLocalMountPoints();
494     osi_Log0(afsd_logp,"\tcreated new set of localmountpoints!");
495
496     // then we re-create that dir
497     osi_Log0(afsd_logp,"Creating new fakedir...  ");
498     cm_InitFakeRootDir();
499     osi_Log0(afsd_logp,"\t\tcreated new fakedir!");
500
501     lock_ReleaseMutex(&cm_Freelance_Lock);
502
503     cm_GetCallback(cm_data.rootSCachep, cm_rootUserp, &req, 0);
504     lock_ReleaseWrite(&cm_data.rootSCachep->rw);
505
506     if (RDR_Initialized)
507         RDR_InvalidateVolume(AFS_FAKE_ROOT_CELL_ID, AFS_FAKE_ROOT_VOL_ID,
508                              AFS_INVALIDATE_DATA_VERSION);
509
510     osi_Log0(afsd_logp,"----- freelance reinit complete -----");
511     return 0;
512 }
513
514 /*
515  * cm_enforceTrailingDot
516  *
517  * return 0 on failure, non-zero on success
518  *
519  */
520 static int
521 cm_enforceTrailingDot(char * line, size_t cchLine, DWORD *pdwSize)
522 {
523     if (*pdwSize < 4) {
524         afsi_log("invalid string");
525         return 0;
526     }
527
528     /* trailing white space first. */
529     if (line[(*pdwSize)-1] == '\0') {
530         while (isspace(line[(*pdwSize)-2])) {
531             line[(*pdwSize)-2] = '\0';
532             (*pdwSize)--;
533         }
534     } else {
535         while (isspace(line[(*pdwSize)-1])) {
536             line[(*pdwSize)-1] = '\0';
537             (*pdwSize)--;
538         }
539     }
540
541     /* then enforce the trailing dot requirement */
542     if (line[(*pdwSize)-1] == '\0' && line[(*pdwSize)-2] != '.') {
543         if ((*pdwSize) >= cchLine) {
544             afsi_log("no room for trailing dot");
545             return 0;
546         }
547         line[(*pdwSize)-1] = '.';
548         line[(*pdwSize)] = '\0';
549     } else if (line[(*pdwSize)-1] != '\0' && line[(*pdwSize)-1] != '.') {
550         if ((*pdwSize) >= cchLine) {
551             afsi_log("no room for trailing dot and nul");
552             return 0;
553         }
554         line[(*pdwSize)] = '.';
555         line[(*pdwSize)+1] = '\0';
556     } else if (line[(*pdwSize)-1] != '\0') {
557         if ((*pdwSize) >= cchLine) {
558             afsi_log("no room for trailing nul");
559             return 0;
560         }
561         line[(*pdwSize)] = '\0';
562     }
563     return 1;
564 }
565
566
567 // yj: open up the registry and read all the local mount
568 // points that are stored there. Part of the initialization
569 // process for the freelance client.
570 /* to be called while holding freelance lock. */
571 long cm_InitLocalMountPoints() {
572     FILE *fp;
573     unsigned int i;
574     char line[512];
575     char*t, *t2;
576     cm_localMountPoint_t* aLocalMountPoint;
577     char hdir[260];
578     long code;
579     char rootCellName[256];
580     HKEY hkFreelance = 0, hkFreelanceSymlinks = 0;
581     DWORD dwType, dwSize;
582     DWORD dwMountPoints = 0;
583     DWORD dwIndex;
584     DWORD dwSymlinks = 0;
585     FILETIME ftLastWriteTime;
586
587     if (RegOpenKeyEx( HKEY_LOCAL_MACHINE,
588                       AFSREG_CLT_OPENAFS_SUBKEY "\\Freelance",
589                       0,
590                       KEY_READ|KEY_WRITE|KEY_QUERY_VALUE,
591                       &hkFreelance) == ERROR_SUCCESS) {
592
593         RegQueryInfoKey( hkFreelance,
594                          NULL,  /* lpClass */
595                          NULL,  /* lpcClass */
596                          NULL,  /* lpReserved */
597                          NULL,  /* lpcSubKeys */
598                          NULL,  /* lpcMaxSubKeyLen */
599                          NULL,  /* lpcMaxClassLen */
600                          &dwMountPoints, /* lpcValues */
601                          NULL,  /* lpcMaxValueNameLen */
602                          NULL,  /* lpcMaxValueLen */
603                          NULL,  /* lpcbSecurityDescriptor */
604                          &ftLastWriteTime /* lpftLastWriteTime */
605                          );
606
607         cm_UnixTimeFromLargeSearchTime(&FakeFreelanceModTime, &ftLastWriteTime);
608
609         if ( dwMountPoints == 0 ) {
610             rootCellName[0] = '.';
611             code = cm_GetRootCellName(&rootCellName[1]);
612             if (code == 0) {
613                 lock_ReleaseMutex(&cm_Freelance_Lock);
614                 cm_FreelanceAddMount(&rootCellName[1], &rootCellName[1], "root.cell", 0, NULL);
615                 cm_FreelanceAddMount(rootCellName, &rootCellName[1], "root.cell", 1, NULL);
616                 cm_FreelanceAddMount(".root", &rootCellName[1], "root.afs", 1, NULL);
617                 lock_ObtainMutex(&cm_Freelance_Lock);
618                 dwMountPoints = 3;
619             }
620         }
621
622         if (RegCreateKeyEx( HKEY_LOCAL_MACHINE,
623                           AFSREG_CLT_OPENAFS_SUBKEY "\\Freelance\\Symlinks",
624                           0,
625                           NULL,
626                           REG_OPTION_NON_VOLATILE,
627                           KEY_READ|KEY_WRITE|KEY_QUERY_VALUE,
628                           NULL,
629                           &hkFreelanceSymlinks,
630                           NULL) == ERROR_SUCCESS) {
631
632             RegQueryInfoKey( hkFreelanceSymlinks,
633                              NULL,  /* lpClass */
634                              NULL,  /* lpcClass */
635                              NULL,  /* lpReserved */
636                              NULL,  /* lpcSubKeys */
637                              NULL,  /* lpcMaxSubKeyLen */
638                              NULL,  /* lpcMaxClassLen */
639                              &dwSymlinks, /* lpcValues */
640                              NULL,  /* lpcMaxValueNameLen */
641                              NULL,  /* lpcMaxValueLen */
642                              NULL,  /* lpcbSecurityDescriptor */
643                              NULL   /* lpftLastWriteTime */
644                              );
645         }
646
647         // get the number of entries there are from the first line
648         // that we read
649         cm_noLocalMountPoints = dwMountPoints + dwSymlinks;
650
651         // create space to store the local mount points
652         cm_localMountPoints = malloc(sizeof(cm_localMountPoint_t) * cm_noLocalMountPoints);
653         aLocalMountPoint = cm_localMountPoints;
654
655         // now we read n lines and parse them into local mount points
656         // where n is the number of local mount points there are, as
657         // determined above.
658         // Each line in the ini file represents 1 local mount point and
659         // is in the format xxx#yyy:zzz, where xxx is the directory
660         // entry name, yyy is the cell name and zzz is the volume name.
661         // #yyy:zzz together make up the mount point.
662         for ( dwIndex = 0 ; dwIndex < dwMountPoints; dwIndex++ ) {
663             TCHAR szValueName[16];
664             DWORD dwValueSize = 16;
665             dwSize = sizeof(line);
666             if (RegEnumValue( hkFreelance, dwIndex, szValueName, &dwValueSize, NULL,
667                           &dwType, line, &dwSize))
668             {
669                 afsi_log("RegEnumValue(hkFreelance) failed");
670                 cm_noLocalMountPoints--;
671                 continue;
672             }
673
674             /* make sure there is a trailing dot and a nul terminator */
675             if (!cm_enforceTrailingDot(line, sizeof(line), &dwSize)) {
676                 cm_noLocalMountPoints--;
677                 continue;
678             }
679
680             afsi_log("Mountpoint[%d] = %s", dwIndex, line);
681
682             for ( t=line;*t;t++ ) {
683                 if ( !isprint(*t) ) {
684                     afsi_log("error occurred while parsing mountpoint entry [%d]: non-printable character", dwIndex);
685                     fprintf(stderr, "error occurred while parsing mountpoint entry [%d]: non-printable character", dwIndex);
686                     cm_noLocalMountPoints--;
687                     continue;
688                 }
689             }
690
691             // line is not empty, so let's parse it
692             t = strchr(line, '#');
693             if (!t)
694                 t = strchr(line, '%');
695             // make sure that there is a '#' or '%' separator in the line
696             if (!t) {
697                 afsi_log("error occurred while parsing mountpoint entry [%d]: no # or %% separator", dwIndex);
698                 fprintf(stderr, "error occurred while parsing mountpoint entry [%d]: no # or %% separator", dwIndex);
699                 cm_noLocalMountPoints--;
700                 continue;
701             }
702
703             aLocalMountPoint->fileType = CM_SCACHETYPE_MOUNTPOINT;
704             aLocalMountPoint->namep=malloc(t-line+1);
705             strncpy(aLocalMountPoint->namep, line, t-line);
706             aLocalMountPoint->namep[t-line] = '\0';
707
708             /* copy the mount point string */
709             aLocalMountPoint->mountPointStringp=malloc(strlen(t));
710             strncpy(aLocalMountPoint->mountPointStringp, t, strlen(t)-1);
711             aLocalMountPoint->mountPointStringp[strlen(t)-1] = '\0';
712
713             osi_Log2(afsd_logp,"found mount point: name %s, string %s",
714                       osi_LogSaveString(afsd_logp,aLocalMountPoint->namep),
715                       osi_LogSaveString(afsd_logp,aLocalMountPoint->mountPointStringp));
716
717             aLocalMountPoint++;
718         }
719
720         for ( dwIndex = 0 ; dwIndex < dwSymlinks; dwIndex++ ) {
721             TCHAR szValueName[16];
722             DWORD dwValueSize = 16;
723             dwSize = sizeof(line);
724             if (RegEnumValue( hkFreelanceSymlinks, dwIndex, szValueName, &dwValueSize, NULL,
725                               &dwType, line, &dwSize))
726             {
727                 afsi_log("RegEnumValue(hkFreelanceSymlinks) failed");
728                 cm_noLocalMountPoints--;
729                 continue;
730             }
731
732             /* make sure there is a trailing dot and a nul terminator */
733             if (!cm_enforceTrailingDot(line, sizeof(line), &dwSize)) {
734                 cm_noLocalMountPoints--;
735                 continue;
736             }
737
738             afsi_log("Symlink[%d] = %s", dwIndex, line);
739
740             for ( t=line;*t;t++ ) {
741                 if ( !isprint(*t) ) {
742                     afsi_log("error occurred while parsing symlink entry [%d]: non-printable character", dwIndex);
743                     fprintf(stderr, "error occurred while parsing symlink entry [%d]: non-printable character", dwIndex);
744                     cm_noLocalMountPoints--;
745                     continue;
746                 }
747             }
748
749             // line is not empty, so let's parse it
750             t = strchr(line, ':');
751
752             // make sure that there is a ':' separator in the line
753             if (!t) {
754                 afsi_log("error occurred while parsing symlink entry [%d]: no ':' separator", dwIndex);
755                 fprintf(stderr, "error occurred while parsing symlink entry [%d]: no ':' separator", dwIndex);
756                 cm_noLocalMountPoints--;
757                 continue;
758             }
759
760             aLocalMountPoint->fileType = CM_SCACHETYPE_SYMLINK;
761             aLocalMountPoint->namep=malloc(t-line+1);
762             strncpy(aLocalMountPoint->namep, line, t-line);
763             aLocalMountPoint->namep[t-line] = '\0';
764
765             /* copy the symlink string */
766             aLocalMountPoint->mountPointStringp=malloc(strlen(t)-1);
767             strncpy(aLocalMountPoint->mountPointStringp, t+1, strlen(t)-2);
768             aLocalMountPoint->mountPointStringp[strlen(t)-2] = '\0';
769
770             osi_Log2(afsd_logp,"found symlink: name %s, string %s",
771                       osi_LogSaveString(afsd_logp,aLocalMountPoint->namep),
772                       osi_LogSaveString(afsd_logp,aLocalMountPoint->mountPointStringp));
773
774             aLocalMountPoint++;
775         }
776
777         if ( hkFreelanceSymlinks )
778             RegCloseKey( hkFreelanceSymlinks );
779         RegCloseKey(hkFreelance);
780         return 0;
781     }
782
783     /* What follows is the old code to read freelance mount points
784      * out of a text file modified to copy the data into the registry
785      */
786     cm_GetConfigDir(hdir, sizeof(hdir));
787     strcat(hdir, AFS_FREELANCE_INI);
788     // open the ini file for reading
789     fp = fopen(hdir, "r");
790     if (!fp) {
791         /* look in the Windows directory where we used to store the file */
792         GetWindowsDirectory(hdir, sizeof(hdir));
793         strcat(hdir,"\\");
794         strcat(hdir, AFS_FREELANCE_INI);
795         fp = fopen(hdir, "r");
796     }
797
798     RegCreateKeyEx( HKEY_LOCAL_MACHINE,
799                     AFSREG_CLT_OPENAFS_SUBKEY "\\Freelance",
800                     0,
801                     NULL,
802                     REG_OPTION_NON_VOLATILE,
803                     KEY_READ|KEY_WRITE,
804                     NULL,
805                     &hkFreelance,
806                     NULL);
807     dwIndex = 0;
808
809     if (!fp) {
810         RegCloseKey(hkFreelance);
811         rootCellName[0] = '.';
812         code = cm_GetRootCellName(&rootCellName[1]);
813         if (code == 0) {
814             lock_ReleaseMutex(&cm_Freelance_Lock);
815             cm_FreelanceAddMount(&rootCellName[1], &rootCellName[1], "root.cell", 0, NULL);
816             cm_FreelanceAddMount(rootCellName, &rootCellName[1], "root.cell", 1, NULL);
817             cm_FreelanceAddMount(".root", &rootCellName[1], "root.afs", 1, NULL);
818             lock_ObtainMutex(&cm_Freelance_Lock);
819         }
820         return 0;
821     }
822
823     // we successfully opened the file
824     osi_Log0(afsd_logp,"opened afs_freelance.ini");
825
826     // now we read the first line to see how many entries
827     // there are
828     fgets(line, sizeof(line), fp);
829
830     // if the line is empty at any point when we're reading
831     // we're screwed. report error and return.
832     if (*line==0) {
833         afsi_log("error occurred while reading afs_freelance.ini");
834         fprintf(stderr, "error occurred while reading afs_freelance.ini");
835         return -1;
836     }
837
838     // get the number of entries there are from the first line
839     // that we read
840     cm_noLocalMountPoints = atoi(line);
841
842     if (cm_noLocalMountPoints > 0) {
843         // create space to store the local mount points
844         cm_localMountPoints = malloc(sizeof(cm_localMountPoint_t) * cm_noLocalMountPoints);
845         aLocalMountPoint = cm_localMountPoints;
846     }
847
848     // now we read n lines and parse them into local mount points
849     // where n is the number of local mount points there are, as
850     // determined above.
851     // Each line in the ini file represents 1 local mount point and
852     // is in the format xxx#yyy:zzz, where xxx is the directory
853     // entry name, yyy is the cell name and zzz is the volume name.
854     // #yyy:zzz together make up the mount point.
855     for (i=0; i<cm_noLocalMountPoints; i++) {
856         fgets(line, sizeof(line), fp);
857         // check that the line is not empty
858         if (line[0]==0) {
859             afsi_log("error occurred while parsing entry in %s: empty line in line %d", AFS_FREELANCE_INI, i);
860             fprintf(stderr, "error occurred while parsing entry in afs_freelance.ini: empty line in line %d", i);
861             return -1;
862         }
863
864         /* find the trailing dot; null terminate after it */
865         t2 = strrchr(line, '.');
866         if (t2)
867             *(t2+1) = '\0';
868
869         if ( hkFreelance ) {
870             char szIndex[16];
871             /* we are migrating to the registry */
872             sprintf(szIndex,"%d",dwIndex++);
873             dwType = REG_SZ;
874             dwSize = (DWORD)strlen(line) + 1;
875             RegSetValueEx( hkFreelance, szIndex, 0, dwType, line, dwSize);
876         }
877
878         // line is not empty, so let's parse it
879         t = strchr(line, '#');
880         if (!t)
881             t = strchr(line, '%');
882         // make sure that there is a '#' or '%' separator in the line
883         if (!t) {
884             afsi_log("error occurred while parsing entry in %s: no # or %% separator in line %d", AFS_FREELANCE_INI, i);
885             fprintf(stderr, "error occurred while parsing entry in afs_freelance.ini: no # or %% separator in line %d", i);
886             return -1;
887         }
888         aLocalMountPoint->namep=malloc(t-line+1);
889         memcpy(aLocalMountPoint->namep, line, t-line);
890         *(aLocalMountPoint->namep + (t-line)) = 0;
891
892         aLocalMountPoint->mountPointStringp=malloc(strlen(line) - (t-line) + 1);
893         memcpy(aLocalMountPoint->mountPointStringp, t, strlen(line)-(t-line)-1);
894         *(aLocalMountPoint->mountPointStringp + (strlen(line)-(t-line)-1)) = 0;
895
896         osi_Log2(afsd_logp,"found mount point: name %s, string %s",
897                   aLocalMountPoint->namep,
898                   aLocalMountPoint->mountPointStringp);
899
900         aLocalMountPoint++;
901     }
902     fclose(fp);
903     if ( hkFreelance ) {
904         RegCloseKey(hkFreelance);
905         DeleteFile(hdir);
906     }
907     return 0;
908 }
909
910 int cm_getNoLocalMountPoints() {
911     return cm_noLocalMountPoints;
912 }
913
914 long cm_FreelanceMountPointExists(char * filename, int prefix_ok)
915 {
916     char* cp;
917     char line[512];
918     char shortname[200];
919     int found = 0;
920     HKEY hkFreelance = 0;
921     DWORD dwType, dwSize;
922     DWORD dwMountPoints;
923     DWORD dwIndex;
924
925     lock_ObtainMutex(&cm_Freelance_Lock);
926
927     if (RegOpenKeyEx( HKEY_LOCAL_MACHINE,
928                       AFSREG_CLT_OPENAFS_SUBKEY "\\Freelance",
929                       0,
930                       KEY_READ|KEY_QUERY_VALUE,
931                       &hkFreelance) == ERROR_SUCCESS)
932     {
933         RegQueryInfoKey( hkFreelance,
934                          NULL,  /* lpClass */
935                          NULL,  /* lpcClass */
936                          NULL,  /* lpReserved */
937                          NULL,  /* lpcSubKeys */
938                          NULL,  /* lpcMaxSubKeyLen */
939                          NULL,  /* lpcMaxClassLen */
940                          &dwMountPoints, /* lpcValues */
941                          NULL,  /* lpcMaxValueNameLen */
942                          NULL,  /* lpcMaxValueLen */
943                          NULL,  /* lpcbSecurityDescriptor */
944                          NULL   /* lpftLastWriteTime */
945                          );
946
947         for ( dwIndex = 0; dwIndex < dwMountPoints; dwIndex++ ) {
948             TCHAR szValueName[16];
949             DWORD dwValueSize = 16;
950             dwSize = sizeof(line);
951             RegEnumValue( hkFreelance, dwIndex, szValueName, &dwValueSize, NULL,
952                           &dwType, line, &dwSize);
953
954             cp=strchr(line, '#');
955             if (!cp)
956                 cp=strchr(line, '%');
957             memcpy(shortname, line, cp-line);
958             shortname[cp-line]=0;
959
960             if (!strcmp(shortname, filename)) {
961                 found = 1;
962                 break;
963             }
964         }
965         for ( dwIndex = 0; dwIndex < dwMountPoints; dwIndex++ ) {
966             TCHAR szValueName[16];
967             DWORD dwValueSize = 16;
968             dwSize = sizeof(line);
969             RegEnumValue( hkFreelance, dwIndex, szValueName, &dwValueSize, NULL,
970                           &dwType, line, &dwSize);
971
972             cp=strchr(line, '#');
973             if (!cp)
974                 cp=strchr(line, '%');
975             memcpy(shortname, line, cp-line);
976             shortname[cp-line]=0;
977
978             if (!cm_stricmp_utf8(shortname, filename)) {
979                 found = 1;
980                 break;
981             }
982
983             if (prefix_ok && strlen(shortname) - strlen(filename) == 1 && !strncmp(shortname, filename, strlen(filename))) {
984                 found = 1;
985                 break;
986             }
987         }
988         RegCloseKey(hkFreelance);
989     }
990
991     lock_ReleaseMutex(&cm_Freelance_Lock);
992
993     return found;
994 }
995
996 long cm_FreelanceSymlinkExists(char * filename, int prefix_ok)
997 {
998     char* cp;
999     char line[512];
1000     char shortname[200];
1001     int found = 0;
1002     HKEY hkFreelance = 0;
1003     DWORD dwType, dwSize;
1004     DWORD dwSymlinks;
1005     DWORD dwIndex;
1006
1007     lock_ObtainMutex(&cm_Freelance_Lock);
1008
1009     if (RegOpenKeyEx( HKEY_LOCAL_MACHINE,
1010                       AFSREG_CLT_OPENAFS_SUBKEY "\\Freelance\\Symlinks",
1011                       0,
1012                       KEY_READ|KEY_QUERY_VALUE,
1013                       &hkFreelance) == ERROR_SUCCESS)
1014     {
1015         RegQueryInfoKey( hkFreelance,
1016                          NULL,  /* lpClass */
1017                          NULL,  /* lpcClass */
1018                          NULL,  /* lpReserved */
1019                          NULL,  /* lpcSubKeys */
1020                          NULL,  /* lpcMaxSubKeyLen */
1021                          NULL,  /* lpcMaxClassLen */
1022                          &dwSymlinks, /* lpcValues */
1023                          NULL,  /* lpcMaxValueNameLen */
1024                          NULL,  /* lpcMaxValueLen */
1025                          NULL,  /* lpcbSecurityDescriptor */
1026                          NULL   /* lpftLastWriteTime */
1027                          );
1028
1029         for ( dwIndex = 0; dwIndex < dwSymlinks; dwIndex++ ) {
1030             TCHAR szValueName[16];
1031             DWORD dwValueSize = 16;
1032             dwSize = sizeof(line);
1033             RegEnumValue( hkFreelance, dwIndex, szValueName, &dwValueSize, NULL,
1034                           &dwType, line, &dwSize);
1035
1036             cp=strchr(line, ':');
1037             memcpy(shortname, line, cp-line);
1038             shortname[cp-line]=0;
1039
1040             if (!strcmp(shortname, filename)) {
1041                 found = 1;
1042                 break;
1043             }
1044
1045             if (prefix_ok && strlen(shortname) - strlen(filename) == 1 && !strncmp(shortname, filename, strlen(filename))) {
1046                 found = 1;
1047                 break;
1048             }
1049         }
1050         for ( dwIndex = 0; dwIndex < dwSymlinks; dwIndex++ ) {
1051             TCHAR szValueName[16];
1052             DWORD dwValueSize = 16;
1053             dwSize = sizeof(line);
1054             RegEnumValue( hkFreelance, dwIndex, szValueName, &dwValueSize, NULL,
1055                           &dwType, line, &dwSize);
1056
1057             cp=strchr(line, ':');
1058             memcpy(shortname, line, cp-line);
1059             shortname[cp-line]=0;
1060
1061             if (!cm_stricmp_utf8(shortname, filename)) {
1062                 found = 1;
1063                 break;
1064             }
1065         }
1066         RegCloseKey(hkFreelance);
1067     }
1068
1069     lock_ReleaseMutex(&cm_Freelance_Lock);
1070
1071     return found;
1072 }
1073
1074 long cm_FreelanceAddMount(char *filename, char *cellname, char *volume, int rw, cm_fid_t *fidp)
1075 {
1076     FILE *fp;
1077     char hfile[260];
1078     char line[512];
1079     char fullname[CELL_MAXNAMELEN];
1080     int n;
1081     int alias = 0;
1082     HKEY hkFreelance = 0;
1083     DWORD dwType, dwSize;
1084     DWORD dwMountPoints;
1085     DWORD dwIndex;
1086     afs_uint32 code = 0;
1087
1088     /* before adding, verify the cell name; if it is not a valid cell,
1089        don't add the mount point.
1090        allow partial matches as a means of poor man's alias. */
1091     /* major performance issue? */
1092     osi_Log4(afsd_logp,"Freelance Add Mount request: filename=%s cellname=%s volume=%s %s",
1093               osi_LogSaveString(afsd_logp,filename),
1094               osi_LogSaveString(afsd_logp,cellname),
1095               osi_LogSaveString(afsd_logp,volume),
1096               rw ? "rw" : "ro");
1097
1098     if ( filename[0] == '\0' || cellname[0] == '\0' || volume[0] == '\0' )
1099         return CM_ERROR_INVAL;
1100
1101     if ( cm_FreelanceMountPointExists(filename, 0) ||
1102          cm_FreelanceSymlinkExists(filename, 0) ) {
1103         code = CM_ERROR_EXISTS;
1104         goto done;
1105     }
1106
1107     if (cellname[0] == '.') {
1108         if (!cm_GetCell_Gen(&cellname[1], fullname, CM_FLAG_CREATE))
1109             return CM_ERROR_INVAL;
1110     } else {
1111         if (!cm_GetCell_Gen(cellname, fullname, CM_FLAG_CREATE))
1112             return CM_ERROR_INVAL;
1113     }
1114
1115     osi_Log1(afsd_logp,"Freelance Adding Mount for Cell: %s",
1116               osi_LogSaveString(afsd_logp,cellname));
1117
1118     lock_ObtainMutex(&cm_Freelance_Lock);
1119
1120     if (RegOpenKeyEx( HKEY_LOCAL_MACHINE,
1121                       AFSREG_CLT_OPENAFS_SUBKEY "\\Freelance",
1122                       0,
1123                       KEY_READ|KEY_WRITE|KEY_QUERY_VALUE,
1124                       &hkFreelance) == ERROR_SUCCESS) {
1125
1126         RegQueryInfoKey( hkFreelance,
1127                          NULL,  /* lpClass */
1128                          NULL,  /* lpcClass */
1129                          NULL,  /* lpReserved */
1130                          NULL,  /* lpcSubKeys */
1131                          NULL,  /* lpcMaxSubKeyLen */
1132                          NULL,  /* lpcMaxClassLen */
1133                          &dwMountPoints, /* lpcValues */
1134                          NULL,  /* lpcMaxValueNameLen */
1135                          NULL,  /* lpcMaxValueLen */
1136                          NULL,  /* lpcbSecurityDescriptor */
1137                          NULL   /* lpftLastWriteTime */
1138                          );
1139
1140         if (rw)
1141             sprintf(line, "%s%%%s:%s.", filename, fullname, volume);
1142         else
1143             sprintf(line, "%s#%s:%s.", filename, fullname, volume);
1144
1145         /* If we are adding a new value, there must be an unused name
1146          * within the range 0 to dwMountPoints
1147          */
1148         for ( dwIndex = 0; dwIndex <= dwMountPoints; dwIndex++ ) {
1149             char szIndex[16];
1150             char szMount[1024];
1151
1152             dwSize = sizeof(szMount);
1153             sprintf(szIndex, "%d", dwIndex);
1154             if (RegQueryValueEx( hkFreelance, szIndex, 0, &dwType, szMount, &dwSize) != ERROR_SUCCESS) {
1155                 /* found an unused value */
1156                 dwType = REG_SZ;
1157                 dwSize = (DWORD)strlen(line) + 1;
1158                 RegSetValueEx( hkFreelance, szIndex, 0, dwType, line, dwSize);
1159                 break;
1160             } else {
1161                 int len = (int)strlen(filename);
1162                 if ( dwType == REG_SZ && !strncmp(filename, szMount, len) &&
1163                      (szMount[len] == '%' || szMount[len] == '#')) {
1164                     /* Replace the existing value */
1165                     dwType = REG_SZ;
1166                     dwSize = (DWORD)strlen(line) + 1;
1167                     RegSetValueEx( hkFreelance, szIndex, 0, dwType, line, dwSize);
1168                     break;
1169                 }
1170             }
1171         }
1172         RegCloseKey(hkFreelance);
1173     } else
1174     {
1175         cm_GetConfigDir(hfile, sizeof(hfile));
1176         strcat(hfile, AFS_FREELANCE_INI);
1177         fp = fopen(hfile, "r+");
1178         if (!fp)
1179             return CM_ERROR_INVAL;
1180         fgets(line, sizeof(line), fp);
1181         n = atoi(line);
1182         n++;
1183         fseek(fp, 0, SEEK_SET);
1184         fprintf(fp, "%d", n);
1185         fseek(fp, 0, SEEK_END);
1186         if (rw)
1187             fprintf(fp, "%s%%%s:%s.\n", filename, fullname, volume);
1188         else
1189             fprintf(fp, "%s#%s:%s.\n", filename, fullname, volume);
1190         fclose(fp);
1191     }
1192
1193     /* Do this while we are holding the lock */
1194     cm_noteLocalMountPointChange(TRUE);
1195     lock_ReleaseMutex(&cm_Freelance_Lock);
1196
1197   done:
1198     if (fidp) {
1199         cm_req_t req;
1200         cm_scache_t *scp;
1201         clientchar_t *cpath;
1202
1203         cm_InitReq(&req);
1204
1205         cpath = cm_FsStringToClientStringAlloc(filename, -1, NULL);
1206         if (!cpath)
1207             return CM_ERROR_NOSUCHPATH;
1208
1209         if (cm_getLocalMountPointChange()) {    // check for changes
1210             cm_clearLocalMountPointChange();    // clear the changefile
1211             cm_reInitLocalMountPoints();        // start reinit
1212         }
1213
1214         code = cm_NameI(cm_RootSCachep(cm_rootUserp, &req), cpath,
1215                         CM_FLAG_DIRSEARCH | CM_FLAG_CASEFOLD,
1216                         cm_rootUserp, NULL, &req, &scp);
1217         free(cpath);
1218         if (code)
1219             return code;
1220         *fidp = scp->fid;
1221         cm_ReleaseSCache(scp);
1222     }
1223
1224     return code;
1225 }
1226
1227 long cm_FreelanceRemoveMount(char *toremove)
1228 {
1229     int i, n;
1230     char* cp;
1231     char line[512];
1232     char shortname[200];
1233     char hfile[260], hfile2[260];
1234     FILE *fp1, *fp2;
1235     int found=0;
1236     HKEY hkFreelance = 0;
1237     DWORD dwType, dwSize;
1238     DWORD dwMountPoints;
1239     DWORD dwIndex;
1240
1241     lock_ObtainMutex(&cm_Freelance_Lock);
1242
1243     if (RegOpenKeyEx( HKEY_LOCAL_MACHINE,
1244                       AFSREG_CLT_OPENAFS_SUBKEY "\\Freelance",
1245                       0,
1246                       KEY_READ|KEY_WRITE|KEY_QUERY_VALUE,
1247                       &hkFreelance) == ERROR_SUCCESS) {
1248
1249         RegQueryInfoKey( hkFreelance,
1250                          NULL,  /* lpClass */
1251                          NULL,  /* lpcClass */
1252                          NULL,  /* lpReserved */
1253                          NULL,  /* lpcSubKeys */
1254                          NULL,  /* lpcMaxSubKeyLen */
1255                          NULL,  /* lpcMaxClassLen */
1256                          &dwMountPoints, /* lpcValues */
1257                          NULL,  /* lpcMaxValueNameLen */
1258                          NULL,  /* lpcMaxValueLen */
1259                          NULL,  /* lpcbSecurityDescriptor */
1260                          NULL   /* lpftLastWriteTime */
1261                          );
1262
1263         for ( dwIndex = 0; dwIndex < dwMountPoints; dwIndex++ ) {
1264             TCHAR szValueName[16];
1265             DWORD dwValueSize = 16;
1266             dwSize = sizeof(line);
1267             RegEnumValue( hkFreelance, dwIndex, szValueName, &dwValueSize, NULL,
1268                           &dwType, line, &dwSize);
1269
1270             cp=strchr(line, '#');
1271             if (!cp)
1272                 cp=strchr(line, '%');
1273             memcpy(shortname, line, cp-line);
1274             shortname[cp-line]=0;
1275
1276             if (!strcmp(shortname, toremove)) {
1277                 RegDeleteValue( hkFreelance, szValueName );
1278                 found = 1;
1279                 break;
1280             }
1281         }
1282         RegCloseKey(hkFreelance);
1283     } else
1284     {
1285         cm_GetConfigDir(hfile, sizeof(hfile));
1286         strcat(hfile, AFS_FREELANCE_INI);
1287         strcpy(hfile2, hfile);
1288         strcat(hfile2, "2");
1289         fp1=fopen(hfile, "r+");
1290         if (!fp1)
1291             return CM_ERROR_INVAL;
1292         fp2=fopen(hfile2, "w+");
1293         if (!fp2) {
1294             fclose(fp1);
1295             return CM_ERROR_INVAL;
1296         }
1297
1298         fgets(line, sizeof(line), fp1);
1299         n=atoi(line);
1300         fprintf(fp2, "%d\n", n-1);
1301
1302         for (i=0; i<n; i++) {
1303             fgets(line, sizeof(line), fp1);
1304             cp=strchr(line, '#');
1305             if (!cp)
1306                 cp=strchr(line, '%');
1307             memcpy(shortname, line, cp-line);
1308             shortname[cp-line]=0;
1309
1310             if (strcmp(shortname, toremove)==0) {
1311
1312             } else {
1313                 found = 1;
1314                 fputs(line, fp2);
1315             }
1316         }
1317
1318         fclose(fp1);
1319         fclose(fp2);
1320         if (found) {
1321             unlink(hfile);
1322             rename(hfile2, hfile);
1323         }
1324     }
1325
1326     if (found) {
1327         /* Do this while we are holding the lock */
1328         cm_noteLocalMountPointChange(TRUE);
1329     }
1330     lock_ReleaseMutex(&cm_Freelance_Lock);
1331     return (found ? 0 : CM_ERROR_NOSUCHFILE);
1332 }
1333
1334 long cm_FreelanceAddSymlink(char *filename, char *destination, cm_fid_t *fidp)
1335 {
1336     char line[512];
1337     char fullname[CELL_MAXNAMELEN] = "";
1338     int alias = 0;
1339     HKEY hkFreelanceSymlinks = 0;
1340     DWORD dwType, dwSize;
1341     DWORD dwSymlinks;
1342     DWORD dwIndex;
1343     afs_uint32 code = 0;
1344
1345     /*
1346      * before adding, verify the filename.  If it is already in use, either as
1347      * as mount point or a cellname, do not permit the creation of the symlink.
1348      */
1349     osi_Log2(afsd_logp,"Freelance Add Symlink request: filename=%s destination=%s",
1350               osi_LogSaveString(afsd_logp,filename),
1351               osi_LogSaveString(afsd_logp,destination));
1352
1353     if ( filename[0] == '\0' || destination[0] == '\0' )
1354         return CM_ERROR_INVAL;
1355
1356     /* Do not create the symlink if the name ends in a dot */
1357     if ( filename[strlen(filename)-1] == '.')
1358         return CM_ERROR_INVAL;
1359
1360     if ( cm_FreelanceMountPointExists(filename, 0) ||
1361          cm_FreelanceSymlinkExists(filename, 0) ) {
1362         code = CM_ERROR_EXISTS;
1363         goto done;
1364     }
1365
1366     if (filename[0] == '.') {
1367         cm_GetCell_Gen(&filename[1], fullname, CM_FLAG_CREATE);
1368         if (cm_stricmp_utf8(&filename[1],fullname) == 0) {
1369             code = CM_ERROR_EXISTS;
1370             goto done;
1371         }
1372     } else {
1373         cm_GetCell_Gen(filename, fullname, CM_FLAG_CREATE);
1374         if (cm_stricmp_utf8(filename,fullname) == 0) {
1375             code = CM_ERROR_EXISTS;
1376             goto done;
1377         }
1378     }
1379
1380     lock_ObtainMutex(&cm_Freelance_Lock);
1381
1382     if (RegCreateKeyEx( HKEY_LOCAL_MACHINE,
1383                         AFSREG_CLT_OPENAFS_SUBKEY "\\Freelance\\Symlinks",
1384                         0,
1385                         NULL,
1386                         REG_OPTION_NON_VOLATILE,
1387                         KEY_READ|KEY_WRITE|KEY_QUERY_VALUE,
1388                         NULL,
1389                         &hkFreelanceSymlinks,
1390                         NULL) == ERROR_SUCCESS) {
1391
1392         RegQueryInfoKey( hkFreelanceSymlinks,
1393                          NULL,  /* lpClass */
1394                          NULL,  /* lpcClass */
1395                          NULL,  /* lpReserved */
1396                          NULL,  /* lpcSubKeys */
1397                          NULL,  /* lpcMaxSubKeyLen */
1398                          NULL,  /* lpcMaxClassLen */
1399                          &dwSymlinks, /* lpcValues */
1400                          NULL,  /* lpcMaxValueNameLen */
1401                          NULL,  /* lpcMaxValueLen */
1402                          NULL,  /* lpcbSecurityDescriptor */
1403                          NULL   /* lpftLastWriteTime */
1404                          );
1405
1406         sprintf(line, "%s:%s.", filename, destination);
1407
1408         /* If we are adding a new value, there must be an unused name
1409          * within the range 0 to dwSymlinks
1410          */
1411         for ( dwIndex = 0; dwIndex <= dwSymlinks; dwIndex++ ) {
1412             char szIndex[16];
1413             char szLink[1024];
1414
1415             dwSize = sizeof(szLink);
1416             sprintf(szIndex, "%d", dwIndex);
1417             if (RegQueryValueEx( hkFreelanceSymlinks, szIndex, 0, &dwType, szLink, &dwSize) != ERROR_SUCCESS) {
1418                 /* found an unused value */
1419                 dwType = REG_SZ;
1420                 dwSize = (DWORD)strlen(line) + 1;
1421                 RegSetValueEx( hkFreelanceSymlinks, szIndex, 0, dwType, line, dwSize);
1422                 break;
1423             } else {
1424                 int len = (int)strlen(filename);
1425                 if ( dwType == REG_SZ && !strncmp(filename, szLink, len) && szLink[len] == ':') {
1426                     /* Replace the existing value */
1427                     dwType = REG_SZ;
1428                     dwSize = (DWORD)strlen(line) + 1;
1429                     RegSetValueEx( hkFreelanceSymlinks, szIndex, 0, dwType, line, dwSize);
1430                     break;
1431                 }
1432             }
1433         }
1434         RegCloseKey(hkFreelanceSymlinks);
1435     }
1436
1437     /* Do this while we are holding the lock */
1438     cm_noteLocalMountPointChange(TRUE);
1439     lock_ReleaseMutex(&cm_Freelance_Lock);
1440
1441   done:
1442     if (fidp) {
1443         cm_req_t req;
1444         cm_scache_t *scp;
1445         clientchar_t *cpath;
1446
1447         cm_InitReq(&req);
1448
1449         cpath = cm_FsStringToClientStringAlloc(filename, -1, NULL);
1450         if (!cpath) {
1451             code = CM_ERROR_NOSUCHPATH;
1452         } else {
1453             if (cm_getLocalMountPointChange()) {        // check for changes
1454                 cm_clearLocalMountPointChange();    // clear the changefile
1455                 cm_reInitLocalMountPoints();    // start reinit
1456             }
1457
1458             code = cm_NameI(cm_RootSCachep(cm_rootUserp, &req), cpath,
1459                              CM_FLAG_DIRSEARCH | CM_FLAG_CASEFOLD,
1460                              cm_rootUserp, NULL, &req, &scp);
1461             free(cpath);
1462             if (code == 0) {
1463                 *fidp = scp->fid;
1464                 cm_ReleaseSCache(scp);
1465             }
1466         }
1467     }
1468
1469     return code;
1470 }
1471
1472 long cm_FreelanceRemoveSymlink(char *toremove)
1473 {
1474     char* cp;
1475     char line[512];
1476     char shortname[200];
1477     int found=0;
1478     HKEY hkFreelanceSymlinks = 0;
1479     DWORD dwType, dwSize;
1480     DWORD dwSymlinks;
1481     DWORD dwIndex;
1482
1483     lock_ObtainMutex(&cm_Freelance_Lock);
1484
1485     if (RegOpenKeyEx( HKEY_LOCAL_MACHINE,
1486                       AFSREG_CLT_OPENAFS_SUBKEY "\\Freelance\\Symlinks",
1487                       0,
1488                       KEY_READ|KEY_WRITE|KEY_QUERY_VALUE,
1489                       &hkFreelanceSymlinks) == ERROR_SUCCESS) {
1490
1491         RegQueryInfoKey( hkFreelanceSymlinks,
1492                          NULL,  /* lpClass */
1493                          NULL,  /* lpcClass */
1494                          NULL,  /* lpReserved */
1495                          NULL,  /* lpcSubKeys */
1496                          NULL,  /* lpcMaxSubKeyLen */
1497                          NULL,  /* lpcMaxClassLen */
1498                          &dwSymlinks, /* lpcValues */
1499                          NULL,  /* lpcMaxValueNameLen */
1500                          NULL,  /* lpcMaxValueLen */
1501                          NULL,  /* lpcbSecurityDescriptor */
1502                          NULL   /* lpftLastWriteTime */
1503                          );
1504
1505         for ( dwIndex = 0; dwIndex < dwSymlinks; dwIndex++ ) {
1506             TCHAR szValueName[16];
1507             DWORD dwValueSize = 16;
1508             dwSize = sizeof(line);
1509             RegEnumValue( hkFreelanceSymlinks, dwIndex, szValueName, &dwValueSize, NULL,
1510                           &dwType, line, &dwSize);
1511
1512             cp=strchr(line, ':');
1513             memcpy(shortname, line, cp-line);
1514             shortname[cp-line]=0;
1515
1516             if (!strcmp(shortname, toremove)) {
1517                 RegDeleteValue( hkFreelanceSymlinks, szValueName );
1518                 found = 1;
1519                 break;
1520             }
1521         }
1522         RegCloseKey(hkFreelanceSymlinks);
1523     }
1524
1525     if (found) {
1526         /* Do this while we are holding the lock */
1527         cm_noteLocalMountPointChange(TRUE);
1528     }
1529     lock_ReleaseMutex(&cm_Freelance_Lock);
1530     return (found ? 0 : CM_ERROR_NOSUCHFILE);
1531 }
1532
1533 long
1534 cm_FreelanceFetchMountPointString(cm_scache_t *scp)
1535 {
1536     lock_ObtainMutex(&cm_Freelance_Lock);
1537     if (scp->mpDataVersion != scp->dataVersion &&
1538         scp->fid.cell == AFS_FAKE_ROOT_CELL_ID &&
1539         scp->fid.volume == AFS_FAKE_ROOT_VOL_ID &&
1540         (afs_int32)(scp->fid.unique - cm_data.fakeUnique) - 1 >= 0 &&
1541         scp->fid.unique - cm_data.fakeUnique <= cm_noLocalMountPoints) {
1542         strncpy(scp->mountPointStringp, cm_localMountPoints[scp->fid.unique-cm_data.fakeUnique-1].mountPointStringp, MOUNTPOINTLEN);
1543         scp->mountPointStringp[MOUNTPOINTLEN-1] = 0;    /* null terminate */
1544         scp->mpDataVersion = scp->dataVersion;
1545     }
1546     lock_ReleaseMutex(&cm_Freelance_Lock);
1547
1548     return 0;
1549 }
1550
1551 long
1552 cm_FreelanceFetchFileType(cm_scache_t *scp)
1553 {
1554     lock_ObtainMutex(&cm_Freelance_Lock);
1555     if (scp->fid.cell == AFS_FAKE_ROOT_CELL_ID &&
1556         scp->fid.volume == AFS_FAKE_ROOT_VOL_ID &&
1557         (afs_int32)(scp->fid.unique - cm_data.fakeUnique) - 1 >= 0 &&
1558         scp->fid.unique - cm_data.fakeUnique <= cm_noLocalMountPoints)
1559     {
1560         scp->fileType = cm_localMountPoints[scp->fid.unique-cm_data.fakeUnique-1].fileType;
1561
1562         if (scp->fileType == CM_SCACHETYPE_SYMLINK &&
1563             !strnicmp(cm_localMountPoints[scp->fid.unique-cm_data.fakeUnique-1].mountPointStringp, "msdfs:", strlen("msdfs:")) )
1564         {
1565             scp->fileType = CM_SCACHETYPE_DFSLINK;
1566         }
1567     } else {
1568         scp->fileType = CM_SCACHETYPE_INVALID;
1569     }
1570     lock_ReleaseMutex(&cm_Freelance_Lock);
1571
1572     return 0;
1573 }
1574 #endif /* AFS_FREELANCE_CLIENT */