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