]> arthur.barton.de Git - netatalk.git/blob - etc/afpd/spotlight.c
Spotlight: enhance behaviour for long running queries
[netatalk.git] / etc / afpd / spotlight.c
1 /*
2   Copyright (c) 2012-2014 Ralph Boehme
3
4   This program is free software; you can redistribute it and/or modify
5   it under the terms of the GNU General Public License as published by
6   the Free Software Foundation; either version 2 of the License, or
7   (at your option) any later version.
8
9   This program is distributed in the hope that it will be useful,
10   but WITHOUT ANY WARRANTY; without even the implied warranty of
11   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12   GNU General Public License for more details.
13 */
14
15 #define USE_LIST
16
17 #ifdef HAVE_CONFIG_H
18 #include "config.h"
19 #endif /* HAVE_CONFIG_H */
20
21 #include <string.h>
22 #include <strings.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <errno.h>
26 #include <stdbool.h>
27 #include <inttypes.h>
28 #include <time.h>
29 #include <utime.h>
30
31 #include <atalk/list.h>
32 #include <atalk/errchk.h>
33 #include <atalk/util.h>
34 #include <atalk/logger.h>
35 #include <atalk/talloc.h>
36 #include <atalk/dalloc.h>
37 #include <atalk/byteorder.h>
38 #include <atalk/netatalk_conf.h>
39 #include <atalk/volume.h>
40 #include <atalk/spotlight.h>
41
42 #include "directory.h"
43 #include "etc/spotlight/sparql_parser.h"
44
45 #include <glib.h>
46
47 #define MAX_SL_RESULTS 20
48
49 struct slq_state_names {
50     slq_state_t state;
51     const char *state_name;
52 };
53
54 static struct slq_state_names slq_state_names[] = {
55     {SLQ_STATE_NEW, "SLQ_STATE_NEW"},
56     {SLQ_STATE_RUNNING, "SLQ_STATE_RUNNING"},
57     {SLQ_STATE_RESULTS, "SLQ_STATE_RESULTS"},
58     {SLQ_STATE_FULL, "SLQ_STATE_FULL"},
59     {SLQ_STATE_DONE, "SLQ_STATE_DONE"},
60     {SLQ_STATE_CANCEL_PENDING, "SLQ_STATE_CANCEL_PENDING"},
61     {SLQ_STATE_CANCELLED, "SLQ_STATE_CANCELLED"},
62     {SLQ_STATE_ERROR, "SLQ_STATE_ERROR"}
63 };
64
65
66 static char *tracker_to_unix_path(TALLOC_CTX *mem_ctx, const char *uri);
67 static int cnid_comp_fn(const void *p1, const void *p2);
68 static bool create_result_handle(slq_t *slq);
69 static bool add_filemeta(sl_array_t *reqinfo,
70                          sl_array_t *fm_array,
71                          const char *path,
72                          const struct stat *sp);
73
74 /************************************************
75  * Misc utility functions
76  ************************************************/
77
78 static char *tab_level(TALLOC_CTX *mem_ctx, int level)
79 {
80     int i;
81     char *string = talloc_array(mem_ctx, char, level + 1);
82
83     for (i = 0; i < level; i++) {
84         string[i] = '\t';
85     }
86
87     string[i] = '\0';
88     return string;
89 }
90
91 static char *dd_dump(DALLOC_CTX *dd, int nestinglevel)
92 {
93     const char *type;
94     int n;
95     uint64_t i;
96     sl_bool_t bl;
97     sl_time_t t;
98     struct tm *tm;
99     char datestring[256];
100     sl_cnids_t cnids;
101     char *logstring, *nested_logstring;
102     char *tab_string1, *tab_string2;
103
104     tab_string1 = tab_level(dd, nestinglevel);
105     tab_string2 = tab_level(dd, nestinglevel + 1);
106     if (tab_string1 == NULL || tab_string2 == NULL) {
107         return NULL;
108     }
109
110     logstring = talloc_asprintf(dd,
111                                 "%s%s(#%lu): {\n",
112                                 tab_string1,
113                                 talloc_get_name(dd),
114                                 talloc_array_length(dd->dd_talloc_array));
115
116     for (n = 0; n < talloc_array_length(dd->dd_talloc_array); n++) {
117         type = talloc_get_name(dd->dd_talloc_array[n]);
118         if (strequal(type, "DALLOC_CTX")
119             || strequal(type, "sl_array_t")
120             || strequal(type, "sl_filemeta_t")
121             || strequal(type, "sl_dict_t")) {
122             nested_logstring = dd_dump(dd->dd_talloc_array[n],
123                                        nestinglevel + 1);
124             if (!nested_logstring) {
125                 return NULL;
126             }
127             logstring = talloc_strdup_append(logstring,
128                                              nested_logstring);
129             if (!logstring) {
130                 return NULL;
131             }
132         } else if (strequal(type, "uint64_t")) {
133             memcpy(&i, dd->dd_talloc_array[n], sizeof(uint64_t));
134             logstring = talloc_asprintf_append(
135                 logstring,
136                 "%suint64_t: 0x%04" PRIx64 "\n",
137                 tab_string2, i);
138             if (!logstring) {
139                 return NULL;
140             }
141         } else if (strequal(type, "char *")) {
142             logstring = talloc_asprintf_append(
143                 logstring,
144                 "%sstring: %s\n",
145                 tab_string2,
146                 (char *)dd->dd_talloc_array[n]);
147             if (!logstring) {
148                 return NULL;
149             }
150         } else if (strequal(type, "smb_ucs2_t *")) {
151             logstring = talloc_asprintf_append(
152                 logstring,
153                 "%sUTF16-string: %s\n",
154                 tab_string2,
155                 (char *)dd->dd_talloc_array[n]);
156             if (!logstring) {
157                 return NULL;
158             }
159         } else if (strequal(type, "sl_bool_t")) {
160             memcpy(&bl, dd->dd_talloc_array[n], sizeof(sl_bool_t));
161             logstring = talloc_asprintf_append(
162                 logstring,
163                 "%sbool: %s\n",
164                 tab_string2,
165                 bl ? "true" : "false");
166             if (!logstring) {
167                 return NULL;
168             }
169         } else if (strequal(type, "sl_nil_t")) {
170             logstring = talloc_asprintf_append(
171                 logstring,
172                 "%snil\n",
173                 tab_string2);
174             if (!logstring) {
175                 return NULL;
176             }
177         } else if (strequal(type, "sl_time_t")) {
178             memcpy(&t, dd->dd_talloc_array[n], sizeof(sl_time_t));
179             tm = localtime(&t.tv_sec);
180             strftime(datestring,
181                      sizeof(datestring),
182                      "%Y-%m-%d %H:%M:%S", tm);
183             logstring = talloc_asprintf_append(
184                 logstring,
185                 "%ssl_time_t: %s.%06lu\n",
186                 tab_string2,
187                 datestring,
188                 (unsigned long)t.tv_usec);
189             if (!logstring) {
190                 return NULL;
191             }
192         } else if (strequal(type, "sl_cnids_t")) {
193             memcpy(&cnids, dd->dd_talloc_array[n], sizeof(sl_cnids_t));
194             logstring = talloc_asprintf_append(
195                 logstring,
196                 "%sCNIDs: unkn1: 0x%" PRIx16 ", unkn2: 0x%" PRIx32 "\n",
197                 tab_string2,
198                 cnids.ca_unkn1,
199                 cnids.ca_context);
200             if (!logstring) {
201                 return NULL;
202             }
203             if (cnids.ca_cnids) {
204                 nested_logstring = dd_dump(
205                     cnids.ca_cnids,
206                     nestinglevel + 2);
207                 if (!nested_logstring) {
208                     return NULL;
209                 }
210                 logstring = talloc_strdup_append(logstring,
211                                                  nested_logstring);
212                 if (!logstring) {
213                     return NULL;
214                 }
215             }
216         } else {
217             logstring = talloc_asprintf_append(
218                 logstring,
219                 "%stype: %s\n",
220                 tab_string2,
221                 type);
222             if (!logstring) {
223                 return NULL;
224             }
225         }
226     }
227     logstring = talloc_asprintf_append(logstring,
228                                        "%s}\n",
229                                        tab_string1);
230     if (!logstring) {
231         return NULL;
232     }
233     return logstring;
234 }
235
236 static int cnid_comp_fn(const void *p1, const void *p2)
237 {
238     const uint64_t *cnid1 = p1, *cnid2 = p2;
239     if (*cnid1 == *cnid2) {
240         return 0;
241     }
242     if (*cnid1 < *cnid2) {
243         return -1;
244     }
245     return 1;
246 }
247
248 static int sl_createCNIDArray(slq_t *slq, const DALLOC_CTX *p)
249 {
250     EC_INIT;
251     uint64_t *cnids = NULL;
252
253     EC_NULL( cnids = talloc_array(slq, uint64_t, talloc_array_length(p)) );
254
255     for (int i = 0; i < talloc_array_length(p); i++) {
256         memcpy(&cnids[i], p->dd_talloc_array[i], sizeof(uint64_t));
257     }
258     qsort(cnids, talloc_array_length(p), sizeof(uint64_t), cnid_comp_fn);
259
260     slq->slq_cnids = cnids;
261     slq->slq_cnids_num = talloc_array_length(p);
262
263 EC_CLEANUP:
264     if (ret != 0) {
265         if (cnids)
266             talloc_free(cnids);
267     }
268     EC_EXIT;
269 }
270
271 static char *tracker_to_unix_path(TALLOC_CTX *mem_ctx, const char *uri)
272 {
273     GFile *f;
274     char *path;
275     char *talloc_path = NULL;
276
277     f = g_file_new_for_uri(uri);
278     if (!f) {
279         return NULL;
280     }
281
282     path = g_file_get_path(f);
283     g_object_unref(f);
284
285     if (!path) {
286         return NULL;
287     }
288
289     talloc_path = talloc_strdup(mem_ctx, path);
290     g_free(path);
291
292     return talloc_path;
293 }
294
295 /**
296  * Add requested metadata for a query result element
297  *
298  * This could be rewritten to something more sophisticated like
299  * querying metadata from Tracker.
300  *
301  * If path or sp is NULL, simply add nil values for all attributes.
302  **/
303 static bool add_filemeta(sl_array_t *reqinfo,
304                          sl_array_t *fm_array,
305                          const char *path,
306                          const struct stat *sp)
307 {
308     sl_array_t *meta;
309     sl_nil_t nil;
310     int i, metacount;
311     uint64_t uint64var;
312     sl_time_t sl_time;
313     char *p, *name;
314
315     metacount = talloc_array_length(reqinfo->dd_talloc_array);
316     if (metacount == 0 || path == NULL || sp == NULL) {
317         dalloc_add_copy(fm_array, &nil, sl_nil_t);
318         return true;
319     }
320
321     meta = talloc_zero(fm_array, sl_array_t);
322
323     for (i = 0; i < metacount; i++) {
324         if (strequal(reqinfo->dd_talloc_array[i], "kMDItemDisplayName")
325             || strequal(reqinfo->dd_talloc_array[i], "kMDItemFSName")) {
326             if ((p = strrchr(path, '/'))) {
327                 name = dalloc_strdup(meta, p + 1);
328                 dalloc_add(meta, name, "char *");
329             }
330         } else if (strequal(reqinfo->dd_talloc_array[i],
331                             "kMDItemPath")) {
332             name = dalloc_strdup(meta, path);
333             dalloc_add(meta, name, "char *");
334         } else if (strequal(reqinfo->dd_talloc_array[i],
335                             "kMDItemFSSize")) {
336             uint64var = sp->st_size;
337             dalloc_add_copy(meta, &uint64var, uint64_t);
338         } else if (strequal(reqinfo->dd_talloc_array[i],
339                             "kMDItemFSOwnerUserID")) {
340             uint64var = sp->st_uid;
341             dalloc_add_copy(meta, &uint64var, uint64_t);
342         } else if (strequal(reqinfo->dd_talloc_array[i],
343                             "kMDItemFSOwnerGroupID")) {
344             uint64var = sp->st_gid;
345             dalloc_add_copy(meta, &uint64var, uint64_t);
346         } else if (strequal(reqinfo->dd_talloc_array[i],
347                             "kMDItemFSContentChangeDate")) {
348             sl_time.tv_sec = sp->st_mtime;
349             dalloc_add_copy(meta, &sl_time, sl_time_t);
350         } else {
351             dalloc_add_copy(meta, &nil, sl_nil_t);
352         }
353     }
354
355     dalloc_add(fm_array, meta, sl_array_t);
356     return true;
357 }
358
359 /**
360  * Allocate result handle used in the async Tracker cursor result
361  * handler for storing results
362  **/
363 static bool create_result_handle(slq_t *slq)
364 {
365     sl_nil_t nil = 0;
366     struct sl_rslts *query_results;
367
368     if (slq->query_results) {
369         LOG(log_error, logtype_sl,"unexpected existing result handle");
370         return false;
371     }
372
373     query_results = talloc_zero(slq, struct sl_rslts);
374
375     /* CNIDs */
376     query_results->cnids = talloc_zero(query_results, sl_cnids_t);
377     if (query_results->cnids == NULL) {
378         return false;
379     }
380     query_results->cnids->ca_cnids = talloc_zero(query_results->cnids,
381                                                  DALLOC_CTX);
382     if (query_results->cnids->ca_cnids == NULL) {
383         return false;
384     }
385
386     query_results->cnids->ca_unkn1 = 0xadd;
387     query_results->cnids->ca_context = slq->slq_ctx2;
388
389     /* FileMeta */
390     query_results->fm_array = talloc_zero(query_results, sl_array_t);
391     if (query_results->fm_array == NULL) {
392         return false;
393     }
394
395     /* For some reason the list of results always starts with a nil entry */
396     dalloc_add_copy(query_results->fm_array, &nil, sl_nil_t);
397
398     slq->query_results = query_results;
399     return true;
400 }
401
402 static bool add_results(sl_array_t *array, slq_t *slq)
403 {
404     sl_filemeta_t *fm;
405     uint64_t status;
406
407     /* FileMeta */
408     fm = talloc_zero(array, sl_filemeta_t);
409     if (!fm) {
410         return false;
411     }
412
413     switch (slq->slq_state) {
414     case SLQ_STATE_RUNNING:
415         /*
416          * Wtf, why 35? Taken from an AFP capture.
417          */
418         status = 35;
419         break;
420
421     default:
422         status = 0;
423         break;
424     }
425
426     dalloc_add_copy(array, &status, uint64_t);
427     dalloc_add(array, slq->query_results->cnids, sl_cnids_t);
428     if (slq->query_results->num_results > 0) {
429         dalloc_add(fm, slq->query_results->fm_array, sl_array_t);
430     }
431     dalloc_add(array, fm, sl_filemeta_t);
432
433     /* This ensure the results get clean up after been sent to the client */
434     talloc_steal(array, slq->query_results);
435     slq->query_results = NULL;
436
437     if (!create_result_handle(slq)) {
438         LOG(log_error, logtype_sl, "couldn't add result handle");
439         slq->slq_state = SLQ_STATE_ERROR;
440         return false;
441     }
442
443     return true;
444 }
445
446 /******************************************************************************
447  * Spotlight queries
448  ******************************************************************************/
449
450 static ATALK_LIST_HEAD(sl_queries);
451 static ATALK_LIST_HEAD(sl_cancelled_queries);
452
453 /**
454  * Add a query to the list of active queries
455  **/
456 static void slq_add(slq_t *slq)
457 {
458     list_add(&(slq->slq_list), &sl_queries);
459 }
460
461 /**
462  * Add a query to the list of active queries
463  **/
464 static void slq_cancelled_add(slq_t *slq)
465 {
466     list_add(&(slq->slq_list), &sl_cancelled_queries);
467 }
468
469 /**
470  * Remove a query from the active list
471  **/
472 static void slq_remove(slq_t *slq)
473 {
474     struct list_head *p;
475     slq_t *q = NULL;
476
477     list_for_each(p, &sl_queries) {
478         q = list_entry(p, slq_t, slq_list);
479         if ((q->slq_ctx1 == slq->slq_ctx1) && (q->slq_ctx2 == slq->slq_ctx2)) {
480             list_del(p);
481             break;
482         }
483     }
484
485     return;
486 }
487
488 static slq_t *slq_for_ctx(uint64_t ctx1, uint64_t ctx2)
489 {
490     slq_t *q = NULL;
491     struct list_head *p;
492
493     list_for_each(p, &sl_queries) {
494         q = list_entry(p, slq_t, slq_list);
495         if ((q->slq_ctx1 == ctx1) && (q->slq_ctx2 == ctx2)) {
496             break;
497         }
498         q = NULL;
499     }
500
501     return q;
502 }
503
504 /**
505  * Remove a query from the active queue and free it
506  **/
507 static void slq_destroy(slq_t *slq)
508 {
509     if (slq == NULL) {
510         return;
511     }
512     slq_remove(slq);
513     talloc_free(slq);
514 }
515
516 /**
517  * Cancel a query
518  **/
519 static void slq_cancel(slq_t *slq)
520 {
521     slq->slq_state = SLQ_STATE_CANCEL_PENDING;
522     slq_remove(slq);
523     slq_cancelled_add(slq);
524 }
525
526 /**
527  * talloc destructor cb
528  **/
529 static int slq_free_cb(slq_t *slq)
530 {
531     if (slq->tracker_cursor) {
532         g_object_unref(slq->tracker_cursor);
533     }
534     return 0;
535 }
536
537 /**
538  * Free all cancelled queries
539  **/
540 static void slq_cancelled_cleanup(void)
541 {
542     struct list_head *p;
543     slq_t *q = NULL;
544
545     list_for_each(p, &sl_cancelled_queries) {
546         q = list_entry(p, slq_t, slq_list);
547         if (q->slq_state == SLQ_STATE_CANCELLED) {
548             LOG(log_debug, logtype_sl,
549                 "ctx1: %" PRIx64 ", ctx2: %" PRIx64 ": cancelled",
550                 q->slq_ctx1, q->slq_ctx2);
551             list_del(p);
552             talloc_free(q);
553         } else {
554             LOG(log_debug, logtype_sl,
555                 "ctx1: %" PRIx64 ", ctx2: %" PRIx64 ": %s",
556                 q->slq_ctx1, q->slq_ctx2, slq_state_names[q->slq_state].state_name);
557         }
558     }
559
560     return;
561 }
562
563 static void slq_dump(void)
564 {
565     struct list_head *p;
566     slq_t *q = NULL;
567     int i = 0;
568
569     list_for_each(p, &sl_queries) {
570         q = list_entry(p, slq_t, slq_list);
571         LOG(log_debug, logtype_sl,
572             "query[%d]: ctx1: %" PRIx64 ", ctx2: %" PRIx64 ", state: %s",
573             i++, q->slq_ctx1, q->slq_ctx2,
574             slq_state_names[q->slq_state].state_name);
575     }
576
577     return;
578 }
579
580 /************************************************
581  * Tracker async callbacks
582  ************************************************/
583
584 static void tracker_con_cb(GObject      *object,
585                            GAsyncResult *res,
586                            gpointer      user_data)
587 {
588     struct sl_ctx *sl_ctx = user_data;
589     GError *error = NULL;
590
591     sl_ctx->tracker_con = tracker_sparql_connection_get_finish(res,
592                                                                &error);
593     if (error) {
594         LOG(log_error, logtype_sl, "Could not connect to Tracker: %s",
595             error->message);
596         sl_ctx->tracker_con = NULL;
597         g_error_free(error);
598         return;
599     }
600
601     LOG(log_info, logtype_sl, "connected to Tracker");
602 }
603
604 static void tracker_cursor_cb(GObject      *object,
605                               GAsyncResult *res,
606                               gpointer      user_data)
607 {
608     GError *error = NULL;
609     slq_t *slq = user_data;
610     gboolean more_results;
611     const gchar *uri;
612     char *path;
613     int result;
614     struct stat sb;
615     uint64_t uint64var;
616     bool ok;
617     cnid_t did, id;
618
619     LOG(log_debug, logtype_sl,
620         "cursor cb[%d]: ctx1: %" PRIx64 ", ctx2: %" PRIx64,
621         slq->query_results->num_results, slq->slq_ctx1, slq->slq_ctx2);
622
623     more_results = tracker_sparql_cursor_next_finish(slq->tracker_cursor,
624                                                      res,
625                                                      &error);
626
627     if (slq->slq_state == SLQ_STATE_CANCEL_PENDING) {
628         LOG(log_debug, logtype_sl,
629             "cursor cb: ctx1: %" PRIx64 ", ctx2: %" PRIx64 ": cancelled",
630             slq->slq_ctx1, slq->slq_ctx2);
631         slq->slq_state = SLQ_STATE_CANCELLED;
632         return;
633     }
634
635     if (error) {
636         LOG(log_error, logtype_sl, "Tracker cursor: %s", error->message);
637         g_error_free(error);
638         slq->slq_state = SLQ_STATE_ERROR;
639         return;
640     }
641
642     if (!more_results) {
643         LOG(log_debug, logtype_sl, "tracker_cursor_cb: done");
644         slq->slq_state = SLQ_STATE_DONE;
645         return;
646     }
647
648     uri = tracker_sparql_cursor_get_string(slq->tracker_cursor, 0, NULL);
649     if (uri == NULL) {
650         /*
651          * Not sure how this could happen if
652          * tracker_sparql_cursor_next_finish() returns true, but I've
653          * seen it.
654          */
655         LOG(log_debug, logtype_sl, "no URI for result");
656         return;
657     }
658
659     LOG(log_debug, logtype_sl, "URI: %s", uri);
660
661     path = tracker_to_unix_path(slq->query_results, uri);
662     if (path == NULL) {
663         LOG(log_error, logtype_sl, "error converting Tracker URI: %s", uri);
664         slq->slq_state = SLQ_STATE_ERROR;
665         return;
666     }
667
668     result = access(path, R_OK);
669     if (result != 0) {
670         goto exit;
671     }
672
673     id = cnid_for_path(slq->slq_vol->v_cdb, slq->slq_vol->v_path, path, &did);
674     if (id == CNID_INVALID) {
675         LOG(log_error, logtype_sl, "cnid_for_path error: %s", path);
676         goto exit;
677     }
678     uint64var = ntohl(id);
679
680     if (slq->slq_cnids) {
681         ok = bsearch(&uint64var, slq->slq_cnids, slq->slq_cnids_num,
682                      sizeof(uint64_t), cnid_comp_fn);
683         if (!ok) {
684             goto exit;
685         }
686     }
687
688     dalloc_add_copy(slq->query_results->cnids->ca_cnids,
689                     &uint64var, uint64_t);
690     ok = add_filemeta(slq->slq_reqinfo, slq->query_results->fm_array,
691                       path, &sb);
692     if (!ok) {
693         LOG(log_error, logtype_sl, "add_filemeta error");
694         slq->slq_state = SLQ_STATE_ERROR;
695         return;
696     }
697
698     slq->query_results->num_results++;
699
700 exit:
701     if (slq->query_results->num_results < MAX_SL_RESULTS) {
702         LOG(log_debug, logtype_sl,
703             "cursor cb[%d]: ctx1: %" PRIx64 ", ctx2: %" PRIx64 ": requesting more results",
704             slq->query_results->num_results - 1, slq->slq_ctx1, slq->slq_ctx2);
705
706         slq->slq_state = SLQ_STATE_RESULTS;
707
708         tracker_sparql_cursor_next_async(slq->tracker_cursor,
709                                          slq->slq_obj->sl_ctx->cancellable,
710                                          tracker_cursor_cb,
711                                          slq);
712     } else {
713         LOG(log_debug, logtype_sl,
714             "cursor cb[%d]: ctx1: %" PRIx64 ", ctx2: %" PRIx64 ": full",
715             slq->query_results->num_results - 1, slq->slq_ctx1, slq->slq_ctx2);
716
717         slq->slq_state = SLQ_STATE_FULL;
718     }
719 }
720
721 static void tracker_query_cb(GObject      *object,
722                              GAsyncResult *res,
723                              gpointer      user_data)
724 {
725     GError *error = NULL;
726     slq_t *slq = user_data;
727
728     LOG(log_debug, logtype_sl,
729         "query cb: ctx1: %" PRIx64 ", ctx2: %" PRIx64,
730         slq->slq_ctx1, slq->slq_ctx2);
731
732     slq->tracker_cursor = tracker_sparql_connection_query_finish(
733         TRACKER_SPARQL_CONNECTION(object),
734         res,
735         &error);
736
737     if (slq->slq_state == SLQ_STATE_CANCEL_PENDING) {
738         slq->slq_state = SLQ_STATE_CANCELLED;
739         return;
740     }
741
742     if (error) {
743         slq->slq_state = SLQ_STATE_ERROR;
744         LOG(log_error, logtype_sl, "Tracker query error: %s", error->message);
745         g_error_free(error);
746         return;
747     }
748
749     slq->slq_state = SLQ_STATE_RESULTS;
750
751     tracker_sparql_cursor_next_async(slq->tracker_cursor,
752                                      slq->slq_obj->sl_ctx->cancellable,
753                                      tracker_cursor_cb,
754                                      slq);
755 }
756
757 /*******************************************************************************
758  * Spotlight RPC functions
759  ******************************************************************************/
760
761 static int sl_rpc_fetchPropertiesForContext(const AFPObj *obj,
762                                             const DALLOC_CTX *query,
763                                             DALLOC_CTX *reply,
764                                             const struct vol *v)
765 {
766     EC_INIT;
767
768     char *s;
769     sl_dict_t *dict;
770     sl_array_t *array;
771     sl_uuid_t uuid;
772
773     if (!v->v_uuid) {
774         EC_FAIL_LOG("missing UUID for volume: %s", v->v_localname);
775     }
776     dict = talloc_zero(reply, sl_dict_t);
777
778     /* key/val 1 */
779     s = dalloc_strdup(dict, "kMDSStoreMetaScopes");
780     dalloc_add(dict, s, char *);
781
782     array = talloc_zero(dict, sl_array_t);
783     s = dalloc_strdup(array, "kMDQueryScopeComputer");
784     dalloc_add(array, s, char *);
785     dalloc_add(dict, array, sl_array_t);
786
787     /* key/val 2 */
788     s = dalloc_strdup(dict, "kMDSStorePathScopes");
789     dalloc_add(dict, s, char *);
790
791     array = talloc_zero(dict, sl_array_t);
792     s = dalloc_strdup(array, v->v_path);
793     dalloc_add(array, s, char *);
794     dalloc_add(dict, array, sl_array_t);
795
796     /* key/val 3 */
797     s = dalloc_strdup(dict, "kMDSStoreUUID");
798     dalloc_add(dict, s, char *);
799
800     memcpy(uuid.sl_uuid, v->v_uuid, 16);
801     dalloc_add_copy(dict, &uuid, sl_uuid_t);
802
803     /* key/val 4 */
804     s = dalloc_strdup(dict, "kMDSStoreHasPersistentUUID");
805     dalloc_add(dict, s, char *);
806     sl_bool_t b = true;
807     dalloc_add_copy(dict, &b, sl_bool_t);
808
809     dalloc_add(reply, dict, sl_dict_t);
810
811 EC_CLEANUP:
812     EC_EXIT;
813 }
814
815 static int sl_rpc_openQuery(AFPObj *obj,
816                             const DALLOC_CTX *query,
817                             DALLOC_CTX *reply,
818                             struct vol *v)
819 {
820     EC_INIT;
821     char *sl_query;
822     uint64_t *uint64;
823     DALLOC_CTX *reqinfo;
824     sl_array_t *array;
825     sl_cnids_t *cnids;
826     slq_t *slq;
827     char slq_host[MAXPATHLEN + 1];
828     uint16_t convflags = v->v_mtou_flags;
829     uint64_t result;
830     gchar *sparql_query;
831     GError *error = NULL;
832     bool ok;
833
834     array = talloc_zero(reply, sl_array_t);
835
836     if (obj->sl_ctx->tracker_con == NULL) {
837         LOG(log_error, logtype_sl, "no tracker connection");
838         EC_FAIL;
839     }
840
841     /* Allocate and initialize query object */
842     slq = talloc_zero(obj->sl_ctx, slq_t);
843     slq->slq_state = SLQ_STATE_NEW;
844     slq->slq_obj = obj;
845     slq->slq_vol = v;
846     slq->slq_allow_expr = obj->options.flags & OPTION_SPOTLIGHT_EXPR ? true : false;
847     slq->slq_result_limit = obj->options.sparql_limit;
848     talloc_set_destructor(slq, slq_free_cb);
849
850     LOG(log_debug, logtype_sl, "Spotlight: expr: %s, limit: %" PRIu64,
851         slq->slq_allow_expr ? "yes" : "no", slq->slq_result_limit);
852
853     /* convert spotlight query charset to host charset */
854     sl_query = dalloc_value_for_key(query, "DALLOC_CTX", 0,
855                                     "DALLOC_CTX", 1,
856                                     "kMDQueryString");
857     if (sl_query == NULL) {
858         EC_FAIL;
859     }
860     ret = convert_charset(CH_UTF8_MAC, v->v_volcharset, v->v_maccharset,
861                           sl_query, strlen(sl_query), slq_host, MAXPATHLEN,
862                           &convflags);
863     if (ret == -1) {
864         LOG(log_error, logtype_sl, "charset conversion failed");
865         EC_FAIL;
866     }
867     slq->slq_qstring = talloc_strdup(slq, slq_host);
868     LOG(log_debug, logtype_sl, "Spotlight query: \"%s\"", slq->slq_qstring);
869
870     slq->slq_time = time(NULL);
871     uint64 = dalloc_get(query, "DALLOC_CTX", 0, "DALLOC_CTX", 0, "uint64_t", 1);
872     if (uint64 == NULL) {
873         EC_FAIL;
874     }
875     slq->slq_ctx1 = *uint64;
876
877     uint64 = dalloc_get(query, "DALLOC_CTX", 0, "DALLOC_CTX", 0, "uint64_t", 2);
878     if (uint64 == NULL) {
879         EC_FAIL;
880     }
881     slq->slq_ctx2 = *uint64;
882
883     reqinfo = dalloc_value_for_key(query, "DALLOC_CTX", 0, "DALLOC_CTX", 1,
884                                    "kMDAttributeArray");
885     if (reqinfo == NULL) {
886         EC_FAIL;
887     }
888     slq->slq_reqinfo = talloc_steal(slq, reqinfo);
889
890     cnids = dalloc_value_for_key(query, "DALLOC_CTX", 0, "DALLOC_CTX", 1,
891                                  "kMDQueryItemArray");
892     if (cnids) {
893         EC_ZERO_LOG( sl_createCNIDArray(slq, cnids->ca_cnids) );
894     }
895
896     ret = map_spotlight_to_sparql_query(slq, &sparql_query);
897     if (ret != 0) {
898         LOG(log_debug, logtype_sl, "mapping retured non-zero");
899         EC_FAIL;
900     }
901     LOG(log_debug, logtype_sl, "SPARQL query: \"%s\"", sparql_query);
902
903     tracker_sparql_connection_query_async(obj->sl_ctx->tracker_con,
904                                           sparql_query,
905                                           slq->slq_obj->sl_ctx->cancellable,
906                                           tracker_query_cb,
907                                           slq);
908     if (error) {
909         LOG(log_error, logtype_sl, "Couldn't query the Tracker Store: '%s'",
910             error->message);
911         g_clear_error(&error);
912         EC_FAIL;
913     }
914
915     slq->slq_state = SLQ_STATE_RUNNING;
916
917     ok = create_result_handle(slq);
918     if (!ok) {
919         LOG(log_error, logtype_sl, "create_result_handle error");
920         slq->slq_state = SLQ_STATE_ERROR;
921         EC_FAIL;
922     }
923
924     slq_add(slq);
925
926 EC_CLEANUP:
927     if (ret != 0) {
928         slq_destroy(slq);
929         result = UINT64_MAX;
930         ret = 0;
931     } else {
932         result = 0;
933     }
934
935     dalloc_add_copy(array, &result, uint64_t);
936     dalloc_add(reply, array, sl_array_t);
937     EC_EXIT;
938 }
939
940 static int sl_rpc_fetchQueryResultsForContext(const AFPObj *obj,
941                                               const DALLOC_CTX *query,
942                                               DALLOC_CTX *reply,
943                                               const struct vol *v)
944 {
945     EC_INIT;
946     slq_t *slq = NULL;
947     uint64_t *uint64, ctx1, ctx2, status;
948     sl_array_t *array;
949     bool ok;
950
951     array = talloc_zero(reply, sl_array_t);
952     if (array == NULL) {
953         return false;
954     }
955
956     /* Context */
957     uint64 = dalloc_get(query, "DALLOC_CTX", 0, "DALLOC_CTX", 0, "uint64_t", 1);
958     if (uint64 == NULL) {
959         EC_FAIL;
960     }
961     ctx1 = *uint64;
962     uint64 = dalloc_get(query, "DALLOC_CTX", 0, "DALLOC_CTX", 0, "uint64_t", 2);
963     if (uint64 == NULL) {
964         EC_FAIL;
965     }
966     ctx2 = *uint64;
967
968     /* Get query for context */
969     slq = slq_for_ctx(ctx1, ctx2);
970     if (slq == NULL) {
971         EC_FAIL;
972     }
973
974     switch (slq->slq_state) {
975     case SLQ_STATE_RUNNING:
976     case SLQ_STATE_RESULTS:
977     case SLQ_STATE_FULL:
978     case SLQ_STATE_DONE:
979         ok = add_results(array, slq);
980         if (!ok) {
981             LOG(log_error, logtype_sl, "error adding results");
982             EC_FAIL;
983         }
984         if (slq->slq_state == SLQ_STATE_FULL) {
985             slq->slq_state = SLQ_STATE_RESULTS;
986
987             tracker_sparql_cursor_next_async(
988                 slq->tracker_cursor,
989                 slq->slq_obj->sl_ctx->cancellable,
990                 tracker_cursor_cb,
991                 slq);
992         }
993         break;
994
995     case SLQ_STATE_ERROR:
996         LOG(log_error, logtype_sl, "query in error state");
997         EC_FAIL;
998
999     default:
1000         LOG(log_error, logtype_sl, "unexpected query state %d", slq->slq_state);
1001         EC_FAIL;
1002     }
1003
1004     dalloc_add(reply, array, sl_array_t);
1005     EC_EXIT;
1006
1007 EC_CLEANUP:
1008     slq_destroy(slq);
1009     status = UINT64_MAX;
1010     dalloc_add_copy(array, &status, uint64_t);
1011     dalloc_add(reply, array, sl_array_t);
1012     EC_EXIT;
1013 }
1014
1015 static int sl_rpc_storeAttributesForOIDArray(const AFPObj *obj,
1016                                              const DALLOC_CTX *query,
1017                                              DALLOC_CTX *reply,
1018                                              const struct vol *vol)
1019 {
1020     EC_INIT;
1021     uint64_t uint64;
1022     sl_array_t *array;
1023     sl_cnids_t *cnids;
1024     sl_time_t *sl_time;
1025     cnid_t id;
1026     char *path;
1027     struct dir *dir;
1028
1029     EC_NULL_LOG( cnids = dalloc_get(query, "DALLOC_CTX", 0, "sl_cnids_t", 2) );
1030     memcpy(&uint64, cnids->ca_cnids->dd_talloc_array[0], sizeof(uint64_t));
1031     id = (cnid_t)uint64;
1032     LOG(log_debug, logtype_sl, "CNID: %" PRIu32, id);
1033
1034     if (htonl(id) == DIRDID_ROOT) {
1035         path = vol->v_path;
1036     } else if (id < CNID_START) {
1037         EC_FAIL;
1038     } else {
1039         cnid_t did;
1040         char buffer[12 + MAXPATHLEN + 1];
1041
1042         did = htonl(id);
1043         EC_NULL_LOG( path = cnid_resolve(vol->v_cdb, &did, buffer, sizeof(buffer)) );
1044         EC_NULL_LOG( dir = dirlookup(vol, did) );
1045         EC_NEG1_LOG( movecwd(vol, dir) );
1046     }
1047
1048     /*
1049      * We're possibly supposed to update attributes in two places: the
1050      * database and the filesystem.  Due to the lack of documentation
1051      * and not yet implemented database updates, we cherry pick attributes
1052      * that seems to be candidates for updating filesystem metadata.
1053      */
1054
1055     if ((sl_time = dalloc_value_for_key(query, "DALLOC_CTX", 0, "DALLOC_CTX", 1, "DALLOC_CTX", 1, "kMDItemFSContentChangeDate"))) {
1056         struct utimbuf utimes;
1057         utimes.actime = utimes.modtime = sl_time->tv_sec;
1058         utime(path, &utimes);
1059     }
1060
1061     array = talloc_zero(reply, sl_array_t);
1062     uint64_t sl_res = 0;
1063     dalloc_add_copy(array, &sl_res, uint64_t);
1064     dalloc_add(reply, array, sl_array_t);
1065
1066 EC_CLEANUP:
1067     EC_EXIT;
1068 }
1069
1070 static int sl_rpc_fetchAttributeNamesForOIDArray(const AFPObj *obj, const DALLOC_CTX *query, DALLOC_CTX *reply, const struct vol *vol)
1071 {
1072     EC_INIT;
1073     uint64_t uint64;
1074     sl_cnids_t *cnids;
1075     cnid_t id;
1076     char *path;
1077     struct dir *dir;
1078
1079     EC_NULL_LOG( cnids = dalloc_get(query, "DALLOC_CTX", 0, "sl_cnids_t", 1) );
1080     memcpy(&uint64, cnids->ca_cnids->dd_talloc_array[0], sizeof(uint64_t));
1081     id = (cnid_t)uint64;
1082     LOG(log_debug, logtype_sl, "sl_rpc_fetchAttributeNamesForOIDArray: CNID: %" PRIu32, id);
1083
1084     if (htonl(id) == DIRDID_ROOT) {
1085         path = vol->v_path;
1086     } else if (id < CNID_START) {
1087         EC_FAIL;
1088     } else {
1089         cnid_t did;
1090         char buffer[12 + MAXPATHLEN + 1];
1091
1092         did = htonl(id);
1093         EC_NULL_LOG( path = cnid_resolve(vol->v_cdb, &did, buffer, sizeof(buffer)) );
1094         EC_NULL_LOG( dir = dirlookup(vol, did) );
1095         EC_NEG1_LOG( movecwd(vol, dir) );
1096     }
1097
1098     /* Result array */
1099     sl_array_t *array = talloc_zero(reply, sl_array_t);
1100     dalloc_add(reply, array, sl_array_t);
1101
1102     /* Return result value 0 */
1103     uint64_t sl_res = 0;
1104     dalloc_add_copy(array, &sl_res, uint64_t);
1105
1106     /* Return CNID array */
1107     sl_cnids_t *replycnids = talloc_zero(reply, sl_cnids_t);
1108     replycnids->ca_cnids = talloc_zero(cnids, DALLOC_CTX);
1109     replycnids->ca_unkn1 = 0xfec;
1110     replycnids->ca_context = cnids->ca_context;
1111     uint64 = (uint64_t)id;
1112     dalloc_add_copy(replycnids->ca_cnids, &uint64, uint64_t);
1113     dalloc_add(array, replycnids, sl_cnids_t);
1114
1115     /* Return filemeta array */
1116
1117     /*
1118      * FIXME: this should return the real attributes from all known metadata sources
1119      * (Tracker and filesystem)
1120      */
1121     sl_array_t *mdattrs = talloc_zero(reply, sl_array_t);
1122     dalloc_add(mdattrs, dalloc_strdup(mdattrs, "kMDItemFSName"), "char *");
1123     dalloc_add(mdattrs, dalloc_strdup(mdattrs, "kMDItemDisplayName"), "char *");
1124     dalloc_add(mdattrs, dalloc_strdup(mdattrs, "kMDItemFSSize"), "char *");
1125     dalloc_add(mdattrs, dalloc_strdup(mdattrs, "kMDItemFSOwnerUserID"), "char *");
1126     dalloc_add(mdattrs, dalloc_strdup(mdattrs, "kMDItemFSOwnerGroupID"), "char *");
1127     dalloc_add(mdattrs, dalloc_strdup(mdattrs, "kMDItemFSContentChangeDate"), "char *");
1128
1129     sl_filemeta_t *fmeta = talloc_zero(reply, sl_filemeta_t);
1130     dalloc_add(fmeta, mdattrs, sl_array_t);
1131     dalloc_add(array, fmeta, sl_filemeta_t);
1132
1133 EC_CLEANUP:
1134     EC_EXIT;
1135 }
1136
1137 static int sl_rpc_fetchAttributesForOIDArray(AFPObj *obj, const DALLOC_CTX *query, DALLOC_CTX *reply, const struct vol *vol)
1138 {
1139     EC_INIT;
1140     uint64_t uint64;
1141     sl_cnids_t *cnids, *replycnids;
1142     cnid_t id, did;
1143     struct dir *dir;
1144     sl_array_t *array, *reqinfo, *fm_array;
1145     char buffer[12 + MAXPATHLEN + 1];
1146     char *name, *path;
1147     sl_filemeta_t *fm;
1148     sl_nil_t nil;
1149     uint64_t sl_res;
1150     struct stat sb;
1151
1152     array = talloc_zero(reply, sl_array_t);
1153     replycnids = talloc_zero(reply, sl_cnids_t);
1154     replycnids->ca_cnids = talloc_zero(replycnids, DALLOC_CTX);
1155     fm = talloc_zero(array, sl_filemeta_t);
1156     fm_array = talloc_zero(fm, sl_array_t);
1157
1158     if (array == NULL || replycnids == NULL || replycnids->ca_cnids == NULL
1159         || fm == NULL || fm_array == NULL) {
1160         EC_FAIL;
1161     }
1162
1163     reqinfo = dalloc_get(query, "DALLOC_CTX", 0, "sl_array_t", 1);
1164     if (reqinfo == NULL) {
1165         EC_FAIL;
1166     }
1167     cnids = dalloc_get(query, "DALLOC_CTX", 0, "sl_cnids_t", 2);
1168     if (cnids == NULL) {
1169         EC_FAIL;
1170     }
1171
1172     memcpy(&uint64, cnids->ca_cnids->dd_talloc_array[0], sizeof(uint64_t));
1173     id = (cnid_t)uint64;
1174
1175     if (htonl(id) == DIRDID_ROOT) {
1176         path = talloc_strdup(reply, vol->v_path);
1177     } else if (id < CNID_START) {
1178         EC_FAIL;
1179     } else {
1180         did = htonl(id);
1181         EC_NULL( name = cnid_resolve(vol->v_cdb, &did, buffer, sizeof(buffer)) );
1182         EC_NULL( dir = dirlookup(vol, did) );
1183         EC_NULL( path = talloc_asprintf(reply, "%s/%s", bdata(dir->d_fullpath), name) );
1184     }
1185
1186     EC_ZERO( stat(path, &sb) );
1187
1188     sl_res = 0;
1189     dalloc_add_copy(array, &sl_res, uint64_t);
1190
1191     replycnids->ca_unkn1 = 0xfec;
1192     replycnids->ca_context = cnids->ca_context;
1193     uint64 = (uint64_t)id;
1194     dalloc_add_copy(replycnids->ca_cnids, &uint64, uint64_t);
1195     dalloc_add(array, replycnids, sl_cnids_t);
1196     dalloc_add(fm, fm_array, fm_array_t);
1197     dalloc_add_copy(fm_array, &nil, sl_nil_t);
1198     add_filemeta(reqinfo, fm_array, path, &sb);
1199
1200     /* Now add result */
1201     dalloc_add(array, fm, sl_filemeta_t);
1202     dalloc_add(reply, array, sl_array_t);
1203     EC_EXIT;
1204
1205 EC_CLEANUP:
1206     sl_res = UINT64_MAX;
1207     dalloc_add_copy(array, &sl_res, uint64_t);
1208     dalloc_add(array, fm, sl_filemeta_t);
1209     dalloc_add(reply, array, sl_array_t);
1210     EC_EXIT;
1211 }
1212
1213 static int sl_rpc_closeQueryForContext(const AFPObj *obj,
1214                                        const DALLOC_CTX *query,
1215                                        DALLOC_CTX *reply,
1216                                        const struct vol *v)
1217 {
1218     EC_INIT;
1219     slq_t *slq = NULL;
1220     uint64_t *uint64, ctx1, ctx2;
1221     sl_array_t *array;
1222     uint64_t sl_result;
1223
1224     array = talloc_zero(reply, sl_array_t);
1225
1226     /* Context */
1227     uint64 = dalloc_get(query, "DALLOC_CTX", 0, "DALLOC_CTX", 0, "uint64_t", 1);
1228     if (uint64 == NULL) {
1229         EC_FAIL;
1230     }
1231     ctx1 = *uint64;
1232     uint64 = dalloc_get(query, "DALLOC_CTX", 0, "DALLOC_CTX", 0, "uint64_t", 2);
1233     if (uint64 == NULL) {
1234         EC_FAIL;
1235     }
1236     ctx2 = *uint64;
1237
1238     /* Get query for context and free it */
1239     slq = slq_for_ctx(ctx1, ctx2);
1240     if (slq == NULL) {
1241         EC_FAIL;
1242     }
1243
1244     switch (slq->slq_state) {
1245     case SLQ_STATE_FULL:
1246     case SLQ_STATE_DONE:
1247     case SLQ_STATE_ERROR:
1248         LOG(log_debug, logtype_sl, "close: destroying query: state %s",
1249             slq_state_names[slq->slq_state].state_name);
1250         slq_destroy(slq);
1251         break;
1252
1253     case SLQ_STATE_RUNNING:
1254     case SLQ_STATE_RESULTS:
1255         LOG(log_debug, logtype_sl, "close: cancel query: state %s",
1256             slq_state_names[slq->slq_state].state_name);
1257         slq_cancel(slq);
1258         break;
1259
1260     default:
1261         LOG(log_error, logtype_sl, "Unexpected state %d", slq->slq_state);
1262         EC_FAIL;
1263     }
1264
1265     sl_result = 0;
1266
1267 EC_CLEANUP:
1268     if (ret != 0) {
1269         sl_result = UINT64_MAX;
1270     }
1271     dalloc_add_copy(array, &sl_result, uint64_t);
1272     dalloc_add(reply, array, sl_array_t);
1273     EC_EXIT;
1274 }
1275
1276 /******************************************************************************
1277  * Spotlight functions
1278  ******************************************************************************/
1279
1280 int spotlight_init(AFPObj *obj)
1281 {
1282     static bool initialized = false;
1283     const char *attributes;
1284     struct sl_ctx *sl_ctx;
1285
1286     if (initialized) {
1287         return 0;
1288     }
1289
1290     LOG(log_info, logtype_sl, "Initializing Spotlight");
1291
1292     sl_ctx = talloc_zero(NULL, struct sl_ctx);
1293     obj->sl_ctx = sl_ctx;
1294
1295     attributes = atalk_iniparser_getstring(obj->iniconfig, INISEC_GLOBAL,
1296                                            "spotlight attributes", NULL);
1297     if (attributes) {
1298         configure_spotlight_attributes(attributes);
1299     }
1300
1301     /*
1302      * Tracker uses glibs event dispatching, so we need a mainloop
1303      */
1304 #if ((GLIB_MAJOR_VERSION <= 2) && (GLIB_MINOR_VERSION < 36))
1305         g_type_init();
1306 #endif
1307     sl_ctx->mainloop = g_main_loop_new(NULL, false);
1308     sl_ctx->cancellable = g_cancellable_new();
1309
1310     setenv("DBUS_SESSION_BUS_ADDRESS", "unix:path=" _PATH_STATEDIR "spotlight.ipc", 1);
1311     setenv("XDG_DATA_HOME", _PATH_STATEDIR, 0);
1312     setenv("XDG_CACHE_HOME", _PATH_STATEDIR, 0);
1313     setenv("TRACKER_USE_LOG_FILES", "1", 0);
1314
1315     tracker_sparql_connection_get_async(sl_ctx->cancellable,
1316                                         tracker_con_cb, sl_ctx);
1317
1318     initialized = true;
1319     return 0;
1320 }
1321
1322 /******************************************************************************
1323  * AFP functions
1324  ******************************************************************************/
1325
1326 int afp_spotlight_rpc(AFPObj *obj, char *ibuf, size_t ibuflen,
1327                       char *rbuf, size_t *rbuflen)
1328 {
1329     EC_INIT;
1330     TALLOC_CTX *tmp_ctx = talloc_new(NULL);
1331     uint16_t vid;
1332     int cmd;
1333     struct vol      *vol;
1334     DALLOC_CTX *query;
1335     DALLOC_CTX *reply;
1336     char *rpccmd;
1337     int len;
1338     bool event;
1339
1340     *rbuflen = 0;
1341
1342     if (!(obj->options.flags & OPTION_SPOTLIGHT)) {
1343         return AFPERR_NOOP;
1344     }
1345
1346     spotlight_init(obj);
1347     slq_dump();
1348
1349     /*
1350      * Process finished glib events
1351      */
1352     event = true;
1353     while (event) {
1354         event = g_main_context_iteration(NULL, false);
1355     }
1356     slq_cancelled_cleanup();
1357
1358     ibuf += 2;
1359     ibuflen -= 2;
1360
1361     vid = SVAL(ibuf, 0);
1362     LOG(log_debug, logtype_sl, "afp_spotlight_rpc(vid: %" PRIu16 ")", vid);
1363
1364     if ((vol = getvolbyvid(vid)) == NULL) {
1365         LOG(log_error, logtype_sl, "afp_spotlight_rpc: bad volume id: %" PRIu16 ")", vid);
1366         ret = AFPERR_ACCESS;
1367         goto EC_CLEANUP;
1368     }
1369
1370     /*    IVAL(ibuf, 2): unknown, always 0x00008004, some flags ? */
1371
1372     cmd = RIVAL(ibuf, 6);
1373     LOG(log_debug, logtype_sl, "afp_spotlight_rpc(cmd: %d)", cmd);
1374
1375     /*    IVAL(ibuf, 10: unknown, always 0x00000000 */
1376
1377     switch (cmd) {
1378
1379     case SPOTLIGHT_CMD_OPEN:
1380     case SPOTLIGHT_CMD_OPEN2:
1381         RSIVAL(rbuf, 0, ntohs(vid));
1382         RSIVAL(rbuf, 4, 0);
1383         len = strlen(vol->v_path) + 1;
1384         strncpy(rbuf + 8, vol->v_path, len);
1385         *rbuflen += 8 + len;
1386         break;
1387
1388     case SPOTLIGHT_CMD_FLAGS:
1389         RSIVAL(rbuf, 0, 0x0100006b); /* Whatever this value means... flags? Helios uses 0x1eefface */
1390         *rbuflen += 4;
1391         break;
1392
1393     case SPOTLIGHT_CMD_RPC:
1394         EC_NULL( query = talloc_zero(tmp_ctx, DALLOC_CTX) );
1395         EC_NULL( reply = talloc_zero(tmp_ctx, DALLOC_CTX) );
1396         EC_NEG1_LOG( sl_unpack(query, ibuf + 22) );
1397
1398         LOG(log_debug, logtype_sl, "Spotlight RPC request:\n%s",
1399             dd_dump(query, 0));
1400
1401         EC_NULL_LOG( rpccmd = dalloc_get(query, "DALLOC_CTX", 0, "DALLOC_CTX", 0, "char *", 0) );
1402
1403         if (STRCMP(rpccmd, ==, "fetchPropertiesForContext:")) {
1404             EC_ZERO_LOG( sl_rpc_fetchPropertiesForContext(obj, query, reply, vol) );
1405         } else if (STRCMP(rpccmd, ==, "openQueryWithParams:forContext:")) {
1406             EC_ZERO_LOG( sl_rpc_openQuery(obj, query, reply, vol) );
1407         } else if (STRCMP(rpccmd, ==, "fetchQueryResultsForContext:")) {
1408             EC_ZERO_LOG( sl_rpc_fetchQueryResultsForContext(obj, query, reply, vol) );
1409         } else if (STRCMP(rpccmd, ==, "storeAttributes:forOIDArray:context:")) {
1410             EC_ZERO_LOG( sl_rpc_storeAttributesForOIDArray(obj, query, reply, vol) );
1411         } else if (STRCMP(rpccmd, ==, "fetchAttributeNamesForOIDArray:context:")) {
1412             EC_ZERO_LOG( sl_rpc_fetchAttributeNamesForOIDArray(obj, query, reply, vol) );
1413         } else if (STRCMP(rpccmd, ==, "fetchAttributes:forOIDArray:context:")) {
1414             EC_ZERO_LOG( sl_rpc_fetchAttributesForOIDArray(obj, query, reply, vol) );
1415         } else if (STRCMP(rpccmd, ==, "closeQueryForContext:")) {
1416             EC_ZERO_LOG( sl_rpc_closeQueryForContext(obj, query, reply, vol) );
1417         } else {
1418             LOG(log_error, logtype_sl, "afp_spotlight_rpc: unknown Spotlight RPC: %s", rpccmd);
1419         }
1420
1421         LOG(log_debug, logtype_sl, "Spotlight RPC reply dump:\n%s",
1422             dd_dump(reply, 0));
1423
1424         memset(rbuf, 0, 4);
1425         *rbuflen += 4;
1426
1427         EC_NEG1_LOG( len = sl_pack(reply, rbuf + 4) );
1428         *rbuflen += len;
1429         break;
1430     }
1431
1432 EC_CLEANUP:
1433     talloc_free(tmp_ctx);
1434     if (ret != AFP_OK) {
1435         *rbuflen = 0;
1436         return AFPERR_MISC;
1437     }
1438     EC_EXIT;
1439 }