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