ticket-2618-patches-20031207
[openafs.git] / src / WINNT / afsd / cm_freelance.c
1 #include <afs/param.h>
2 #include <afs/stds.h>
3
4 #ifndef DJGPP
5 #include <windows.h>
6 #include <winsock2.h>
7 #else
8 #include <netdb.h>
9 #endif /* !DJGPP */
10 #include <stdlib.h>
11 #include <malloc.h>
12 #include <string.h>
13
14 #include <rx/rx.h>
15
16 #include "afsd.h"
17 #ifdef AFS_FREELANCE_CLIENT
18 #include "cm_freelance.h"
19 #include "stdio.h"
20
21 extern void afsi_log(char *pattern, ...);
22
23 int cm_noLocalMountPoints;
24 int cm_fakeDirSize;
25 int cm_fakeDirCallback=0;
26 int cm_fakeGettingCallback=0;
27 int cm_fakeDirVersion = 0x8;
28 cm_localMountPoint_t* cm_localMountPoints;
29 osi_mutex_t cm_Freelance_Lock;
30 int cm_localMountPointChangeFlag = 0;
31 int cm_freelanceEnabled = 0;
32
33 void cm_InitFakeRootDir();
34
35 void cm_InitFreelance() {
36   
37         lock_InitializeMutex(&cm_Freelance_Lock, "Freelance Lock");
38   
39         // yj: first we make a call to cm_initLocalMountPoints
40         // to read all the local mount points from an ini file
41         cm_InitLocalMountPoints();
42         
43         // then we make a call to InitFakeRootDir to create
44         // a fake root directory based on the local mount points
45         cm_InitFakeRootDir();
46
47         // --- end of yj code
48 }
49
50 /* yj: Initialization of the fake root directory */
51 /* to be called while holding freelance lock unless during init. */
52 void cm_InitFakeRootDir() {
53         
54         int i, t1, t2;
55         char* currentPos;
56         int noChunks;
57
58         // allocate space for the fake info
59         cm_dirHeader_t fakeDirHeader;
60         cm_dirEntry_t fakeEntry;
61         cm_pageHeader_t fakePageHeader;
62
63         // i'm going to calculate how much space is needed for
64         // this fake root directory. we have these rules:
65         // 1. there are cm_noLocalMountPoints number of entries
66         // 2. each page is CM_DIR_PAGESIZE in size
67         // 3. the first 13 chunks of the first page are used for
68         //    some header stuff
69         // 4. the first chunk of all subsequent pages are used
70         //    for page header stuff
71         // 5. a max of CM_DIR_EPP entries are allowed per page
72         // 6. each entry takes 1 or more chunks, depending on 
73         //    the size of the mount point string, as determined
74         //    by cm_NameEntries
75         // 7. each chunk is CM_DIR_CHUNKSIZE bytes
76
77         int CPP = CM_DIR_PAGESIZE / CM_DIR_CHUNKSIZE;
78         int curChunk = 13;      // chunks 0 - 12 are used for header stuff
79                                                 // of the first page in the directory
80         int curPage = 0;
81         int curDirEntry = 0;
82         int curDirEntryInPage = 0;
83         int sizeOfCurEntry;
84         int dirSize;
85
86         /* Reserve 2 directory chunks for "." and ".." */
87         curChunk += 2;
88
89         while (curDirEntry!=cm_noLocalMountPoints) {
90                 sizeOfCurEntry = cm_NameEntries((cm_localMountPoints+curDirEntry)->namep, 0);
91                 if ((curChunk + sizeOfCurEntry >= CPP) ||
92                         (curDirEntryInPage + 1 >= CM_DIR_EPP)) {
93                         curPage++;
94                         curDirEntryInPage = 0;
95                         curChunk = 1;
96                 }
97                 curChunk += sizeOfCurEntry;
98                 curDirEntry++;
99                 curDirEntryInPage++;
100         }
101
102         dirSize = (curPage+1) *  CM_DIR_PAGESIZE;
103         cm_FakeRootDir = malloc(dirSize);
104         cm_fakeDirSize = dirSize;
105
106         
107
108         // yj: when we get here, we've figured out how much memory we need and 
109         // allocated the appropriate space for it. we now prceed to fill
110         // it up with entries.
111         curPage = 0;
112         curDirEntry = 0;
113         curDirEntryInPage = 0;
114         curChunk = 0;
115         
116         // fields in the directory entry that are unused.
117         fakeEntry.flag = 1;
118         fakeEntry.length = 0;
119         fakeEntry.next = 0;
120         fakeEntry.fid.unique = htonl(1);
121
122         // the first page is special, it uses fakeDirHeader instead of fakePageHeader
123         // we fill up the page with dirEntries that belong there and we make changes
124         // to the fakeDirHeader.header.freeBitmap along the way. Then when we're done
125         // filling up the dirEntries in this page, we copy the fakeDirHeader into 
126         // the top of the page.
127
128         // init the freeBitmap array
129         for (i=0; i<8; i++) 
130                 fakeDirHeader.header.freeBitmap[i]=0;
131
132         fakeDirHeader.header.freeBitmap[0] = 0xff;
133         fakeDirHeader.header.freeBitmap[1] = 0x7f;
134         
135
136         // we start counting at 13 because the 0th to 12th chunks are used for header
137         curChunk = 13;
138
139         // stick the first 2 entries "." and ".." in
140         fakeEntry.fid.unique = htonl(1);
141         fakeEntry.fid.vnode = htonl(1);
142         strcpy(fakeEntry.name, ".");
143         currentPos = cm_FakeRootDir + curPage * CM_DIR_PAGESIZE + curChunk * CM_DIR_CHUNKSIZE;
144         memcpy(currentPos, &fakeEntry, CM_DIR_CHUNKSIZE);
145         curChunk++; curDirEntryInPage++;
146         strcpy(fakeEntry.name, "..");
147         currentPos = cm_FakeRootDir + curPage * CM_DIR_PAGESIZE + curChunk * CM_DIR_CHUNKSIZE;
148         memcpy(currentPos, &fakeEntry, CM_DIR_CHUNKSIZE);
149         curChunk++; curDirEntryInPage++;
150
151         // keep putting stuff into page 0 if
152         // 1. we're not done with all entries
153         // 2. we have less than CM_DIR_EPP entries in page 0
154         // 3. we're not out of chunks in page 0
155
156         while( (curDirEntry!=cm_noLocalMountPoints) && 
157                    (curDirEntryInPage < CM_DIR_EPP) &&
158                    (curChunk + cm_NameEntries((cm_localMountPoints+curDirEntry)->namep, 0) <= CPP)) 
159         {
160
161                 noChunks = cm_NameEntries((cm_localMountPoints+curDirEntry)->namep, 0);
162                 fakeEntry.fid.vnode = htonl(curDirEntry + 2);
163                 currentPos = cm_FakeRootDir + curPage * CM_DIR_PAGESIZE + curChunk * CM_DIR_CHUNKSIZE;
164
165                 memcpy(currentPos, &fakeEntry, CM_DIR_CHUNKSIZE);
166                 strcpy(currentPos + 12, (cm_localMountPoints+curDirEntry)->namep);
167                 curDirEntry++;
168                 curDirEntryInPage++;
169                 for (i=0; i<noChunks; i++) {
170                         t1 = (curChunk + i) / 8;
171                         t2 = curChunk + i - (t1*8);
172                         fakeDirHeader.header.freeBitmap[t1] |= (1 << t2);
173                 }
174                 curChunk+=noChunks;
175         }
176
177         // when we get here, we're done with filling in the entries for page 0
178         // copy in the header info
179
180         memcpy(cm_FakeRootDir, &fakeDirHeader, 13 * CM_DIR_CHUNKSIZE);
181
182         curPage++;
183
184         // ok, page 0's done. Move on to the next page.
185         while (curDirEntry!=cm_noLocalMountPoints) {
186                 // setup a new page
187                 curChunk = 1;                   // the zeroth chunk is reserved for page header
188                 curDirEntryInPage = 0; 
189                 for (i=0; i<8; i++) {
190                         fakePageHeader.freeBitmap[i]=0;
191                 }
192                 fakePageHeader.freeCount = 0;
193                 fakePageHeader.pgcount = 0;
194                 fakePageHeader.tag = htons(1234);
195                 
196                 // while we're on the same page...
197                 while ( (curDirEntry!=cm_noLocalMountPoints) &&
198                                 (curDirEntryInPage < CM_DIR_EPP) &&
199                             (curChunk + cm_NameEntries((cm_localMountPoints+curDirEntry)->namep, 0) <= CPP))
200                 {
201                         // add an entry to this page
202
203                         noChunks = cm_NameEntries((cm_localMountPoints+curDirEntry)->namep, 0);
204                         fakeEntry.fid.vnode=htonl(curDirEntry+2);
205                         currentPos = cm_FakeRootDir + curPage * CM_DIR_PAGESIZE + curChunk * CM_DIR_CHUNKSIZE;
206                         memcpy(currentPos, &fakeEntry, CM_DIR_CHUNKSIZE);
207                         strcpy(currentPos + 12, (cm_localMountPoints+curDirEntry)->namep);
208                         curDirEntry++;
209                         curDirEntryInPage++;
210                         for (i=0; i<noChunks; i++) {
211                                 t1 = (curChunk + i) / 8;
212                                 t2 = curChunk + i - (t1*8);
213                                 fakePageHeader.freeBitmap[t1] |= (1 << t2);
214                         }
215                         curChunk+=noChunks;
216                 }
217                 memcpy(cm_FakeRootDir + curPage * CM_DIR_PAGESIZE, &fakePageHeader, sizeof(fakePageHeader));
218
219                 curPage++;
220         }
221         
222         // we know the fakeDir is setup properly, so we claim that we have callback
223         cm_fakeDirCallback=1;
224
225         // when we get here, we've set up everything! done!
226
227
228 }
229
230 int cm_FakeRootFid(cm_fid_t *fidp)
231 {
232   fidp->cell = 0x1;            /* root cell */
233         fidp->volume = 0x20000001;   /* root.afs ? */
234         fidp->vnode = 0x1;
235         fidp->unique = 0x1;
236 }
237   
238 int cm_getLocalMountPointChange() {
239   return cm_localMountPointChangeFlag;
240 }
241
242 int cm_clearLocalMountPointChange() {
243   cm_localMountPointChangeFlag = 0;
244 }
245
246 /* called directly from ioctl */
247 /* called while not holding freelance lock */
248 int cm_noteLocalMountPointChange() {
249   lock_ObtainMutex(&cm_Freelance_Lock);
250   cm_fakeDirVersion++;
251   cm_localMountPointChangeFlag = 1;
252   lock_ReleaseMutex(&cm_Freelance_Lock);
253   return 1;
254 }
255
256 int cm_reInitLocalMountPoints() {
257         cm_fid_t aFid;
258         int i, hash;
259         cm_scache_t *scp, **lscpp, *tscp;
260
261         
262         printf("\n\n----- reinitialization starts ----- \n");
263
264
265         // first we invalidate all the SCPs that were created
266         // for the local mount points
267
268         printf("Invalidating local mount point scp...  ");
269
270         aFid.cell = 0x1;
271         aFid.volume=0x20000001;
272         aFid.unique=0x1;
273         aFid.vnode=0x2;
274
275         lock_ObtainWrite(&cm_scacheLock);
276         lock_ObtainMutex(&cm_Freelance_Lock);  /* always scache then freelance lock */
277         for (i=0; i<cm_noLocalMountPoints; i++) {
278                 hash = CM_SCACHE_HASH(&aFid);
279                 for (scp=cm_hashTablep[hash]; scp; scp=scp->nextp) {
280                         if (scp->fid.volume == aFid.volume &&
281                                 scp->fid.vnode == aFid.vnode &&
282                                 scp->fid.unique == aFid.unique 
283                                 ) {
284
285                                 // mark the scp to be reused
286                                 lock_ReleaseWrite(&cm_scacheLock);
287                                 lock_ObtainMutex(&scp->mx);
288                                 cm_DiscardSCache(scp);
289                                 lock_ReleaseMutex(&scp->mx);
290                                 cm_CallbackNotifyChange(scp);
291                                 lock_ObtainWrite(&cm_scacheLock);
292                                 scp->refCount--;
293
294                                 // take the scp out of the hash
295                                 lscpp = &cm_hashTablep[hash];
296                                 for (tscp=*lscpp; tscp; lscpp = &tscp->nextp, tscp = *lscpp) {
297                                         if (tscp == scp) break;
298                                 }
299                                 *lscpp = scp->nextp;
300                                 scp->flags &= ~CM_SCACHEFLAG_INHASH;
301
302
303                         }
304                 }
305                 aFid.vnode = aFid.vnode + 1;
306         }
307         lock_ReleaseWrite(&cm_scacheLock);
308         printf("\tall old scp cleared!\n");
309
310         // we must free the memory that was allocated in the prev
311         // cm_InitLocalMountPoints call
312         printf("Removing old localmountpoints...  ");
313         free(cm_localMountPoints);
314         printf("\tall old localmountpoints cleared!\n");
315
316         // now re-init the localmountpoints
317         printf("Creating new localmountpoints...  ");
318         cm_InitLocalMountPoints();
319         printf("\tcreated new set of localmountpoints!\n");
320         
321         
322         // now we have to free the memory allocated in cm_initfakerootdir
323         printf("Removing old fakedir...  ");
324         free(cm_FakeRootDir);
325         printf("\t\told fakedir removed!\n");
326
327         // then we re-create that dir
328         printf("Creating new fakedir...  ");
329         cm_InitFakeRootDir();
330         printf("\t\tcreated new fakedir!\n");   
331
332         lock_ReleaseMutex(&cm_Freelance_Lock);
333
334         printf("----- reinit complete -----\n\n");
335 }
336
337
338 // yj: open up the ini file and read all the local mount 
339 // points that are stored there. Part of the initialization
340 // process for the freelance client.
341 /* to be called while holding freelance lock unless during init. */
342 long cm_InitLocalMountPoints() {
343         
344         FILE *fp;
345         char line[200];
346         int i;
347         char* t;
348         cm_localMountPoint_t* aLocalMountPoint;
349         char hdir[120];
350
351         cm_GetConfigDir(hdir);
352         strcat(hdir, AFS_FREELANCE_INI);
353         // open the ini file for reading
354         fp = fopen(hdir, "r");
355
356         // if we fail to open the file, create an empty one
357         if (!fp) {
358           fp = fopen(hdir, "w");
359           fputs("0\n", fp);
360           fclose(fp);
361           return 0;  /* success */
362         }
363
364         // we successfully opened the file
365 #ifdef DEBUG
366         fprintf(stderr, "opened afs_freelance.ini\n");
367 #endif
368         
369         // now we read the first line to see how many entries
370         // there are
371         fgets(line, 200, fp);
372
373         // if the line is empty at any point when we're reading
374         // we're screwed. report error and return.
375         if (*line==0) {
376                 afsi_log("error occurred while reading afs_freelance.ini");
377                 fprintf(stderr, "error occurred while reading afs_freelance.ini");
378                 return -1;
379         }
380
381         // get the number of entries there are from the first line
382         // that we read
383         cm_noLocalMountPoints = atoi(line);
384
385         // create space to store the local mount points
386         cm_localMountPoints = malloc(sizeof(cm_localMountPoint_t) * cm_noLocalMountPoints);
387         aLocalMountPoint = cm_localMountPoints;
388                 
389         // now we read n lines and parse them into local mount points
390         // where n is the number of local mount points there are, as
391         // determined above.
392         // Each line in the ini file represents 1 local mount point and 
393         // is in the format xxx#yyy:zzz, where xxx is the directory
394         // entry name, yyy is the cell name and zzz is the volume name.
395         // #yyy:zzz together make up the mount point.
396         for (i=0; i<cm_noLocalMountPoints; i++) {
397                 fgets(line, 200, fp);
398                 // check that the line is not empty
399                 if (line[0]==0) {
400                         afsi_log("error occurred while parsing entry in %s: empty line in line %d", AFS_FREELANCE_INI, i);
401                         fprintf(stderr, "error occurred while parsing entry in afs_freelance.ini: empty line in line %d", i);
402                         return -1;
403                 }
404                 // line is not empty, so let's parse it
405                 t = strchr(line, '#');
406                 // make sure that there is a '#' separator in the line
407                 if (!t) {
408                         afsi_log("error occurred while parsing entry in %s: no # separator in line %d", AFS_FREELANCE_INI, i);
409                         fprintf(stderr, "error occurred while parsing entry in afs_freelance.ini: no # separator in line %d", i);
410                         return -1;
411                 }
412                 aLocalMountPoint->namep=malloc(t-line+1);
413                 memcpy(aLocalMountPoint->namep, line, t-line);
414                 *(aLocalMountPoint->namep + (t-line)) = 0;
415                 aLocalMountPoint->mountPointStringp=malloc(strlen(line) - (t-line) + 1);
416                 memcpy(aLocalMountPoint->mountPointStringp, t, strlen(line)-(t-line)-2);
417                 *(aLocalMountPoint->mountPointStringp + (strlen(line)-(t-line)-2)) = 0;
418 #ifdef DEBUG
419                 fprintf(stderr, "found mount point: name %s, string %s\n",
420                         aLocalMountPoint->namep,
421                         aLocalMountPoint->mountPointStringp);
422 #endif
423                 
424                 aLocalMountPoint++;
425
426         }
427         fclose(fp);
428         return 0;
429 }
430
431
432 int cm_getNoLocalMountPoints() {
433         return cm_noLocalMountPoints;
434 }
435
436 cm_localMountPoint_t* cm_getLocalMountPoint(int vnode) {
437         return 0;
438 }
439
440 long cm_FreelanceAddMount(char *filename, char *cellname, char *volume, cm_fid_t *fidp)
441 {
442     FILE *fp;
443     char hfile[120];
444     char line[200];
445     char fullname[200];
446     int n;
447
448     /* before adding, verify the cell name; if it is not a valid cell,
449        don't add the mount point */
450     /* major performance issue? */
451     if (!cm_GetCell_Gen(cellname, fullname, CM_FLAG_CREATE))
452       return -1;
453 #if 0
454     if (strcmp(cellname, fullname) != 0)   /* no partial matches allowed */
455       return -1;
456 #endif
457     
458     lock_ObtainMutex(&cm_Freelance_Lock);
459
460      cm_GetConfigDir(hfile);
461      strcat(hfile, AFS_FREELANCE_INI);
462      fp = fopen(hfile, "r+");
463      if (!fp)
464        return CM_ERROR_INVAL;
465      fgets(line, 200, fp);
466      n = atoi(line);
467      n++;
468      fseek(fp, 0, SEEK_SET);
469      fprintf(fp, "%d", n);
470      fseek(fp, 0, SEEK_END);
471      fprintf(fp, "%s#%s:%s\n", filename, fullname, volume);
472      fclose(fp);
473      lock_ReleaseMutex(&cm_Freelance_Lock);
474
475      /*cm_reInitLocalMountPoints(&vnode);*/
476      if (fidp) {
477        fidp->unique = 1;
478        fidp->vnode = cm_noLocalMountPoints + 1;   /* vnode value of last mt pt */
479      }
480      cm_noteLocalMountPointChange();
481      
482      return 0;
483 }
484
485 long cm_FreelanceRemoveMount(char *toremove)
486 {
487      int i, n;
488      char* cp;
489      char line[200];
490      char shortname[200];
491      char hfile[120], hfile2[120];
492      FILE *fp1, *fp2;
493      int found=0;
494
495     lock_ObtainMutex(&cm_Freelance_Lock);
496
497      cm_GetConfigDir(hfile);
498      strcat(hfile, AFS_FREELANCE_INI);
499      strcpy(hfile2, hfile);
500      strcat(hfile2, "2");
501      fp1=fopen(hfile, "r+");
502      if (!fp1)
503        return CM_ERROR_INVAL;
504      fp2=fopen(hfile2, "w+");
505      if (!fp2) {
506        fclose(fp1);
507        return CM_ERROR_INVAL;
508      }
509
510      fgets(line, 200, fp1);
511      n=atoi(line);
512      fprintf(fp2, "%d\n", n-1);
513
514      for (i=0; i<n; i++) {
515           fgets(line, 200, fp1);
516           cp=strchr(line, '#');
517           memcpy(shortname, line, cp-line);
518           shortname[cp-line]=0;
519
520           if (strcmp(shortname, toremove)==0) {
521
522           } else {
523             found = 1;
524             fputs(line, fp2);
525           }
526      }
527
528      fclose(fp1);
529      fclose(fp2);
530      if (!found)
531        return CM_ERROR_NOSUCHFILE;
532
533      unlink(hfile);
534      rename(hfile2, hfile);
535
536      lock_ReleaseMutex(&cm_Freelance_Lock);
537
538      cm_noteLocalMountPointChange();
539      return 0;
540 }
541
542 #endif /* AFS_FREELANCE_CLIENT */