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