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