]> arthur.barton.de Git - netatalk.git/blob - etc/afpd/catsearch.c
89a6d5733aed67b6c13de4d41f8b3f357928d0c2
[netatalk.git] / etc / afpd / catsearch.c
1 /* 
2  * Netatalk 2002 (c)
3  * Copyright (C) 1990, 1993 Regents of The University of Michigan
4  * Copyright (C) 2010 Frank Lahm
5  * All Rights Reserved. See COPYRIGHT
6  */
7
8
9 /*
10  * This file contains FPCatSearch implementation. FPCatSearch performs
11  * file/directory search based on specified criteria. It is used by client
12  * to perform fast searches on (propably) big volumes. So, it has to be
13  * pretty fast.
14  *
15  * This implementation bypasses most of adouble/libatalk stuff as long as
16  * possible and does a standard filesystem search. It calls higher-level
17  * libatalk/afpd functions only when it is really needed, mainly while
18  * returning some non-UNIX information or filtering by non-UNIX criteria.
19  *
20  * Initial version written by Rafal Lewczuk <rlewczuk@pronet.pl>
21  *
22  * Starting with Netatalk 2.2 searching by name criteria utilizes the
23  * CNID database in conjunction with an enhanced cnid_dbd. This requires
24  * the use of cnidscheme:dbd for the searched volume, the new functionality
25  * is not built into cnidscheme:cdb.
26  */
27
28 #ifdef HAVE_CONFIG_H
29 #include "config.h"
30 #endif /* HAVE_CONFIG_H */
31
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <errno.h>
35 #include <ctype.h>
36 #include <string.h>
37 #include <time.h>
38 #include <string.h>
39 #include <sys/file.h>
40 #include <netinet/in.h>
41
42 #include <atalk/afp.h>
43 #include <atalk/adouble.h>
44 #include <atalk/logger.h>
45 #include <atalk/cnid.h>
46 #include <atalk/cnid_dbd_private.h>
47 #include <atalk/util.h>
48 #include <atalk/bstradd.h>
49 #include <atalk/unicode.h>
50 #include <atalk/globals.h>
51
52 #include "desktop.h"
53 #include "directory.h"
54 #include "dircache.h"
55 #include "file.h"
56 #include "volume.h"
57 #include "filedir.h"
58 #include "fork.h"
59
60
61 struct finderinfo {
62         u_int32_t f_type;
63         u_int32_t creator;
64         u_int16_t attrs;    /* File attributes (high 8 bits)*/
65         u_int16_t label;    /* Label (low 8 bits )*/
66         char reserved[22]; /* Unknown (at least for now...) */
67 };
68
69 typedef char packed_finder[ADEDLEN_FINDERI];
70
71 /* Known attributes:
72  * 0x04 - has a custom icon
73  * 0x20 - name/icon is locked
74  * 0x40 - is invisible
75  * 0x80 - is alias
76  *
77  * Known labels:
78  * 0x02 - project 2
79  * 0x04 - project 1
80  * 0x06 - personal
81  * 0x08 - cool
82  * 0x0a - in progress
83  * 0x0c - hot
84  * 0x0e - essential
85  */
86
87 /* This is our search-criteria structure. */
88 struct scrit {
89         u_int32_t rbitmap;          /* Request bitmap - which values should we check ? */
90         u_int16_t fbitmap, dbitmap; /* file & directory bitmap - which values should we return ? */
91         u_int16_t attr;             /* File attributes */
92         time_t cdate;               /* Creation date */
93         time_t mdate;               /* Last modification date */
94         time_t bdate;               /* Last backup date */
95         u_int32_t pdid;             /* Parent DID */
96     u_int16_t offcnt;           /* Offspring count */
97         struct finderinfo finfo;    /* Finder info */
98         char lname[64];             /* Long name */ 
99         char utf8name[514];         /* UTF8 or UCS2 name */ /* for convert_charset dest_len parameter +2 */
100 };
101
102 /*
103  * Directory tree search is recursive by its nature. But AFP specification
104  * requires FPCatSearch to pause after returning n results and be able to
105  * resume the search later. So we have to do recursive search using flat
106  * (iterative) algorithm and remember all directories to look into in an
107  * stack-like structure. The structure below is one item of directory stack.
108  *
109  */
110 struct dsitem {
111 //      struct dir *dir; /* Structure describing this directory */
112 //  cnid_t did;      /* CNID of this directory           */
113         int pidx;        /* Parent's dsitem structure index. */
114         int checked;     /* Have we checked this directory ? */
115         int path_len;
116         char *path;      /* absolute UNIX path to this directory */
117 };
118  
119
120 #define DS_BSIZE 128
121 static int save_cidx = -1; /* Saved index of currently scanned directory. */
122 static struct dsitem *dstack = NULL; /* Directory stack data... */
123 static int dssize = 0;               /* Directory stack (allocated) size... */
124 static int dsidx = 0;                /* First free item index... */
125 static struct scrit c1, c2;          /* search criteria */
126
127 /* Clears directory stack. */
128 static void clearstack(void) 
129 {
130         save_cidx = -1;
131         while (dsidx > 0) {
132                 dsidx--;
133                 free(dstack[dsidx].path);
134         }
135 }
136
137 /* Puts new item onto directory stack. */
138 static int addstack(char *uname, struct dir *dir, int pidx)
139 {
140         struct dsitem *ds;
141         size_t         l, u;
142     struct dsitem *tmpds = NULL;
143
144         /* check if we have some space on stack... */
145         if (dsidx >= dssize) {
146                 dssize += DS_BSIZE;
147                 tmpds = realloc(dstack, dssize * sizeof(struct dsitem));        
148                 if (tmpds == NULL) {
149             clearstack();
150             free(dstack);
151                         return -1;
152         }
153         dstack = tmpds;
154         }
155
156         /* Put new element. Allocate and copy lname and path. */
157         ds = dstack + dsidx++;
158 //      ds->did = dir->d_did;
159         ds->pidx = pidx;
160         ds->checked = 0;
161         if (pidx >= 0) {
162             l = dstack[pidx].path_len;
163             u = strlen(uname) +1;
164             if (!(ds->path = malloc(l + u + 1) ))
165                         return -1;
166                 memcpy(ds->path, dstack[pidx].path, l);
167                 ds->path[l] = '/';
168                 memcpy(&ds->path[l+1], uname, u);
169                 ds->path_len = l +u;
170         }
171         else {
172             ds->path = strdup(uname);
173                 ds->path_len = strlen(uname);
174         }
175         return 0;
176 }
177
178 /* Removes checked items from top of directory stack. Returns index of the first unchecked elements or -1. */
179 static int reducestack(void)
180 {
181         int r;
182         if (save_cidx != -1) {
183                 r = save_cidx;
184                 save_cidx = -1;
185                 return r;
186         }
187
188         while (dsidx > 0) {
189                 if (dstack[dsidx-1].checked) {
190                         dsidx--;
191                         free(dstack[dsidx].path);
192                 } else
193                         return dsidx - 1;
194         } 
195         return -1;
196
197
198 /* Looks up for an opened adouble structure, opens resource fork of selected file. 
199  * FIXME What about noadouble?
200 */
201 static struct adouble *adl_lkup(struct vol *vol, struct path *path, struct adouble *adp)
202 {
203         static struct adouble ad;
204         
205         struct ofork *of;
206         int isdir;
207         
208         if (adp)
209             return adp;
210             
211         isdir  = S_ISDIR(path->st.st_mode);
212
213         if (!isdir && (of = of_findname(path))) {
214                 adp = of->of_ad;
215         } else {
216                 ad_init(&ad, vol->v_adouble, vol->v_ad_options);
217                 adp = &ad;
218         } 
219
220     if ( ad_metadata( path->u_name, ((isdir) ? ADFLAGS_DIR : 0), adp) < 0 ) {
221         adp = NULL; /* FIXME without resource fork adl_lkup will be call again */
222     }
223     
224         return adp;     
225 }
226
227 /* -------------------- */
228 static struct finderinfo *unpack_buffer(struct finderinfo *finfo, char *buffer)
229 {
230         memcpy(&finfo->f_type,  buffer +FINDERINFO_FRTYPEOFF, sizeof(finfo->f_type));
231         memcpy(&finfo->creator, buffer +FINDERINFO_FRCREATOFF, sizeof(finfo->creator));
232         memcpy(&finfo->attrs,   buffer +FINDERINFO_FRFLAGOFF, sizeof(finfo->attrs));
233         memcpy(&finfo->label,   buffer +FINDERINFO_FRFLAGOFF, sizeof(finfo->label));
234         finfo->attrs &= 0xff00; /* high 8 bits */
235         finfo->label &= 0xff;   /* low 8 bits */
236
237         return finfo;
238 }
239
240 /* -------------------- */
241 static struct finderinfo *
242 unpack_finderinfo(struct vol *vol, struct path *path, struct adouble **adp, struct finderinfo *finfo, int islnk)
243 {
244         packed_finder  buf;
245         void           *ptr;
246         
247     *adp = adl_lkup(vol, path, *adp);
248         ptr = get_finderinfo(vol, path->u_name, *adp, &buf,islnk);
249         return unpack_buffer(finfo, ptr);
250 }
251
252 /* -------------------- */
253 #define CATPBIT_PARTIAL 31
254 /* Criteria checker. This function returns a 2-bit value. */
255 /* bit 0 means if checked file meets given criteria. */
256 /* bit 1 means if it is a directory and we should descent into it. */
257 /* uname - UNIX name 
258  * fname - our fname (translated to UNIX)
259  * cidx - index in directory stack
260  */
261 static int crit_check(struct vol *vol, struct path *path) {
262         int result = 0;
263         u_int16_t attr, flags = CONV_PRECOMPOSE;
264         struct finderinfo *finfo = NULL, finderinfo;
265         struct adouble *adp = NULL;
266         time_t c_date, b_date;
267         u_int32_t ac_date, ab_date;
268         static char convbuf[514]; /* for convert_charset dest_len parameter +2 */
269         size_t len;
270     int islnk;
271     islnk=S_ISLNK(path->st.st_mode);
272
273         if (S_ISDIR(path->st.st_mode)) {
274                 if (!c1.dbitmap)
275                         return 0;
276         }
277         else {
278                 if (!c1.fbitmap)
279                         return 0;
280
281                 /* compute the Mac name 
282                  * first try without id (it's slow to find it)
283                  * An other option would be to call get_id in utompath but 
284                  * we need to pass parent dir
285                 */
286         if (!(path->m_name = utompath(vol, path->u_name, 0 , utf8_encoding()) )) {
287                 /*retry with the right id */
288        
289                 cnid_t id;
290                 
291                 adp = adl_lkup(vol, path, adp);
292                 id = get_id(vol, adp, &path->st, path->d_dir->d_did, path->u_name, strlen(path->u_name));
293                 if (!id) {
294                         /* FIXME */
295                         return 0;
296                 }
297                 /* save the id for getfilparm */
298                 path->id = id;
299                 if (!(path->m_name = utompath(vol, path->u_name, id , utf8_encoding()))) {
300                         return 0;
301                 }
302         }
303         }
304                 
305         /* Kind of optimization: 
306          * -- first check things we've already have - filename
307          * -- last check things we get from ad_open()
308          * FIXME strmcp strstr (icase)
309          */
310
311         /* Check for filename */
312         if ((c1.rbitmap & (1<<DIRPBIT_LNAME))) { 
313                 if ( (size_t)(-1) == (len = convert_string(vol->v_maccharset, CH_UCS2, path->m_name, -1, convbuf, 512)) )
314                         goto crit_check_ret;
315
316                 if ((c1.rbitmap & (1<<CATPBIT_PARTIAL))) {
317                         if (strcasestr_w( (ucs2_t*) convbuf, (ucs2_t*) c1.lname) == NULL)
318                                 goto crit_check_ret;
319                 } else
320                         if (strcasecmp_w((ucs2_t*) convbuf, (ucs2_t*) c1.lname) != 0)
321                                 goto crit_check_ret;
322         } 
323         
324         if ((c1.rbitmap & (1<<FILPBIT_PDINFO))) { 
325                 if ( (size_t)(-1) == (len = convert_charset( CH_UTF8_MAC, CH_UCS2, CH_UTF8, path->m_name, strlen(path->m_name), convbuf, 512, &flags))) {
326                         goto crit_check_ret;
327                 }
328
329                 if (c1.rbitmap & (1<<CATPBIT_PARTIAL)) {
330                         if (strcasestr_w((ucs2_t *) convbuf, (ucs2_t*)c1.utf8name) == NULL)
331                                 goto crit_check_ret;
332                 } else
333                         if (strcasecmp_w((ucs2_t *)convbuf, (ucs2_t*)c1.utf8name) != 0)
334                                 goto crit_check_ret;
335         } 
336
337
338         /* FIXME */
339         if ((unsigned)c2.mdate > 0x7fffffff)
340                 c2.mdate = 0x7fffffff;
341         if ((unsigned)c2.cdate > 0x7fffffff)
342                 c2.cdate = 0x7fffffff;
343         if ((unsigned)c2.bdate > 0x7fffffff)
344                 c2.bdate = 0x7fffffff;
345
346         /* Check for modification date */
347         if ((c1.rbitmap & (1<<DIRPBIT_MDATE))) {
348                 if (path->st.st_mtime < c1.mdate || path->st.st_mtime > c2.mdate)
349                         goto crit_check_ret;
350         }
351         
352         /* Check for creation date... */
353         if ((c1.rbitmap & (1<<DIRPBIT_CDATE))) {
354                 c_date = path->st.st_mtime;
355                 adp = adl_lkup(vol, path, adp);
356                 if (adp && ad_getdate(adp, AD_DATE_CREATE, &ac_date) >= 0)
357                     c_date = AD_DATE_TO_UNIX(ac_date);
358
359                 if (c_date < c1.cdate || c_date > c2.cdate)
360                         goto crit_check_ret;
361         }
362
363         /* Check for backup date... */
364         if ((c1.rbitmap & (1<<DIRPBIT_BDATE))) {
365                 b_date = path->st.st_mtime;
366                 adp = adl_lkup(vol, path, adp);
367                 if (adp && ad_getdate(adp, AD_DATE_BACKUP, &ab_date) >= 0)
368                         b_date = AD_DATE_TO_UNIX(ab_date);
369
370                 if (b_date < c1.bdate || b_date > c2.bdate)
371                         goto crit_check_ret;
372         }
373                                 
374         /* Check attributes */
375         if ((c1.rbitmap & (1<<DIRPBIT_ATTR)) && c2.attr != 0) {
376                 if ((adp = adl_lkup(vol, path, adp))) {
377                         ad_getattr(adp, &attr);
378                         if ((attr & c2.attr) != c1.attr)
379                                 goto crit_check_ret;
380                 } else 
381                         goto crit_check_ret;
382         }               
383
384         /* Check file type ID */
385         if ((c1.rbitmap & (1<<DIRPBIT_FINFO)) && c2.finfo.f_type != 0) {
386             finfo = unpack_finderinfo(vol, path, &adp, &finderinfo,islnk);
387                 if (finfo->f_type != c1.finfo.f_type)
388                         goto crit_check_ret;
389         }
390         
391         /* Check creator ID */
392         if ((c1.rbitmap & (1<<DIRPBIT_FINFO)) && c2.finfo.creator != 0) {
393                 if (!finfo) {
394                         finfo = unpack_finderinfo(vol, path, &adp, &finderinfo,islnk);
395                 }
396                 if (finfo->creator != c1.finfo.creator)
397                         goto crit_check_ret;
398         }
399                 
400         /* Check finder info attributes */
401         if ((c1.rbitmap & (1<<DIRPBIT_FINFO)) && c2.finfo.attrs != 0) {
402                 if (!finfo) {
403                         finfo = unpack_finderinfo(vol, path, &adp, &finderinfo,islnk);
404                 }
405
406                 if ((finfo->attrs & c2.finfo.attrs) != c1.finfo.attrs)
407                         goto crit_check_ret;
408         }
409         
410         /* Check label */
411         if ((c1.rbitmap & (1<<DIRPBIT_FINFO)) && c2.finfo.label != 0) {
412                 if (!finfo) {
413                         finfo = unpack_finderinfo(vol, path, &adp, &finderinfo,islnk);
414                 }
415                 if ((finfo->label & c2.finfo.label) != c1.finfo.label)
416                         goto crit_check_ret;
417         }       
418         /* FIXME: Attributes check ! */
419         
420         /* All criteria are met. */
421         result |= 1;
422 crit_check_ret:
423         if (adp != NULL)
424                 ad_close_metadata(adp);
425         return result;
426 }  
427
428 /* ------------------------------ */
429 static int rslt_add ( struct vol *vol, struct path *path, char **buf, int ext)
430 {
431
432         char            *p = *buf;
433         int             ret;
434         size_t          tbuf =0;
435         u_int16_t       resultsize;
436         int             isdir = S_ISDIR(path->st.st_mode); 
437
438         /* Skip resultsize */
439         if (ext) {
440                 p += sizeof(resultsize); 
441         }
442         else {
443                 p++;
444         }
445         *p++ = isdir ? FILDIRBIT_ISDIR : FILDIRBIT_ISFILE;    /* IsDir ? */
446
447         if (ext) {
448                 *p++ = 0;                  /* Pad */
449         }
450         
451         if ( isdir ) {
452         ret = getdirparams(vol, c1.dbitmap, path, path->d_dir, p , &tbuf ); 
453         }
454         else {
455             /* FIXME slow if we need the file ID, we already know it, done ? */
456                 ret = getfilparams ( vol, c1.fbitmap, path, path->d_dir, p, &tbuf);
457         }
458
459         if ( ret != AFP_OK )
460                 return 0;
461
462         /* Make sure entry length is even */
463         if ((tbuf & 1)) {
464            *p++ = 0;
465            tbuf++;
466         }
467
468         if (ext) {
469                 resultsize = htons(tbuf);
470                 memcpy ( *buf, &resultsize, sizeof(resultsize) );
471                 *buf += tbuf + 4;
472         }
473         else {
474                 **buf = tbuf;
475                 *buf += tbuf + 2;
476         }
477
478         return 1;
479
480         
481 #define VETO_STR \
482         "./../.AppleDouble/.AppleDB/Network Trash Folder/TheVolumeSettingsFolder/TheFindByContentFolder/.AppleDesktop/.Parent/"
483
484 /*!
485  * This function performs a filesystem search
486  *
487  * Uses globals c1, c2, the search criteria
488  *
489  * @param vol       (r)  volume we are searching on ...
490  * @param dir       (rw) directory we are starting from ...
491  * @param rmatches  (r)  maximum number of matches we can return
492  * @param pos       (r)  position we've stopped recently
493  * @param rbuf      (w)  output buffer
494  * @param nrecs     (w)  number of matches
495  * @param rsize     (w)  length of data written to output buffer
496  * @param ext       (r)  extended search flag
497  */
498 #define NUM_ROUNDS 200
499 static int catsearch(struct vol *vol,
500                      struct dir *dir,  
501                      int rmatches,
502                      uint32_t *pos,
503                      char *rbuf,
504                      uint32_t *nrecs,
505                      int *rsize,
506                      int ext)
507 {
508     static u_int32_t cur_pos;    /* Saved position index (ID) - used to remember "position" across FPCatSearch calls */
509     static DIR *dirpos;                  /* UNIX structure describing currently opened directory. */
510     struct dir *currentdir;      /* struct dir of current directory */
511         int cidx, r;
512         struct dirent *entry;
513         int result = AFP_OK;
514         int ccr;
515     struct path path;
516         char *vpath = vol->v_path;
517         char *rrbuf = rbuf;
518     time_t start_time;
519     int num_rounds = NUM_ROUNDS;
520     int cwd = -1;
521     int error;
522         
523         if (*pos != 0 && *pos != cur_pos) {
524                 result = AFPERR_CATCHNG;
525                 goto catsearch_end;
526         }
527
528         /* FIXME: Category "offspring count ! */
529
530
531         /* We need to initialize all mandatory structures/variables and change working directory appropriate... */
532         if (*pos == 0) {
533                 clearstack();
534                 if (dirpos != NULL) {
535                         closedir(dirpos);
536                         dirpos = NULL;
537                 } 
538                 
539                 if (addstack(vpath, dir, -1) == -1) {
540                         result = AFPERR_MISC;
541                         goto catsearch_end;
542                 }
543                 /* FIXME: Sometimes DID is given by client ! (correct this one above !) */
544         }
545
546         /* Save current path */
547     if ((cwd = open(".", O_RDONLY)) < 0) {
548         result = AFPERR_MISC;
549         goto catsearch_end;
550     }
551         
552         /* So we are beginning... */
553     start_time = time(NULL);
554
555         while ((cidx = reducestack()) != -1) {
556         LOG(log_debug, logtype_afpd, "catsearch: dir: \"%s\"", dstack[cidx].path);
557
558                 error = lchdir(dstack[cidx].path);
559
560                 if (!error && dirpos == NULL)
561                         dirpos = opendir(".");
562
563                 if (dirpos == NULL)
564                         dirpos = opendir(dstack[cidx].path);
565
566                 if (error || dirpos == NULL) {
567                         switch (errno) {
568                         case EACCES:
569                                 dstack[cidx].checked = 1;
570                                 continue;
571                         case EMFILE:
572                         case ENFILE:
573                         case ENOENT:
574                                 result = AFPERR_NFILE;
575                                 break;
576                         case ENOMEM:
577                         case ENOTDIR:
578                         default:
579                                 result = AFPERR_MISC;
580                         } /* switch (errno) */
581                         goto catsearch_end;
582                 }
583
584         if ((currentdir = dirlookup_bypath(vol, dstack[cidx].path)) == NULL) {
585             result = AFPERR_MISC;
586             goto catsearch_end;
587         }
588         LOG(log_debug, logtype_afpd, "catsearch: current struct dir: \"%s\"", cfrombstr(currentdir->d_fullpath));
589                 
590                 while ((entry = readdir(dirpos)) != NULL) {
591                         (*pos)++;
592
593                         if (!check_dirent(vol, entry->d_name))
594                            continue;
595
596             LOG(log_debug, logtype_afpd, "catsearch(\"%s\"): dirent: \"%s\"",
597                 cfrombstr(currentdir->d_fullpath), entry->d_name);
598
599                         memset(&path, 0, sizeof(path));
600                         path.u_name = entry->d_name;
601                         if (of_stat(&path) != 0) {
602                                 switch (errno) {
603                                 case EACCES:
604                                 case ELOOP:
605                                 case ENOENT:
606                                         continue;
607                                 case ENOTDIR:
608                                 case EFAULT:
609                                 case ENOMEM:
610                                 case ENAMETOOLONG:
611                                 default:
612                                         result = AFPERR_MISC;
613                                         goto catsearch_end;
614                                 } 
615                         }
616                         if (S_ISDIR(path.st.st_mode)) {
617                                 /* here we can short cut 
618                                    ie if in the same loop the parent dir wasn't in the cache
619                                    ALL dirsearch_byname will fail.
620                                 */
621                 int unlen = strlen(path.u_name);
622                 path.d_dir = dircache_search_by_name(vol,
623                                                      currentdir,
624                                                      path.u_name,
625                                                      unlen);
626                 if (path.d_dir == NULL) {
627                         /* path.m_name is set by adddir */
628                     if ((path.d_dir = dir_add(vol,
629                                               currentdir,
630                                               &path,
631                                               unlen)) == NULL) {
632                                                 result = AFPERR_MISC;
633                                                 goto catsearch_end;
634                                         }
635                 }
636                 path.m_name = cfrombstr(path.d_dir->d_m_name);
637                         
638                                 if (addstack(path.u_name, path.d_dir, cidx) == -1) {
639                                         result = AFPERR_MISC;
640                                         goto catsearch_end;
641                                 } 
642             } else {
643                 path.d_dir = currentdir;
644             }
645
646                         ccr = crit_check(vol, &path);
647
648                         /* bit 0 means that criteria has been met */
649                         if ((ccr & 1)) {
650                                 r = rslt_add ( vol, &path, &rrbuf, ext);
651                                 
652                                 if (r == 0) {
653                                         result = AFPERR_MISC;
654                                         goto catsearch_end;
655                                 } 
656                                 *nrecs += r;
657                                 /* Number of matches limit */
658                                 if (--rmatches == 0) 
659                                         goto catsearch_pause;
660                                 /* Block size limit */
661                                 if (rrbuf - rbuf >= 448)
662                                         goto catsearch_pause;
663                         }
664                         /* MacOS 9 doesn't like servers executing commands longer than few seconds */
665                         if (--num_rounds <= 0) {
666                             if (start_time != time(NULL)) {
667                                         result=AFP_OK;
668                                         goto catsearch_pause;
669                             }
670                             num_rounds = NUM_ROUNDS;
671                         }
672                 } /* while ((entry=readdir(dirpos)) != NULL) */
673                 closedir(dirpos);
674                 dirpos = NULL;
675                 dstack[cidx].checked = 1;
676         } /* while (current_idx = reducestack()) != -1) */
677
678         /* We have finished traversing our tree. Return EOF here. */
679         result = AFPERR_EOF;
680         goto catsearch_end;
681
682 catsearch_pause:
683         cur_pos = *pos; 
684         save_cidx = cidx;
685
686 catsearch_end: /* Exiting catsearch: error condition */
687         *rsize = rrbuf - rbuf;
688     if (cwd != -1) {
689         if ((fchdir(cwd)) != 0) {
690             LOG(log_debug, logtype_afpd, "error chdiring back: %s", strerror(errno));        
691         }
692         close(cwd);
693     }
694         return result;
695 } /* catsearch() */
696
697 /*!
698  * This function performs a CNID db search
699  *
700  * Uses globals c1, c2, the search criteria
701  *
702  * @param vol       (r)  volume we are searching on ...
703  * @param dir       (rw) directory we are starting from ...
704  * @param uname     (r)  UNIX name of object to search
705  * @param rmatches  (r)  maximum number of matches we can return
706  * @param pos       (r)  position we've stopped recently
707  * @param rbuf      (w)  output buffer
708  * @param nrecs     (w)  number of matches
709  * @param rsize     (w)  length of data written to output buffer
710  * @param ext       (r)  extended search flag
711  */
712 static int catsearch_db(struct vol *vol,
713                         struct dir *dir,  
714                         const char *uname,
715                         int rmatches,
716                         uint32_t *pos,
717                         char *rbuf,
718                         uint32_t *nrecs,
719                         int *rsize,
720                         int ext)
721 {
722     static char resbuf[DBD_MAX_SRCH_RSLTS * sizeof(cnid_t)];
723     static uint32_t cur_pos;
724     static int num_matches;
725     int ccr ,r;
726         int result = AFP_OK;
727     struct path path;
728         char *rrbuf = rbuf;
729     char buffer[MAXPATHLEN +2];
730     uint16_t flags = CONV_TOLOWER;
731
732     LOG(log_debug, logtype_afpd, "catsearch_db(req pos: %u): {pos: %u, name: %s}",
733         *pos, cur_pos, uname);
734         
735         if (*pos != 0 && *pos != cur_pos) {
736                 result = AFPERR_CATCHNG;
737                 goto catsearch_end;
738         }
739
740     if (cur_pos == 0 || *pos == 0) {
741         if (convert_charset(vol->v_volcharset,
742                             vol->v_volcharset,
743                             vol->v_maccharset,
744                             uname,
745                             strlen(uname),
746                             buffer,
747                             MAXPATHLEN,
748                             &flags) == (size_t)-1) {
749             LOG(log_error, logtype_afpd, "catsearch_db: conversion error");
750             result = AFPERR_MISC;
751             goto catsearch_end;
752         }
753
754         LOG(log_debug, logtype_afpd, "catsearch_db: %s", buffer);
755
756         if ((num_matches = cnid_find(vol->v_cdb,
757                                      buffer,
758                                      strlen(uname),
759                                      resbuf,
760                                      sizeof(resbuf))) == -1) {
761             result = AFPERR_MISC;
762             goto catsearch_end;
763         }
764     }
765         
766         while (cur_pos < num_matches) {
767         char *name;
768         cnid_t cnid, did;
769         char resolvebuf[12 + MAXPATHLEN + 1];
770         struct dir *dir;
771
772         /* Next CNID to process from buffer */
773         memcpy(&cnid, resbuf + cur_pos * sizeof(cnid_t), sizeof(cnid_t));
774         did = cnid;
775
776         if ((name = cnid_resolve(vol->v_cdb, &did, resolvebuf, 12 + MAXPATHLEN + 1)) == NULL)
777             goto next;
778         LOG(log_debug, logtype_afpd, "catsearch_db: {pos: %u, name:%s, cnid: %u}",
779             cur_pos, name, ntohl(cnid));
780         if ((dir = dirlookup(vol, did)) == NULL)
781             goto next;
782         if (movecwd(vol, dir) < 0 )
783             goto next;
784
785         memset(&path, 0, sizeof(path));
786         path.u_name = name;
787         path.m_name = utompath(vol, name, cnid, utf8_encoding());
788
789         if (of_stat(&path) != 0) {
790             switch (errno) {
791             case EACCES:
792             case ELOOP:
793                 goto next;
794             case ENOENT:
795                 
796             default:
797                 result = AFPERR_MISC;
798                 goto catsearch_end;
799             } 
800         }
801         /* For files path.d_dir is the parent dir, for dirs its the dir itself */
802         if (S_ISDIR(path.st.st_mode))
803             if ((dir = dirlookup(vol, cnid)) == NULL)
804                 goto next;
805         path.d_dir = dir;
806
807         LOG(log_maxdebug, logtype_afpd,"catsearch_db: dir: %s, cwd: %s, name: %s", 
808             cfrombstr(dir->d_fullpath), getcwdpath(), path.u_name);
809
810         /* At last we can check the search criteria */
811         ccr = crit_check(vol, &path);
812         if ((ccr & 1)) {
813             LOG(log_debug, logtype_afpd,"catsearch_db: match: %s/%s",
814                 getcwdpath(), path.u_name);
815             /* bit 1 means that criteria has been met */
816             r = rslt_add(vol, &path, &rrbuf, ext);
817             if (r == 0) {
818                 result = AFPERR_MISC;
819                 goto catsearch_end;
820             } 
821             *nrecs += r;
822             /* Number of matches limit */
823             if (--rmatches == 0) 
824                 goto catsearch_pause;
825             /* Block size limit */
826             if (rrbuf - rbuf >= 448)
827                 goto catsearch_pause;
828         }
829     next:
830         cur_pos++;
831     } /* while */
832
833         /* finished */
834         result = AFPERR_EOF;
835     cur_pos = 0;
836         goto catsearch_end;
837
838 catsearch_pause:
839     *pos = cur_pos;
840
841 catsearch_end: /* Exiting catsearch: error condition */
842         *rsize = rrbuf - rbuf;
843     LOG(log_debug, logtype_afpd, "catsearch_db(req pos: %u): {pos: %u}", *pos, cur_pos);
844         return result;
845 }
846
847 /* -------------------------- */
848 static int catsearch_afp(AFPObj *obj _U_, char *ibuf, size_t ibuflen,
849                   char *rbuf, size_t *rbuflen, int ext)
850 {
851     struct vol *vol;
852     u_int16_t   vid;
853     u_int16_t   spec_len;
854     u_int32_t   rmatches, reserved;
855     u_int32_t   catpos[4];
856     u_int32_t   pdid = 0;
857     int ret, rsize;
858     u_int32_t nrecs = 0;
859     unsigned char *spec1, *spec2, *bspec1, *bspec2;
860     size_t      len;
861     u_int16_t   namelen;
862     u_int16_t   flags;
863     char            tmppath[256];
864     char        *uname;
865
866     *rbuflen = 0;
867
868     /* min header size */
869     if (ibuflen < 32) {
870         return AFPERR_PARAM;
871     }
872
873     memset(&c1, 0, sizeof(c1));
874     memset(&c2, 0, sizeof(c2));
875
876     ibuf += 2;
877     memcpy(&vid, ibuf, sizeof(vid));
878     ibuf += sizeof(vid);
879
880     if ((vol = getvolbyvid(vid)) == NULL) {
881         return AFPERR_PARAM;
882     }
883     
884     memcpy(&rmatches, ibuf, sizeof(rmatches));
885     rmatches = ntohl(rmatches);
886     ibuf += sizeof(rmatches); 
887
888     /* FIXME: (rl) should we check if reserved == 0 ? */
889     ibuf += sizeof(reserved);
890
891     memcpy(catpos, ibuf, sizeof(catpos));
892     ibuf += sizeof(catpos);
893
894     memcpy(&c1.fbitmap, ibuf, sizeof(c1.fbitmap));
895     c1.fbitmap = c2.fbitmap = ntohs(c1.fbitmap);
896     ibuf += sizeof(c1.fbitmap);
897
898     memcpy(&c1.dbitmap, ibuf, sizeof(c1.dbitmap));
899     c1.dbitmap = c2.dbitmap = ntohs(c1.dbitmap);
900     ibuf += sizeof(c1.dbitmap);
901
902     memcpy(&c1.rbitmap, ibuf, sizeof(c1.rbitmap));
903     c1.rbitmap = c2.rbitmap = ntohl(c1.rbitmap);
904     ibuf += sizeof(c1.rbitmap);
905
906     if (! (c1.fbitmap || c1.dbitmap)) {
907             return AFPERR_BITMAP;
908     }
909
910     if ( ext) {
911         memcpy(&spec_len, ibuf, sizeof(spec_len));
912         spec_len = ntohs(spec_len);
913     }
914     else {
915         /* with catsearch only name and parent id are allowed */
916         c1.fbitmap &= (1<<FILPBIT_LNAME) | (1<<FILPBIT_PDID);
917         c1.dbitmap &= (1<<DIRPBIT_LNAME) | (1<<DIRPBIT_PDID);
918         spec_len = *(unsigned char*)ibuf;
919     }
920
921     /* Parse file specifications */
922     spec1 = (unsigned char*)ibuf;
923     spec2 = (unsigned char*)ibuf + spec_len + 2;
924
925     spec1 += 2; 
926     spec2 += 2; 
927
928     bspec1 = spec1;
929     bspec2 = spec2;
930     /* File attribute bits... */
931     if (c1.rbitmap & (1 << FILPBIT_ATTR)) {
932             memcpy(&c1.attr, spec1, sizeof(c1.attr));
933             spec1 += sizeof(c1.attr);
934             memcpy(&c2.attr, spec2, sizeof(c2.attr));
935             spec2 += sizeof(c1.attr);
936     }
937
938     /* Parent DID */
939     if (c1.rbitmap & (1 << FILPBIT_PDID)) {
940             memcpy(&c1.pdid, spec1, sizeof(pdid));
941             spec1 += sizeof(c1.pdid);
942             memcpy(&c2.pdid, spec2, sizeof(pdid));
943             spec2 += sizeof(c2.pdid);
944     } /* FIXME: PDID - do we demarshall this argument ? */
945
946     /* Creation date */
947     if (c1.rbitmap & (1 << FILPBIT_CDATE)) {
948             memcpy(&c1.cdate, spec1, sizeof(c1.cdate));
949             spec1 += sizeof(c1.cdate);
950             c1.cdate = AD_DATE_TO_UNIX(c1.cdate);
951             memcpy(&c2.cdate, spec2, sizeof(c2.cdate));
952             spec2 += sizeof(c1.cdate);
953             ibuf += sizeof(c1.cdate);;
954             c2.cdate = AD_DATE_TO_UNIX(c2.cdate);
955     }
956
957     /* Modification date */
958     if (c1.rbitmap & (1 << FILPBIT_MDATE)) {
959             memcpy(&c1.mdate, spec1, sizeof(c1.mdate));
960             c1.mdate = AD_DATE_TO_UNIX(c1.mdate);
961             spec1 += sizeof(c1.mdate);
962             memcpy(&c2.mdate, spec2, sizeof(c2.mdate));
963             c2.mdate = AD_DATE_TO_UNIX(c2.mdate);
964             spec2 += sizeof(c1.mdate);
965     }
966     
967     /* Backup date */
968     if (c1.rbitmap & (1 << FILPBIT_BDATE)) {
969             memcpy(&c1.bdate, spec1, sizeof(c1.bdate));
970             spec1 += sizeof(c1.bdate);
971             c1.bdate = AD_DATE_TO_UNIX(c1.bdate);
972             memcpy(&c2.bdate, spec2, sizeof(c2.bdate));
973             spec2 += sizeof(c2.bdate);
974             c1.bdate = AD_DATE_TO_UNIX(c2.bdate);
975     }
976
977     /* Finder info */
978     if (c1.rbitmap & (1 << FILPBIT_FINFO)) {
979         packed_finder buf;
980         
981             memcpy(buf, spec1, sizeof(buf));
982             unpack_buffer(&c1.finfo, buf);      
983             spec1 += sizeof(buf);
984
985             memcpy(buf, spec2, sizeof(buf));
986             unpack_buffer(&c2.finfo, buf);
987             spec2 += sizeof(buf);
988     } /* Finder info */
989
990     if ((c1.rbitmap & (1 << DIRPBIT_OFFCNT)) != 0) {
991         /* Offspring count - only directories */
992                 if (c1.fbitmap == 0) {
993                 memcpy(&c1.offcnt, spec1, sizeof(c1.offcnt));
994                 spec1 += sizeof(c1.offcnt);
995                 c1.offcnt = ntohs(c1.offcnt);
996                 memcpy(&c2.offcnt, spec2, sizeof(c2.offcnt));
997                 spec2 += sizeof(c2.offcnt);
998                 c2.offcnt = ntohs(c2.offcnt);
999                 }
1000                 else if (c1.dbitmap == 0) {
1001                         /* ressource fork length */
1002                 }
1003                 else {
1004                 return AFPERR_BITMAP;  /* error */
1005                 }
1006     } /* Offspring count/ressource fork length */
1007
1008     /* Long name */
1009     if (c1.rbitmap & (1 << FILPBIT_LNAME)) {
1010         /* Get the long filename */     
1011                 memcpy(tmppath, bspec1 + spec1[1] + 1, (bspec1 + spec1[1])[0]);
1012                 tmppath[(bspec1 + spec1[1])[0]]= 0;
1013                 len = convert_string ( vol->v_maccharset, CH_UCS2, tmppath, -1, c1.lname, sizeof(c1.lname));
1014         if (len == (size_t)(-1))
1015             return AFPERR_PARAM;
1016
1017 #if 0   
1018                 /* FIXME: do we need it ? It's always null ! */
1019                 memcpy(c2.lname, bspec2 + spec2[1] + 1, (bspec2 + spec2[1])[0]);
1020                 c2.lname[(bspec2 + spec2[1])[0]]= 0;
1021 #endif
1022     }
1023         /* UTF8 Name */
1024     if (c1.rbitmap & (1 << FILPBIT_PDINFO)) {
1025
1026                 /* offset */
1027                 memcpy(&namelen, spec1, sizeof(namelen));
1028                 namelen = ntohs (namelen);
1029
1030                 spec1 = bspec1+namelen+4; /* Skip Unicode Hint */
1031
1032                 /* length */
1033                 memcpy(&namelen, spec1, sizeof(namelen));
1034                 namelen = ntohs (namelen);
1035                 if (namelen > UTF8FILELEN_EARLY)  /* Safeguard */
1036                         namelen = UTF8FILELEN_EARLY;
1037
1038                 memcpy (c1.utf8name, spec1+2, namelen);
1039                 c1.utf8name[namelen] = 0;
1040         if ((uname = mtoupath(vol, c1.utf8name, 0, utf8_encoding())) == NULL)
1041             return AFPERR_PARAM;
1042
1043                 /* convert charset */
1044                 flags = CONV_PRECOMPOSE;
1045                 len = convert_charset(CH_UTF8_MAC, CH_UCS2, CH_UTF8, c1.utf8name, namelen, c1.utf8name, 512, &flags);
1046         if (len == (size_t)(-1))
1047             return AFPERR_PARAM;
1048     }
1049     
1050     /* Call search */
1051     *rbuflen = 24;
1052     if ((c1.rbitmap & (1 << FILPBIT_PDINFO))
1053         && !(c1.rbitmap & (1<<CATPBIT_PARTIAL))
1054         && (strcmp(vol->v_cnidscheme, "dbd") == 0)
1055         && (vol->v_flags & AFPVOL_SEARCHDB))
1056         /* we've got a name and it's a dbd volume, so search CNID database */
1057         ret = catsearch_db(vol, vol->v_root, uname, rmatches, &catpos[0], rbuf+24, &nrecs, &rsize, ext);
1058     else
1059         /* perform a slow filesystem tree search */
1060         ret = catsearch(vol, vol->v_root, rmatches, &catpos[0], rbuf+24, &nrecs, &rsize, ext);
1061
1062     memcpy(rbuf, catpos, sizeof(catpos));
1063     rbuf += sizeof(catpos);
1064
1065     c1.fbitmap = htons(c1.fbitmap);
1066     memcpy(rbuf, &c1.fbitmap, sizeof(c1.fbitmap));
1067     rbuf += sizeof(c1.fbitmap);
1068
1069     c1.dbitmap = htons(c1.dbitmap);
1070     memcpy(rbuf, &c1.dbitmap, sizeof(c1.dbitmap));
1071     rbuf += sizeof(c1.dbitmap);
1072
1073     nrecs = htonl(nrecs);
1074     memcpy(rbuf, &nrecs, sizeof(nrecs));
1075     rbuf += sizeof(nrecs);
1076     *rbuflen += rsize;
1077
1078     return ret;
1079 } /* catsearch_afp */
1080
1081 /* -------------------------- */
1082 int afp_catsearch (AFPObj *obj, char *ibuf, size_t ibuflen,
1083                   char *rbuf, size_t *rbuflen)
1084 {
1085         return catsearch_afp( obj, ibuf, ibuflen, rbuf, rbuflen, 0);
1086 }
1087
1088
1089 int afp_catsearch_ext (AFPObj *obj, char *ibuf, size_t ibuflen,
1090                   char *rbuf, size_t *rbuflen)
1091 {
1092         return catsearch_afp( obj, ibuf, ibuflen, rbuf, rbuflen, 1);
1093 }
1094
1095 /* FIXME: we need a clean separation between afp stubs and 'real' implementation */
1096 /* (so, all buffer packing/unpacking should be done in stub, everything else 
1097    should be done in other functions) */