]> arthur.barton.de Git - netatalk.git/blob - etc/afpd/spotlight.c
Spotlight: Limiting searches to subfolders, bug #581
[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     sl_array_t *scope_array;
834
835     array = talloc_zero(reply, sl_array_t);
836
837     if (obj->sl_ctx->tracker_con == NULL) {
838         LOG(log_error, logtype_sl, "no tracker connection");
839         EC_FAIL;
840     }
841
842     /* Allocate and initialize query object */
843     slq = talloc_zero(obj->sl_ctx, slq_t);
844     slq->slq_state = SLQ_STATE_NEW;
845     slq->slq_obj = obj;
846     slq->slq_vol = v;
847     slq->slq_allow_expr = obj->options.flags & OPTION_SPOTLIGHT_EXPR ? true : false;
848     slq->slq_result_limit = obj->options.sparql_limit;
849     talloc_set_destructor(slq, slq_free_cb);
850
851     LOG(log_debug, logtype_sl, "Spotlight: expr: %s, limit: %" PRIu64,
852         slq->slq_allow_expr ? "yes" : "no", slq->slq_result_limit);
853
854     /* convert spotlight query charset to host charset */
855     sl_query = dalloc_value_for_key(query, "DALLOC_CTX", 0,
856                                     "DALLOC_CTX", 1,
857                                     "kMDQueryString");
858     if (sl_query == NULL) {
859         EC_FAIL;
860     }
861     ret = convert_charset(CH_UTF8_MAC, v->v_volcharset, v->v_maccharset,
862                           sl_query, strlen(sl_query), slq_host, MAXPATHLEN,
863                           &convflags);
864     if (ret == -1) {
865         LOG(log_error, logtype_sl, "charset conversion failed");
866         EC_FAIL;
867     }
868     slq->slq_qstring = talloc_strdup(slq, slq_host);
869     LOG(log_debug, logtype_sl, "Spotlight query: \"%s\"", slq->slq_qstring);
870
871     slq->slq_time = time(NULL);
872     uint64 = dalloc_get(query, "DALLOC_CTX", 0, "DALLOC_CTX", 0, "uint64_t", 1);
873     if (uint64 == NULL) {
874         EC_FAIL;
875     }
876     slq->slq_ctx1 = *uint64;
877
878     uint64 = dalloc_get(query, "DALLOC_CTX", 0, "DALLOC_CTX", 0, "uint64_t", 2);
879     if (uint64 == NULL) {
880         EC_FAIL;
881     }
882     slq->slq_ctx2 = *uint64;
883
884     reqinfo = dalloc_value_for_key(query, "DALLOC_CTX", 0, "DALLOC_CTX", 1,
885                                    "kMDAttributeArray");
886     if (reqinfo == NULL) {
887         EC_FAIL;
888     }
889     slq->slq_reqinfo = talloc_steal(slq, reqinfo);
890
891     scope_array = dalloc_value_for_key(query, "DALLOC_CTX", 0, "DALLOC_CTX", 1,
892                                        "kMDScopeArray");
893     if (scope_array == NULL) {
894         slq->slq_scope = talloc_strdup(slq, v->v_path);
895     } else {
896         slq->slq_scope = talloc_strdup(slq, scope_array->dd_talloc_array[0]);
897     }
898     if (slq->slq_scope == NULL) {
899         LOG(log_error, logtype_sl, "failed to setup search scope");
900         EC_FAIL;
901     }
902
903     LOG(log_debug, logtype_sl, "Search scope: \"%s\"", slq->slq_scope);
904
905     cnids = dalloc_value_for_key(query, "DALLOC_CTX", 0, "DALLOC_CTX", 1,
906                                  "kMDQueryItemArray");
907     if (cnids) {
908         EC_ZERO_LOG( sl_createCNIDArray(slq, cnids->ca_cnids) );
909     }
910
911     ret = map_spotlight_to_sparql_query(slq, &sparql_query);
912     if (ret != 0) {
913         LOG(log_debug, logtype_sl, "mapping retured non-zero");
914         EC_FAIL;
915     }
916     LOG(log_debug, logtype_sl, "SPARQL query: \"%s\"", sparql_query);
917
918     tracker_sparql_connection_query_async(obj->sl_ctx->tracker_con,
919                                           sparql_query,
920                                           slq->slq_obj->sl_ctx->cancellable,
921                                           tracker_query_cb,
922                                           slq);
923     if (error) {
924         LOG(log_error, logtype_sl, "Couldn't query the Tracker Store: '%s'",
925             error->message);
926         g_clear_error(&error);
927         EC_FAIL;
928     }
929
930     slq->slq_state = SLQ_STATE_RUNNING;
931
932     ok = create_result_handle(slq);
933     if (!ok) {
934         LOG(log_error, logtype_sl, "create_result_handle error");
935         slq->slq_state = SLQ_STATE_ERROR;
936         EC_FAIL;
937     }
938
939     slq_add(slq);
940
941 EC_CLEANUP:
942     if (ret != 0) {
943         slq_destroy(slq);
944         result = UINT64_MAX;
945         ret = 0;
946     } else {
947         result = 0;
948     }
949
950     dalloc_add_copy(array, &result, uint64_t);
951     dalloc_add(reply, array, sl_array_t);
952     EC_EXIT;
953 }
954
955 static int sl_rpc_fetchQueryResultsForContext(const AFPObj *obj,
956                                               const DALLOC_CTX *query,
957                                               DALLOC_CTX *reply,
958                                               const struct vol *v)
959 {
960     EC_INIT;
961     slq_t *slq = NULL;
962     uint64_t *uint64, ctx1, ctx2, status;
963     sl_array_t *array;
964     bool ok;
965
966     array = talloc_zero(reply, sl_array_t);
967     if (array == NULL) {
968         return false;
969     }
970
971     /* Context */
972     uint64 = dalloc_get(query, "DALLOC_CTX", 0, "DALLOC_CTX", 0, "uint64_t", 1);
973     if (uint64 == NULL) {
974         EC_FAIL;
975     }
976     ctx1 = *uint64;
977     uint64 = dalloc_get(query, "DALLOC_CTX", 0, "DALLOC_CTX", 0, "uint64_t", 2);
978     if (uint64 == NULL) {
979         EC_FAIL;
980     }
981     ctx2 = *uint64;
982
983     /* Get query for context */
984     slq = slq_for_ctx(ctx1, ctx2);
985     if (slq == NULL) {
986         EC_FAIL;
987     }
988
989     switch (slq->slq_state) {
990     case SLQ_STATE_RUNNING:
991     case SLQ_STATE_RESULTS:
992     case SLQ_STATE_FULL:
993     case SLQ_STATE_DONE:
994         ok = add_results(array, slq);
995         if (!ok) {
996             LOG(log_error, logtype_sl, "error adding results");
997             EC_FAIL;
998         }
999         if (slq->slq_state == SLQ_STATE_FULL) {
1000             slq->slq_state = SLQ_STATE_RESULTS;
1001
1002             tracker_sparql_cursor_next_async(
1003                 slq->tracker_cursor,
1004                 slq->slq_obj->sl_ctx->cancellable,
1005                 tracker_cursor_cb,
1006                 slq);
1007         }
1008         break;
1009
1010     case SLQ_STATE_ERROR:
1011         LOG(log_error, logtype_sl, "query in error state");
1012         EC_FAIL;
1013
1014     default:
1015         LOG(log_error, logtype_sl, "unexpected query state %d", slq->slq_state);
1016         EC_FAIL;
1017     }
1018
1019     dalloc_add(reply, array, sl_array_t);
1020     EC_EXIT;
1021
1022 EC_CLEANUP:
1023     slq_destroy(slq);
1024     status = UINT64_MAX;
1025     dalloc_add_copy(array, &status, uint64_t);
1026     dalloc_add(reply, array, sl_array_t);
1027     EC_EXIT;
1028 }
1029
1030 static int sl_rpc_storeAttributesForOIDArray(const AFPObj *obj,
1031                                              const DALLOC_CTX *query,
1032                                              DALLOC_CTX *reply,
1033                                              const struct vol *vol)
1034 {
1035     EC_INIT;
1036     uint64_t uint64;
1037     sl_array_t *array;
1038     sl_cnids_t *cnids;
1039     sl_time_t *sl_time;
1040     cnid_t id;
1041     char *path;
1042     struct dir *dir;
1043
1044     EC_NULL_LOG( cnids = dalloc_get(query, "DALLOC_CTX", 0, "sl_cnids_t", 2) );
1045     memcpy(&uint64, cnids->ca_cnids->dd_talloc_array[0], sizeof(uint64_t));
1046     id = (cnid_t)uint64;
1047     LOG(log_debug, logtype_sl, "CNID: %" PRIu32, id);
1048
1049     if (htonl(id) == DIRDID_ROOT) {
1050         path = vol->v_path;
1051     } else if (id < CNID_START) {
1052         EC_FAIL;
1053     } else {
1054         cnid_t did;
1055         char buffer[12 + MAXPATHLEN + 1];
1056
1057         did = htonl(id);
1058         EC_NULL_LOG( path = cnid_resolve(vol->v_cdb, &did, buffer, sizeof(buffer)) );
1059         EC_NULL_LOG( dir = dirlookup(vol, did) );
1060         EC_NEG1_LOG( movecwd(vol, dir) );
1061     }
1062
1063     /*
1064      * We're possibly supposed to update attributes in two places: the
1065      * database and the filesystem.  Due to the lack of documentation
1066      * and not yet implemented database updates, we cherry pick attributes
1067      * that seems to be candidates for updating filesystem metadata.
1068      */
1069
1070     if ((sl_time = dalloc_value_for_key(query, "DALLOC_CTX", 0, "DALLOC_CTX", 1, "DALLOC_CTX", 1, "kMDItemFSContentChangeDate"))) {
1071         struct utimbuf utimes;
1072         utimes.actime = utimes.modtime = sl_time->tv_sec;
1073         utime(path, &utimes);
1074     }
1075
1076     array = talloc_zero(reply, sl_array_t);
1077     uint64_t sl_res = 0;
1078     dalloc_add_copy(array, &sl_res, uint64_t);
1079     dalloc_add(reply, array, sl_array_t);
1080
1081 EC_CLEANUP:
1082     EC_EXIT;
1083 }
1084
1085 static int sl_rpc_fetchAttributeNamesForOIDArray(const AFPObj *obj, const DALLOC_CTX *query, DALLOC_CTX *reply, const struct vol *vol)
1086 {
1087     EC_INIT;
1088     uint64_t uint64;
1089     sl_cnids_t *cnids;
1090     cnid_t id;
1091     char *path;
1092     struct dir *dir;
1093
1094     EC_NULL_LOG( cnids = dalloc_get(query, "DALLOC_CTX", 0, "sl_cnids_t", 1) );
1095     memcpy(&uint64, cnids->ca_cnids->dd_talloc_array[0], sizeof(uint64_t));
1096     id = (cnid_t)uint64;
1097     LOG(log_debug, logtype_sl, "sl_rpc_fetchAttributeNamesForOIDArray: CNID: %" PRIu32, id);
1098
1099     if (htonl(id) == DIRDID_ROOT) {
1100         path = vol->v_path;
1101     } else if (id < CNID_START) {
1102         EC_FAIL;
1103     } else {
1104         cnid_t did;
1105         char buffer[12 + MAXPATHLEN + 1];
1106
1107         did = htonl(id);
1108         EC_NULL_LOG( path = cnid_resolve(vol->v_cdb, &did, buffer, sizeof(buffer)) );
1109         EC_NULL_LOG( dir = dirlookup(vol, did) );
1110         EC_NEG1_LOG( movecwd(vol, dir) );
1111     }
1112
1113     /* Result array */
1114     sl_array_t *array = talloc_zero(reply, sl_array_t);
1115     dalloc_add(reply, array, sl_array_t);
1116
1117     /* Return result value 0 */
1118     uint64_t sl_res = 0;
1119     dalloc_add_copy(array, &sl_res, uint64_t);
1120
1121     /* Return CNID array */
1122     sl_cnids_t *replycnids = talloc_zero(reply, sl_cnids_t);
1123     replycnids->ca_cnids = talloc_zero(cnids, DALLOC_CTX);
1124     replycnids->ca_unkn1 = 0xfec;
1125     replycnids->ca_context = cnids->ca_context;
1126     uint64 = (uint64_t)id;
1127     dalloc_add_copy(replycnids->ca_cnids, &uint64, uint64_t);
1128     dalloc_add(array, replycnids, sl_cnids_t);
1129
1130     /* Return filemeta array */
1131
1132     /*
1133      * FIXME: this should return the real attributes from all known metadata sources
1134      * (Tracker and filesystem)
1135      */
1136     sl_array_t *mdattrs = talloc_zero(reply, sl_array_t);
1137     dalloc_add(mdattrs, dalloc_strdup(mdattrs, "kMDItemFSName"), "char *");
1138     dalloc_add(mdattrs, dalloc_strdup(mdattrs, "kMDItemDisplayName"), "char *");
1139     dalloc_add(mdattrs, dalloc_strdup(mdattrs, "kMDItemFSSize"), "char *");
1140     dalloc_add(mdattrs, dalloc_strdup(mdattrs, "kMDItemFSOwnerUserID"), "char *");
1141     dalloc_add(mdattrs, dalloc_strdup(mdattrs, "kMDItemFSOwnerGroupID"), "char *");
1142     dalloc_add(mdattrs, dalloc_strdup(mdattrs, "kMDItemFSContentChangeDate"), "char *");
1143
1144     sl_filemeta_t *fmeta = talloc_zero(reply, sl_filemeta_t);
1145     dalloc_add(fmeta, mdattrs, sl_array_t);
1146     dalloc_add(array, fmeta, sl_filemeta_t);
1147
1148 EC_CLEANUP:
1149     EC_EXIT;
1150 }
1151
1152 static int sl_rpc_fetchAttributesForOIDArray(AFPObj *obj, const DALLOC_CTX *query, DALLOC_CTX *reply, const struct vol *vol)
1153 {
1154     EC_INIT;
1155     uint64_t uint64;
1156     sl_cnids_t *cnids, *replycnids;
1157     cnid_t id, did;
1158     struct dir *dir;
1159     sl_array_t *array, *reqinfo, *fm_array;
1160     char buffer[12 + MAXPATHLEN + 1];
1161     char *name, *path;
1162     sl_filemeta_t *fm;
1163     sl_nil_t nil;
1164     uint64_t sl_res;
1165     struct stat sb;
1166
1167     array = talloc_zero(reply, sl_array_t);
1168     replycnids = talloc_zero(reply, sl_cnids_t);
1169     replycnids->ca_cnids = talloc_zero(replycnids, DALLOC_CTX);
1170     fm = talloc_zero(array, sl_filemeta_t);
1171     fm_array = talloc_zero(fm, sl_array_t);
1172
1173     if (array == NULL || replycnids == NULL || replycnids->ca_cnids == NULL
1174         || fm == NULL || fm_array == NULL) {
1175         EC_FAIL;
1176     }
1177
1178     reqinfo = dalloc_get(query, "DALLOC_CTX", 0, "sl_array_t", 1);
1179     if (reqinfo == NULL) {
1180         EC_FAIL;
1181     }
1182     cnids = dalloc_get(query, "DALLOC_CTX", 0, "sl_cnids_t", 2);
1183     if (cnids == NULL) {
1184         EC_FAIL;
1185     }
1186
1187     memcpy(&uint64, cnids->ca_cnids->dd_talloc_array[0], sizeof(uint64_t));
1188     id = (cnid_t)uint64;
1189
1190     if (htonl(id) == DIRDID_ROOT) {
1191         path = talloc_strdup(reply, vol->v_path);
1192     } else if (id < CNID_START) {
1193         EC_FAIL;
1194     } else {
1195         did = htonl(id);
1196         EC_NULL( name = cnid_resolve(vol->v_cdb, &did, buffer, sizeof(buffer)) );
1197         EC_NULL( dir = dirlookup(vol, did) );
1198         EC_NULL( path = talloc_asprintf(reply, "%s/%s", bdata(dir->d_fullpath), name) );
1199     }
1200
1201     EC_ZERO( stat(path, &sb) );
1202
1203     sl_res = 0;
1204     dalloc_add_copy(array, &sl_res, uint64_t);
1205
1206     replycnids->ca_unkn1 = 0xfec;
1207     replycnids->ca_context = cnids->ca_context;
1208     uint64 = (uint64_t)id;
1209     dalloc_add_copy(replycnids->ca_cnids, &uint64, uint64_t);
1210     dalloc_add(array, replycnids, sl_cnids_t);
1211     dalloc_add(fm, fm_array, fm_array_t);
1212     dalloc_add_copy(fm_array, &nil, sl_nil_t);
1213     add_filemeta(reqinfo, fm_array, path, &sb);
1214
1215     /* Now add result */
1216     dalloc_add(array, fm, sl_filemeta_t);
1217     dalloc_add(reply, array, sl_array_t);
1218     EC_EXIT;
1219
1220 EC_CLEANUP:
1221     sl_res = UINT64_MAX;
1222     dalloc_add_copy(array, &sl_res, uint64_t);
1223     dalloc_add(array, fm, sl_filemeta_t);
1224     dalloc_add(reply, array, sl_array_t);
1225     EC_EXIT;
1226 }
1227
1228 static int sl_rpc_closeQueryForContext(const AFPObj *obj,
1229                                        const DALLOC_CTX *query,
1230                                        DALLOC_CTX *reply,
1231                                        const struct vol *v)
1232 {
1233     EC_INIT;
1234     slq_t *slq = NULL;
1235     uint64_t *uint64, ctx1, ctx2;
1236     sl_array_t *array;
1237     uint64_t sl_result;
1238
1239     array = talloc_zero(reply, sl_array_t);
1240
1241     /* Context */
1242     uint64 = dalloc_get(query, "DALLOC_CTX", 0, "DALLOC_CTX", 0, "uint64_t", 1);
1243     if (uint64 == NULL) {
1244         EC_FAIL;
1245     }
1246     ctx1 = *uint64;
1247     uint64 = dalloc_get(query, "DALLOC_CTX", 0, "DALLOC_CTX", 0, "uint64_t", 2);
1248     if (uint64 == NULL) {
1249         EC_FAIL;
1250     }
1251     ctx2 = *uint64;
1252
1253     /* Get query for context and free it */
1254     slq = slq_for_ctx(ctx1, ctx2);
1255     if (slq == NULL) {
1256         EC_FAIL;
1257     }
1258
1259     switch (slq->slq_state) {
1260     case SLQ_STATE_FULL:
1261     case SLQ_STATE_DONE:
1262     case SLQ_STATE_ERROR:
1263         LOG(log_debug, logtype_sl, "close: destroying query: state %s",
1264             slq_state_names[slq->slq_state].state_name);
1265         slq_destroy(slq);
1266         break;
1267
1268     case SLQ_STATE_RUNNING:
1269     case SLQ_STATE_RESULTS:
1270         LOG(log_debug, logtype_sl, "close: cancel query: state %s",
1271             slq_state_names[slq->slq_state].state_name);
1272         slq_cancel(slq);
1273         break;
1274
1275     default:
1276         LOG(log_error, logtype_sl, "Unexpected state %d", slq->slq_state);
1277         EC_FAIL;
1278     }
1279
1280     sl_result = 0;
1281
1282 EC_CLEANUP:
1283     if (ret != 0) {
1284         sl_result = UINT64_MAX;
1285     }
1286     dalloc_add_copy(array, &sl_result, uint64_t);
1287     dalloc_add(reply, array, sl_array_t);
1288     EC_EXIT;
1289 }
1290
1291 /******************************************************************************
1292  * Spotlight functions
1293  ******************************************************************************/
1294
1295 int spotlight_init(AFPObj *obj)
1296 {
1297     static bool initialized = false;
1298     const char *attributes;
1299     struct sl_ctx *sl_ctx;
1300
1301     if (initialized) {
1302         return 0;
1303     }
1304
1305     LOG(log_info, logtype_sl, "Initializing Spotlight");
1306
1307     sl_ctx = talloc_zero(NULL, struct sl_ctx);
1308     obj->sl_ctx = sl_ctx;
1309
1310     attributes = atalk_iniparser_getstring(obj->iniconfig, INISEC_GLOBAL,
1311                                            "spotlight attributes", NULL);
1312     if (attributes) {
1313         configure_spotlight_attributes(attributes);
1314     }
1315
1316     /*
1317      * Tracker uses glibs event dispatching, so we need a mainloop
1318      */
1319 #if ((GLIB_MAJOR_VERSION <= 2) && (GLIB_MINOR_VERSION < 36))
1320         g_type_init();
1321 #endif
1322     sl_ctx->mainloop = g_main_loop_new(NULL, false);
1323     sl_ctx->cancellable = g_cancellable_new();
1324
1325     setenv("DBUS_SESSION_BUS_ADDRESS", "unix:path=" _PATH_STATEDIR "spotlight.ipc", 1);
1326     setenv("XDG_DATA_HOME", _PATH_STATEDIR, 0);
1327     setenv("XDG_CACHE_HOME", _PATH_STATEDIR, 0);
1328     setenv("TRACKER_USE_LOG_FILES", "1", 0);
1329
1330     tracker_sparql_connection_get_async(sl_ctx->cancellable,
1331                                         tracker_con_cb, sl_ctx);
1332
1333     initialized = true;
1334     return 0;
1335 }
1336
1337 /******************************************************************************
1338  * AFP functions
1339  ******************************************************************************/
1340
1341 int afp_spotlight_rpc(AFPObj *obj, char *ibuf, size_t ibuflen,
1342                       char *rbuf, size_t *rbuflen)
1343 {
1344     EC_INIT;
1345     TALLOC_CTX *tmp_ctx = talloc_new(NULL);
1346     uint16_t vid;
1347     int cmd;
1348     struct vol      *vol;
1349     DALLOC_CTX *query;
1350     DALLOC_CTX *reply;
1351     char *rpccmd;
1352     int len;
1353     bool event;
1354
1355     *rbuflen = 0;
1356
1357     if (!(obj->options.flags & OPTION_SPOTLIGHT)) {
1358         return AFPERR_NOOP;
1359     }
1360
1361     spotlight_init(obj);
1362     slq_dump();
1363
1364     /*
1365      * Process finished glib events
1366      */
1367     event = true;
1368     while (event) {
1369         event = g_main_context_iteration(NULL, false);
1370     }
1371     slq_cancelled_cleanup();
1372
1373     ibuf += 2;
1374     ibuflen -= 2;
1375
1376     vid = SVAL(ibuf, 0);
1377     LOG(log_debug, logtype_sl, "afp_spotlight_rpc(vid: %" PRIu16 ")", vid);
1378
1379     if ((vol = getvolbyvid(vid)) == NULL) {
1380         LOG(log_error, logtype_sl, "afp_spotlight_rpc: bad volume id: %" PRIu16 ")", vid);
1381         ret = AFPERR_ACCESS;
1382         goto EC_CLEANUP;
1383     }
1384
1385     /*    IVAL(ibuf, 2): unknown, always 0x00008004, some flags ? */
1386
1387     cmd = RIVAL(ibuf, 6);
1388     LOG(log_debug, logtype_sl, "afp_spotlight_rpc(cmd: %d)", cmd);
1389
1390     /*    IVAL(ibuf, 10: unknown, always 0x00000000 */
1391
1392     switch (cmd) {
1393
1394     case SPOTLIGHT_CMD_OPEN:
1395     case SPOTLIGHT_CMD_OPEN2:
1396         RSIVAL(rbuf, 0, ntohs(vid));
1397         RSIVAL(rbuf, 4, 0);
1398         len = strlen(vol->v_path) + 1;
1399         strncpy(rbuf + 8, vol->v_path, len);
1400         *rbuflen += 8 + len;
1401         break;
1402
1403     case SPOTLIGHT_CMD_FLAGS:
1404         RSIVAL(rbuf, 0, 0x0100006b); /* Whatever this value means... flags? Helios uses 0x1eefface */
1405         *rbuflen += 4;
1406         break;
1407
1408     case SPOTLIGHT_CMD_RPC:
1409         EC_NULL( query = talloc_zero(tmp_ctx, DALLOC_CTX) );
1410         EC_NULL( reply = talloc_zero(tmp_ctx, DALLOC_CTX) );
1411         EC_NEG1_LOG( sl_unpack(query, ibuf + 22) );
1412
1413         LOG(log_debug, logtype_sl, "Spotlight RPC request:\n%s",
1414             dd_dump(query, 0));
1415
1416         EC_NULL_LOG( rpccmd = dalloc_get(query, "DALLOC_CTX", 0, "DALLOC_CTX", 0, "char *", 0) );
1417
1418         if (STRCMP(rpccmd, ==, "fetchPropertiesForContext:")) {
1419             EC_ZERO_LOG( sl_rpc_fetchPropertiesForContext(obj, query, reply, vol) );
1420         } else if (STRCMP(rpccmd, ==, "openQueryWithParams:forContext:")) {
1421             EC_ZERO_LOG( sl_rpc_openQuery(obj, query, reply, vol) );
1422         } else if (STRCMP(rpccmd, ==, "fetchQueryResultsForContext:")) {
1423             EC_ZERO_LOG( sl_rpc_fetchQueryResultsForContext(obj, query, reply, vol) );
1424         } else if (STRCMP(rpccmd, ==, "storeAttributes:forOIDArray:context:")) {
1425             EC_ZERO_LOG( sl_rpc_storeAttributesForOIDArray(obj, query, reply, vol) );
1426         } else if (STRCMP(rpccmd, ==, "fetchAttributeNamesForOIDArray:context:")) {
1427             EC_ZERO_LOG( sl_rpc_fetchAttributeNamesForOIDArray(obj, query, reply, vol) );
1428         } else if (STRCMP(rpccmd, ==, "fetchAttributes:forOIDArray:context:")) {
1429             EC_ZERO_LOG( sl_rpc_fetchAttributesForOIDArray(obj, query, reply, vol) );
1430         } else if (STRCMP(rpccmd, ==, "closeQueryForContext:")) {
1431             EC_ZERO_LOG( sl_rpc_closeQueryForContext(obj, query, reply, vol) );
1432         } else {
1433             LOG(log_error, logtype_sl, "afp_spotlight_rpc: unknown Spotlight RPC: %s", rpccmd);
1434         }
1435
1436         LOG(log_debug, logtype_sl, "Spotlight RPC reply dump:\n%s",
1437             dd_dump(reply, 0));
1438
1439         memset(rbuf, 0, 4);
1440         *rbuflen += 4;
1441
1442         EC_NEG1_LOG( len = sl_pack(reply, rbuf + 4) );
1443         *rbuflen += len;
1444         break;
1445     }
1446
1447 EC_CLEANUP:
1448     talloc_free(tmp_ctx);
1449     if (ret != AFP_OK) {
1450         *rbuflen = 0;
1451         return AFPERR_MISC;
1452     }
1453     EC_EXIT;
1454 }