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