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