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