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