]> arthur.barton.de Git - netatalk.git/blob - etc/afpd/spotlight.c
8644d465d24e629c1aa956141af6ba8ab9c607d0
[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 = 0;
406
407     /* FileMeta */
408     fm = talloc_zero(array, sl_filemeta_t);
409     if (!fm) {
410         return false;
411     }
412
413     dalloc_add_copy(array, &status, uint64_t);
414     dalloc_add(array, slq->query_results->cnids, sl_cnids_t);
415     if (slq->query_results->num_results > 0) {
416         dalloc_add(fm, slq->query_results->fm_array, sl_array_t);
417     }
418     dalloc_add(array, fm, sl_filemeta_t);
419
420     /* This ensure the results get clean up after been sent to the client */
421     talloc_steal(array, slq->query_results);
422     slq->query_results = NULL;
423
424     if (!create_result_handle(slq)) {
425         LOG(log_error, logtype_sl, "couldn't add result handle");
426         slq->slq_state = SLQ_STATE_ERROR;
427         return false;
428     }
429
430     return true;
431 }
432
433 /******************************************************************************
434  * Spotlight queries
435  ******************************************************************************/
436
437 static ATALK_LIST_HEAD(sl_queries);
438 static ATALK_LIST_HEAD(sl_cancelled_queries);
439
440 /**
441  * Add a query to the list of active queries
442  **/
443 static void slq_add(slq_t *slq)
444 {
445     list_add(&(slq->slq_list), &sl_queries);
446 }
447
448 /**
449  * Add a query to the list of active queries
450  **/
451 static void slq_cancelled_add(slq_t *slq)
452 {
453     list_add(&(slq->slq_list), &sl_cancelled_queries);
454 }
455
456 /**
457  * Remove a query from the active list
458  **/
459 static void slq_remove(slq_t *slq)
460 {
461     struct list_head *p;
462     slq_t *q = NULL;
463
464     list_for_each(p, &sl_queries) {
465         q = list_entry(p, slq_t, slq_list);
466         if ((q->slq_ctx1 == slq->slq_ctx1) && (q->slq_ctx2 == slq->slq_ctx2)) {
467             list_del(p);
468             break;
469         }
470     }
471
472     return;
473 }
474
475 static slq_t *slq_for_ctx(uint64_t ctx1, uint64_t ctx2)
476 {
477     slq_t *q = NULL;
478     struct list_head *p;
479
480     list_for_each(p, &sl_queries) {
481         q = list_entry(p, slq_t, slq_list);
482         if ((q->slq_ctx1 == ctx1) && (q->slq_ctx2 == ctx2)) {
483             break;
484         }
485         q = NULL;
486     }
487
488     return q;
489 }
490
491 /**
492  * Remove a query from the active queue and free it
493  **/
494 static void slq_destroy(slq_t *slq)
495 {
496     if (slq == NULL) {
497         return;
498     }
499     slq_remove(slq);
500     talloc_free(slq);
501 }
502
503 /**
504  * Cancel a query
505  **/
506 static void slq_cancel(slq_t *slq)
507 {
508     slq->slq_state = SLQ_STATE_CANCEL_PENDING;
509     slq_remove(slq);
510     slq_cancelled_add(slq);
511 }
512
513 /**
514  * talloc destructor cb
515  **/
516 static int slq_free_cb(slq_t *slq)
517 {
518     if (slq->tracker_cursor) {
519         g_object_unref(slq->tracker_cursor);
520     }
521     return 0;
522 }
523
524 /**
525  * Free all cancelled queries
526  **/
527 static void slq_cancelled_cleanup(void)
528 {
529     struct list_head *p;
530     slq_t *q = NULL;
531
532     list_for_each(p, &sl_cancelled_queries) {
533         q = list_entry(p, slq_t, slq_list);
534         if (q->slq_state == SLQ_STATE_CANCELLED) {
535             LOG(log_debug, logtype_sl,
536                 "ctx1: %" PRIx64 ", ctx2: %" PRIx64 ": cancelled",
537                 q->slq_ctx1, q->slq_ctx2);
538             list_del(p);
539             talloc_free(q);
540         } else {
541             LOG(log_debug, logtype_sl,
542                 "ctx1: %" PRIx64 ", ctx2: %" PRIx64 ": %s",
543                 q->slq_ctx1, q->slq_ctx2, slq_state_names[q->slq_state].state_name);
544         }
545     }
546
547     return;
548 }
549
550 static void slq_dump(void)
551 {
552     struct list_head *p;
553     slq_t *q = NULL;
554     int i = 0;
555
556     list_for_each(p, &sl_queries) {
557         q = list_entry(p, slq_t, slq_list);
558         LOG(log_debug, logtype_sl,
559             "query[%d]: ctx1: %" PRIx64 ", ctx2: %" PRIx64 ", state: %s",
560             i++, q->slq_ctx1, q->slq_ctx2,
561             slq_state_names[q->slq_state].state_name);
562     }
563
564     return;
565 }
566
567 /************************************************
568  * Tracker async callbacks
569  ************************************************/
570
571 static void tracker_con_cb(GObject      *object,
572                            GAsyncResult *res,
573                            gpointer      user_data)
574 {
575     struct sl_ctx *sl_ctx = user_data;
576     GError *error = NULL;
577
578     sl_ctx->tracker_con = tracker_sparql_connection_get_finish(res,
579                                                                &error);
580     if (error) {
581         LOG(log_error, logtype_sl, "Could not connect to Tracker: %s",
582             error->message);
583         sl_ctx->tracker_con = NULL;
584         g_error_free(error);
585         return;
586     }
587
588     LOG(log_info, logtype_sl, "connected to Tracker");
589 }
590
591 static void tracker_cursor_cb(GObject      *object,
592                               GAsyncResult *res,
593                               gpointer      user_data)
594 {
595     GError *error = NULL;
596     slq_t *slq = user_data;
597     gboolean more_results;
598     const gchar *uri;
599     char *path;
600     int result;
601     struct stat sb;
602     uint64_t uint64var;
603     bool ok;
604     cnid_t did, id;
605
606     LOG(log_debug, logtype_sl,
607         "cursor cb[%d]: ctx1: %" PRIx64 ", ctx2: %" PRIx64,
608         slq->query_results->num_results, slq->slq_ctx1, slq->slq_ctx2);
609
610     more_results = tracker_sparql_cursor_next_finish(slq->tracker_cursor,
611                                                      res,
612                                                      &error);
613
614     if (slq->slq_state == SLQ_STATE_CANCEL_PENDING) {
615         LOG(log_debug, logtype_sl,
616             "cursor cb: ctx1: %" PRIx64 ", ctx2: %" PRIx64 ": cancelled",
617             slq->slq_ctx1, slq->slq_ctx2);
618         slq->slq_state = SLQ_STATE_CANCELLED;
619         return;
620     }
621
622     if (error) {
623         LOG(log_error, logtype_sl, "Tracker cursor: %s", error->message);
624         g_error_free(error);
625         slq->slq_state = SLQ_STATE_ERROR;
626         return;
627     }
628
629     if (!more_results) {
630         LOG(log_debug, logtype_sl, "tracker_cursor_cb: done");
631         slq->slq_state = SLQ_STATE_DONE;
632         return;
633     }
634
635     uri = tracker_sparql_cursor_get_string(slq->tracker_cursor, 0, NULL);
636     if (uri == NULL) {
637         /*
638          * Not sure how this could happen if
639          * tracker_sparql_cursor_next_finish() returns true, but I've
640          * seen it.
641          */
642         LOG(log_debug, logtype_sl, "no URI for result");
643         return;
644     }
645
646     LOG(log_debug, logtype_sl, "URI: %s", uri);
647
648     path = tracker_to_unix_path(slq->query_results, uri);
649     if (path == NULL) {
650         LOG(log_error, logtype_sl, "error converting Tracker URI: %s", uri);
651         slq->slq_state = SLQ_STATE_ERROR;
652         return;
653     }
654
655     result = access(path, R_OK);
656     if (result != 0) {
657         goto exit;
658     }
659
660     id = cnid_for_path(slq->slq_vol->v_cdb, slq->slq_vol->v_path, path, &did);
661     if (id == CNID_INVALID) {
662         LOG(log_error, logtype_sl, "cnid_for_path error: %s", path);
663         goto exit;
664     }
665     uint64var = ntohl(id);
666
667     if (slq->slq_cnids) {
668         ok = bsearch(&uint64var, slq->slq_cnids, slq->slq_cnids_num,
669                      sizeof(uint64_t), cnid_comp_fn);
670         if (!ok) {
671             goto exit;
672         }
673     }
674
675     dalloc_add_copy(slq->query_results->cnids->ca_cnids,
676                     &uint64var, uint64_t);
677     ok = add_filemeta(slq->slq_reqinfo, slq->query_results->fm_array,
678                       path, &sb);
679     if (!ok) {
680         LOG(log_error, logtype_sl, "add_filemeta error");
681         slq->slq_state = SLQ_STATE_ERROR;
682         return;
683     }
684
685     slq->query_results->num_results++;
686
687 exit:
688     if (slq->query_results->num_results < MAX_SL_RESULTS) {
689         LOG(log_debug, logtype_sl,
690             "cursor cb[%d]: ctx1: %" PRIx64 ", ctx2: %" PRIx64 ": requesting more results",
691             slq->query_results->num_results - 1, slq->slq_ctx1, slq->slq_ctx2);
692
693         slq->slq_state = SLQ_STATE_RESULTS;
694
695         tracker_sparql_cursor_next_async(slq->tracker_cursor,
696                                          slq->slq_obj->sl_ctx->cancellable,
697                                          tracker_cursor_cb,
698                                          slq);
699     } else {
700         LOG(log_debug, logtype_sl,
701             "cursor cb[%d]: ctx1: %" PRIx64 ", ctx2: %" PRIx64 ": full",
702             slq->query_results->num_results - 1, slq->slq_ctx1, slq->slq_ctx2);
703
704         slq->slq_state = SLQ_STATE_FULL;
705     }
706 }
707
708 static void tracker_query_cb(GObject      *object,
709                              GAsyncResult *res,
710                              gpointer      user_data)
711 {
712     GError *error = NULL;
713     slq_t *slq = user_data;
714
715     LOG(log_debug, logtype_sl,
716         "query cb: ctx1: %" PRIx64 ", ctx2: %" PRIx64,
717         slq->slq_ctx1, slq->slq_ctx2);
718
719     slq->tracker_cursor = tracker_sparql_connection_query_finish(
720         TRACKER_SPARQL_CONNECTION(object),
721         res,
722         &error);
723
724     if (slq->slq_state == SLQ_STATE_CANCEL_PENDING) {
725         slq->slq_state = SLQ_STATE_CANCELLED;
726         return;
727     }
728
729     if (error) {
730         slq->slq_state = SLQ_STATE_ERROR;
731         LOG(log_error, logtype_sl, "Tracker query error: %s", error->message);
732         g_error_free(error);
733         return;
734     }
735
736     slq->slq_state = SLQ_STATE_RESULTS;
737
738     tracker_sparql_cursor_next_async(slq->tracker_cursor,
739                                      slq->slq_obj->sl_ctx->cancellable,
740                                      tracker_cursor_cb,
741                                      slq);
742 }
743
744 /*******************************************************************************
745  * Spotlight RPC functions
746  ******************************************************************************/
747
748 static int sl_rpc_fetchPropertiesForContext(const AFPObj *obj,
749                                             const DALLOC_CTX *query,
750                                             DALLOC_CTX *reply,
751                                             const struct vol *v)
752 {
753     EC_INIT;
754
755     char *s;
756     sl_dict_t *dict;
757     sl_array_t *array;
758     sl_uuid_t uuid;
759
760     if (!v->v_uuid) {
761         EC_FAIL_LOG("missing UUID for volume: %s", v->v_localname);
762     }
763     dict = talloc_zero(reply, sl_dict_t);
764
765     /* key/val 1 */
766     s = dalloc_strdup(dict, "kMDSStoreMetaScopes");
767     dalloc_add(dict, s, char *);
768
769     array = talloc_zero(dict, sl_array_t);
770     s = dalloc_strdup(array, "kMDQueryScopeComputer");
771     dalloc_add(array, s, char *);
772     dalloc_add(dict, array, sl_array_t);
773
774     /* key/val 2 */
775     s = dalloc_strdup(dict, "kMDSStorePathScopes");
776     dalloc_add(dict, s, char *);
777
778     array = talloc_zero(dict, sl_array_t);
779     s = dalloc_strdup(array, v->v_path);
780     dalloc_add(array, s, char *);
781     dalloc_add(dict, array, sl_array_t);
782
783     /* key/val 3 */
784     s = dalloc_strdup(dict, "kMDSStoreUUID");
785     dalloc_add(dict, s, char *);
786
787     memcpy(uuid.sl_uuid, v->v_uuid, 16);
788     dalloc_add_copy(dict, &uuid, sl_uuid_t);
789
790     /* key/val 4 */
791     s = dalloc_strdup(dict, "kMDSStoreHasPersistentUUID");
792     dalloc_add(dict, s, char *);
793     sl_bool_t b = true;
794     dalloc_add_copy(dict, &b, sl_bool_t);
795
796     dalloc_add(reply, dict, sl_dict_t);
797
798 EC_CLEANUP:
799     EC_EXIT;
800 }
801
802 static int sl_rpc_openQuery(AFPObj *obj,
803                             const DALLOC_CTX *query,
804                             DALLOC_CTX *reply,
805                             struct vol *v)
806 {
807     EC_INIT;
808     char *sl_query;
809     uint64_t *uint64;
810     DALLOC_CTX *reqinfo;
811     sl_array_t *array;
812     sl_cnids_t *cnids;
813     slq_t *slq;
814     char slq_host[MAXPATHLEN + 1];
815     uint16_t convflags = v->v_mtou_flags;
816     uint64_t result;
817     gchar *sparql_query;
818     GError *error = NULL;
819     bool ok;
820
821     array = talloc_zero(reply, sl_array_t);
822
823     if (obj->sl_ctx->tracker_con == NULL) {
824         LOG(log_error, logtype_sl, "no tracker connection");
825         EC_FAIL;
826     }
827
828     /* Allocate and initialize query object */
829     slq = talloc_zero(obj->sl_ctx, slq_t);
830     slq->slq_state = SLQ_STATE_NEW;
831     slq->slq_obj = obj;
832     slq->slq_vol = v;
833     slq->slq_allow_expr = obj->options.flags & OPTION_SPOTLIGHT_EXPR ? true : false;
834     slq->slq_result_limit = obj->options.sparql_limit;
835     talloc_set_destructor(slq, slq_free_cb);
836
837     LOG(log_debug, logtype_sl, "Spotlight: expr: %s, limit: %" PRIu64,
838         slq->slq_allow_expr ? "yes" : "no", slq->slq_result_limit);
839
840     /* convert spotlight query charset to host charset */
841     sl_query = dalloc_value_for_key(query, "DALLOC_CTX", 0,
842                                     "DALLOC_CTX", 1,
843                                     "kMDQueryString");
844     if (sl_query == NULL) {
845         EC_FAIL;
846     }
847     ret = convert_charset(CH_UTF8_MAC, v->v_volcharset, v->v_maccharset,
848                           sl_query, strlen(sl_query), slq_host, MAXPATHLEN,
849                           &convflags);
850     if (ret == -1) {
851         LOG(log_error, logtype_sl, "charset conversion failed");
852         EC_FAIL;
853     }
854     slq->slq_qstring = talloc_strdup(slq, slq_host);
855     LOG(log_debug, logtype_sl, "Spotlight query: \"%s\"", slq->slq_qstring);
856
857     slq->slq_time = time(NULL);
858     uint64 = dalloc_get(query, "DALLOC_CTX", 0, "DALLOC_CTX", 0, "uint64_t", 1);
859     if (uint64 == NULL) {
860         EC_FAIL;
861     }
862     slq->slq_ctx1 = *uint64;
863
864     uint64 = dalloc_get(query, "DALLOC_CTX", 0, "DALLOC_CTX", 0, "uint64_t", 2);
865     if (uint64 == NULL) {
866         EC_FAIL;
867     }
868     slq->slq_ctx2 = *uint64;
869
870     reqinfo = dalloc_value_for_key(query, "DALLOC_CTX", 0, "DALLOC_CTX", 1,
871                                    "kMDAttributeArray");
872     if (reqinfo == NULL) {
873         EC_FAIL;
874     }
875     slq->slq_reqinfo = talloc_steal(slq, reqinfo);
876
877     cnids = dalloc_value_for_key(query, "DALLOC_CTX", 0, "DALLOC_CTX", 1,
878                                  "kMDQueryItemArray");
879     if (cnids) {
880         EC_ZERO_LOG( sl_createCNIDArray(slq, cnids->ca_cnids) );
881     }
882
883     ret = map_spotlight_to_sparql_query(slq, &sparql_query);
884     if (ret != 0) {
885         LOG(log_debug, logtype_sl, "mapping retured non-zero");
886         EC_FAIL;
887     }
888     LOG(log_debug, logtype_sl, "SPARQL query: \"%s\"", sparql_query);
889
890     tracker_sparql_connection_query_async(obj->sl_ctx->tracker_con,
891                                           sparql_query,
892                                           slq->slq_obj->sl_ctx->cancellable,
893                                           tracker_query_cb,
894                                           slq);
895     if (error) {
896         LOG(log_error, logtype_sl, "Couldn't query the Tracker Store: '%s'",
897             error->message);
898         g_clear_error(&error);
899         EC_FAIL;
900     }
901
902     slq->slq_state = SLQ_STATE_RUNNING;
903
904     ok = create_result_handle(slq);
905     if (!ok) {
906         LOG(log_error, logtype_sl, "create_result_handle error");
907         slq->slq_state = SLQ_STATE_ERROR;
908         EC_FAIL;
909     }
910
911     slq_add(slq);
912
913 EC_CLEANUP:
914     if (ret != 0) {
915         slq_destroy(slq);
916         result = UINT64_MAX;
917         ret = 0;
918     } else {
919         result = 0;
920     }
921
922     dalloc_add_copy(array, &result, uint64_t);
923     dalloc_add(reply, array, sl_array_t);
924     EC_EXIT;
925 }
926
927 static int sl_rpc_fetchQueryResultsForContext(const AFPObj *obj,
928                                               const DALLOC_CTX *query,
929                                               DALLOC_CTX *reply,
930                                               const struct vol *v)
931 {
932     EC_INIT;
933     slq_t *slq = NULL;
934     uint64_t *uint64, ctx1, ctx2, status;
935     sl_array_t *array;
936     bool ok;
937
938     array = talloc_zero(reply, sl_array_t);
939     if (array == NULL) {
940         return false;
941     }
942
943     /* Context */
944     uint64 = dalloc_get(query, "DALLOC_CTX", 0, "DALLOC_CTX", 0, "uint64_t", 1);
945     if (uint64 == NULL) {
946         EC_FAIL;
947     }
948     ctx1 = *uint64;
949     uint64 = dalloc_get(query, "DALLOC_CTX", 0, "DALLOC_CTX", 0, "uint64_t", 2);
950     if (uint64 == NULL) {
951         EC_FAIL;
952     }
953     ctx2 = *uint64;
954
955     /* Get query for context */
956     slq = slq_for_ctx(ctx1, ctx2);
957     if (slq == NULL) {
958         EC_FAIL;
959     }
960
961     switch (slq->slq_state) {
962     case SLQ_STATE_RUNNING:
963     case SLQ_STATE_RESULTS:
964     case SLQ_STATE_FULL:
965     case SLQ_STATE_DONE:
966         ok = add_results(array, slq);
967         if (!ok) {
968             LOG(log_error, logtype_sl, "error adding results");
969             EC_FAIL;
970         }
971         if (slq->slq_state == SLQ_STATE_FULL) {
972             slq->slq_state = SLQ_STATE_RESULTS;
973
974             tracker_sparql_cursor_next_async(
975                 slq->tracker_cursor,
976                 slq->slq_obj->sl_ctx->cancellable,
977                 tracker_cursor_cb,
978                 slq);
979         }
980         break;
981
982     case SLQ_STATE_ERROR:
983         LOG(log_error, logtype_sl, "query in error state");
984         EC_FAIL;
985
986     default:
987         LOG(log_error, logtype_sl, "unexpected query state %d", slq->slq_state);
988         EC_FAIL;
989     }
990
991     dalloc_add(reply, array, sl_array_t);
992     EC_EXIT;
993
994 EC_CLEANUP:
995     slq_destroy(slq);
996     status = UINT64_MAX;
997     dalloc_add_copy(array, &status, uint64_t);
998     dalloc_add(reply, array, sl_array_t);
999     EC_EXIT;
1000 }
1001
1002 static int sl_rpc_storeAttributesForOIDArray(const AFPObj *obj,
1003                                              const DALLOC_CTX *query,
1004                                              DALLOC_CTX *reply,
1005                                              const struct vol *vol)
1006 {
1007     EC_INIT;
1008     uint64_t uint64;
1009     sl_array_t *array;
1010     sl_cnids_t *cnids;
1011     sl_time_t *sl_time;
1012     cnid_t id;
1013     char *path;
1014     struct dir *dir;
1015
1016     EC_NULL_LOG( cnids = dalloc_get(query, "DALLOC_CTX", 0, "sl_cnids_t", 2) );
1017     memcpy(&uint64, cnids->ca_cnids->dd_talloc_array[0], sizeof(uint64_t));
1018     id = (cnid_t)uint64;
1019     LOG(log_debug, logtype_sl, "CNID: %" PRIu32, id);
1020
1021     if (htonl(id) == DIRDID_ROOT) {
1022         path = vol->v_path;
1023     } else if (id < CNID_START) {
1024         EC_FAIL;
1025     } else {
1026         cnid_t did;
1027         char buffer[12 + MAXPATHLEN + 1];
1028
1029         did = htonl(id);
1030         EC_NULL_LOG( path = cnid_resolve(vol->v_cdb, &did, buffer, sizeof(buffer)) );
1031         EC_NULL_LOG( dir = dirlookup(vol, did) );
1032         EC_NEG1_LOG( movecwd(vol, dir) );
1033     }
1034
1035     /*
1036      * We're possibly supposed to update attributes in two places: the
1037      * database and the filesystem.  Due to the lack of documentation
1038      * and not yet implemented database updates, we cherry pick attributes
1039      * that seems to be candidates for updating filesystem metadata.
1040      */
1041
1042     if ((sl_time = dalloc_value_for_key(query, "DALLOC_CTX", 0, "DALLOC_CTX", 1, "DALLOC_CTX", 1, "kMDItemFSContentChangeDate"))) {
1043         struct utimbuf utimes;
1044         utimes.actime = utimes.modtime = sl_time->tv_sec;
1045         utime(path, &utimes);
1046     }
1047
1048     array = talloc_zero(reply, sl_array_t);
1049     uint64_t sl_res = 0;
1050     dalloc_add_copy(array, &sl_res, uint64_t);
1051     dalloc_add(reply, array, sl_array_t);
1052
1053 EC_CLEANUP:
1054     EC_EXIT;
1055 }
1056
1057 static int sl_rpc_fetchAttributeNamesForOIDArray(const AFPObj *obj, const DALLOC_CTX *query, DALLOC_CTX *reply, const struct vol *vol)
1058 {
1059     EC_INIT;
1060     uint64_t uint64;
1061     sl_cnids_t *cnids;
1062     cnid_t id;
1063     char *path;
1064     struct dir *dir;
1065
1066     EC_NULL_LOG( cnids = dalloc_get(query, "DALLOC_CTX", 0, "sl_cnids_t", 1) );
1067     memcpy(&uint64, cnids->ca_cnids->dd_talloc_array[0], sizeof(uint64_t));
1068     id = (cnid_t)uint64;
1069     LOG(log_debug, logtype_sl, "sl_rpc_fetchAttributeNamesForOIDArray: CNID: %" PRIu32, id);
1070
1071     if (htonl(id) == DIRDID_ROOT) {
1072         path = vol->v_path;
1073     } else if (id < CNID_START) {
1074         EC_FAIL;
1075     } else {
1076         cnid_t did;
1077         char buffer[12 + MAXPATHLEN + 1];
1078
1079         did = htonl(id);
1080         EC_NULL_LOG( path = cnid_resolve(vol->v_cdb, &did, buffer, sizeof(buffer)) );
1081         EC_NULL_LOG( dir = dirlookup(vol, did) );
1082         EC_NEG1_LOG( movecwd(vol, dir) );
1083     }
1084
1085     /* Result array */
1086     sl_array_t *array = talloc_zero(reply, sl_array_t);
1087     dalloc_add(reply, array, sl_array_t);
1088
1089     /* Return result value 0 */
1090     uint64_t sl_res = 0;
1091     dalloc_add_copy(array, &sl_res, uint64_t);
1092
1093     /* Return CNID array */
1094     sl_cnids_t *replycnids = talloc_zero(reply, sl_cnids_t);
1095     replycnids->ca_cnids = talloc_zero(cnids, DALLOC_CTX);
1096     replycnids->ca_unkn1 = 0xfec;
1097     replycnids->ca_context = cnids->ca_context;
1098     uint64 = (uint64_t)id;
1099     dalloc_add_copy(replycnids->ca_cnids, &uint64, uint64_t);
1100     dalloc_add(array, replycnids, sl_cnids_t);
1101
1102     /* Return filemeta array */
1103
1104     /*
1105      * FIXME: this should return the real attributes from all known metadata sources
1106      * (Tracker and filesystem)
1107      */
1108     sl_array_t *mdattrs = talloc_zero(reply, sl_array_t);
1109     dalloc_add(mdattrs, dalloc_strdup(mdattrs, "kMDItemFSName"), "char *");
1110     dalloc_add(mdattrs, dalloc_strdup(mdattrs, "kMDItemDisplayName"), "char *");
1111     dalloc_add(mdattrs, dalloc_strdup(mdattrs, "kMDItemFSSize"), "char *");
1112     dalloc_add(mdattrs, dalloc_strdup(mdattrs, "kMDItemFSOwnerUserID"), "char *");
1113     dalloc_add(mdattrs, dalloc_strdup(mdattrs, "kMDItemFSOwnerGroupID"), "char *");
1114     dalloc_add(mdattrs, dalloc_strdup(mdattrs, "kMDItemFSContentChangeDate"), "char *");
1115
1116     sl_filemeta_t *fmeta = talloc_zero(reply, sl_filemeta_t);
1117     dalloc_add(fmeta, mdattrs, sl_array_t);
1118     dalloc_add(array, fmeta, sl_filemeta_t);
1119
1120 EC_CLEANUP:
1121     EC_EXIT;
1122 }
1123
1124 static int sl_rpc_fetchAttributesForOIDArray(AFPObj *obj, const DALLOC_CTX *query, DALLOC_CTX *reply, const struct vol *vol)
1125 {
1126     EC_INIT;
1127     uint64_t uint64;
1128     sl_cnids_t *cnids, *replycnids;
1129     cnid_t id, did;
1130     struct dir *dir;
1131     sl_array_t *array, *reqinfo, *fm_array;
1132     char buffer[12 + MAXPATHLEN + 1];
1133     char *name, *path;
1134     sl_filemeta_t *fm;
1135     sl_nil_t nil;
1136     uint64_t sl_res;
1137     struct stat sb;
1138
1139     array = talloc_zero(reply, sl_array_t);
1140     replycnids = talloc_zero(reply, sl_cnids_t);
1141     replycnids->ca_cnids = talloc_zero(replycnids, DALLOC_CTX);
1142     fm = talloc_zero(array, sl_filemeta_t);
1143     fm_array = talloc_zero(fm, sl_array_t);
1144
1145     if (array == NULL || replycnids == NULL || replycnids->ca_cnids == NULL
1146         || fm == NULL || fm_array == NULL) {
1147         EC_FAIL;
1148     }
1149
1150     reqinfo = dalloc_get(query, "DALLOC_CTX", 0, "sl_array_t", 1);
1151     if (reqinfo == NULL) {
1152         EC_FAIL;
1153     }
1154     cnids = dalloc_get(query, "DALLOC_CTX", 0, "sl_cnids_t", 2);
1155     if (cnids == NULL) {
1156         EC_FAIL;
1157     }
1158
1159     memcpy(&uint64, cnids->ca_cnids->dd_talloc_array[0], sizeof(uint64_t));
1160     id = (cnid_t)uint64;
1161
1162     if (htonl(id) == DIRDID_ROOT) {
1163         path = talloc_strdup(reply, vol->v_path);
1164     } else if (id < CNID_START) {
1165         EC_FAIL;
1166     } else {
1167         did = htonl(id);
1168         EC_NULL( name = cnid_resolve(vol->v_cdb, &did, buffer, sizeof(buffer)) );
1169         EC_NULL( dir = dirlookup(vol, did) );
1170         EC_NULL( path = talloc_asprintf(reply, "%s/%s", bdata(dir->d_fullpath), name) );
1171     }
1172
1173     EC_ZERO( stat(path, &sb) );
1174
1175     sl_res = 0;
1176     dalloc_add_copy(array, &sl_res, uint64_t);
1177
1178     replycnids->ca_unkn1 = 0xfec;
1179     replycnids->ca_context = cnids->ca_context;
1180     uint64 = (uint64_t)id;
1181     dalloc_add_copy(replycnids->ca_cnids, &uint64, uint64_t);
1182     dalloc_add(array, replycnids, sl_cnids_t);
1183     dalloc_add(fm, fm_array, fm_array_t);
1184     dalloc_add_copy(fm_array, &nil, sl_nil_t);
1185     add_filemeta(reqinfo, fm_array, path, &sb);
1186
1187     /* Now add result */
1188     dalloc_add(array, fm, sl_filemeta_t);
1189     dalloc_add(reply, array, sl_array_t);
1190     EC_EXIT;
1191
1192 EC_CLEANUP:
1193     sl_res = UINT64_MAX;
1194     dalloc_add_copy(array, &sl_res, uint64_t);
1195     dalloc_add(array, fm, sl_filemeta_t);
1196     dalloc_add(reply, array, sl_array_t);
1197     EC_EXIT;
1198 }
1199
1200 static int sl_rpc_closeQueryForContext(const AFPObj *obj,
1201                                        const DALLOC_CTX *query,
1202                                        DALLOC_CTX *reply,
1203                                        const struct vol *v)
1204 {
1205     EC_INIT;
1206     slq_t *slq = NULL;
1207     uint64_t *uint64, ctx1, ctx2;
1208     sl_array_t *array;
1209     uint64_t sl_result;
1210
1211     array = talloc_zero(reply, sl_array_t);
1212
1213     /* Context */
1214     uint64 = dalloc_get(query, "DALLOC_CTX", 0, "DALLOC_CTX", 0, "uint64_t", 1);
1215     if (uint64 == NULL) {
1216         EC_FAIL;
1217     }
1218     ctx1 = *uint64;
1219     uint64 = dalloc_get(query, "DALLOC_CTX", 0, "DALLOC_CTX", 0, "uint64_t", 2);
1220     if (uint64 == NULL) {
1221         EC_FAIL;
1222     }
1223     ctx2 = *uint64;
1224
1225     /* Get query for context and free it */
1226     slq = slq_for_ctx(ctx1, ctx2);
1227     if (slq == NULL) {
1228         EC_FAIL;
1229     }
1230
1231     switch (slq->slq_state) {
1232     case SLQ_STATE_FULL:
1233     case SLQ_STATE_DONE:
1234     case SLQ_STATE_ERROR:
1235         LOG(log_debug, logtype_sl, "close: destroying query: state %s",
1236             slq_state_names[slq->slq_state].state_name);
1237         slq_destroy(slq);
1238         break;
1239
1240     case SLQ_STATE_RUNNING:
1241     case SLQ_STATE_RESULTS:
1242         LOG(log_debug, logtype_sl, "close: cancel query: state %s",
1243             slq_state_names[slq->slq_state].state_name);
1244         slq_cancel(slq);
1245         break;
1246
1247     default:
1248         LOG(log_error, logtype_sl, "Unexpected state %d", slq->slq_state);
1249         EC_FAIL;
1250     }
1251
1252     sl_result = 0;
1253
1254 EC_CLEANUP:
1255     if (ret != 0) {
1256         sl_result = UINT64_MAX;
1257     }
1258     dalloc_add_copy(array, &sl_result, uint64_t);
1259     dalloc_add(reply, array, sl_array_t);
1260     EC_EXIT;
1261 }
1262
1263 /******************************************************************************
1264  * Spotlight functions
1265  ******************************************************************************/
1266
1267 int spotlight_init(AFPObj *obj)
1268 {
1269     static bool initialized = false;
1270     const char *attributes;
1271     struct sl_ctx *sl_ctx;
1272
1273     if (initialized) {
1274         return 0;
1275     }
1276
1277     LOG(log_info, logtype_sl, "Initializing Spotlight");
1278
1279     sl_ctx = talloc_zero(NULL, struct sl_ctx);
1280     obj->sl_ctx = sl_ctx;
1281
1282     attributes = atalk_iniparser_getstring(obj->iniconfig, INISEC_GLOBAL,
1283                                            "spotlight attributes", NULL);
1284     if (attributes) {
1285         configure_spotlight_attributes(attributes);
1286     }
1287
1288     /*
1289      * Tracker uses glibs event dispatching, so we need a mainloop
1290      */
1291 #if ((GLIB_MAJOR_VERSION <= 2) && (GLIB_MINOR_VERSION < 36))
1292         g_type_init();
1293 #endif
1294     sl_ctx->mainloop = g_main_loop_new(NULL, false);
1295     sl_ctx->cancellable = g_cancellable_new();
1296
1297     setenv("DBUS_SESSION_BUS_ADDRESS", "unix:path=" _PATH_STATEDIR "spotlight.ipc", 1);
1298     setenv("XDG_DATA_HOME", _PATH_STATEDIR, 0);
1299     setenv("XDG_CACHE_HOME", _PATH_STATEDIR, 0);
1300     setenv("TRACKER_USE_LOG_FILES", "1", 0);
1301
1302     tracker_sparql_connection_get_async(sl_ctx->cancellable,
1303                                         tracker_con_cb, sl_ctx);
1304
1305     initialized = true;
1306     return 0;
1307 }
1308
1309 /******************************************************************************
1310  * AFP functions
1311  ******************************************************************************/
1312
1313 int afp_spotlight_rpc(AFPObj *obj, char *ibuf, size_t ibuflen,
1314                       char *rbuf, size_t *rbuflen)
1315 {
1316     EC_INIT;
1317     TALLOC_CTX *tmp_ctx = talloc_new(NULL);
1318     uint16_t vid;
1319     int cmd;
1320     struct vol      *vol;
1321     DALLOC_CTX *query;
1322     DALLOC_CTX *reply;
1323     char *rpccmd;
1324     int len;
1325     bool event;
1326
1327     *rbuflen = 0;
1328
1329     if (!(obj->options.flags & OPTION_SPOTLIGHT)) {
1330         return AFPERR_NOOP;
1331     }
1332
1333     spotlight_init(obj);
1334     slq_dump();
1335
1336     /*
1337      * Process finished glib events
1338      */
1339     event = true;
1340     while (event) {
1341         event = g_main_context_iteration(NULL, false);
1342     }
1343     slq_cancelled_cleanup();
1344
1345     ibuf += 2;
1346     ibuflen -= 2;
1347
1348     vid = SVAL(ibuf, 0);
1349     LOG(log_debug, logtype_sl, "afp_spotlight_rpc(vid: %" PRIu16 ")", vid);
1350
1351     if ((vol = getvolbyvid(vid)) == NULL) {
1352         LOG(log_error, logtype_sl, "afp_spotlight_rpc: bad volume id: %" PRIu16 ")", vid);
1353         ret = AFPERR_ACCESS;
1354         goto EC_CLEANUP;
1355     }
1356
1357     /*    IVAL(ibuf, 2): unknown, always 0x00008004, some flags ? */
1358
1359     cmd = RIVAL(ibuf, 6);
1360     LOG(log_debug, logtype_sl, "afp_spotlight_rpc(cmd: %d)", cmd);
1361
1362     /*    IVAL(ibuf, 10: unknown, always 0x00000000 */
1363
1364     switch (cmd) {
1365
1366     case SPOTLIGHT_CMD_OPEN:
1367     case SPOTLIGHT_CMD_OPEN2:
1368         RSIVAL(rbuf, 0, ntohs(vid));
1369         RSIVAL(rbuf, 4, 0);
1370         len = strlen(vol->v_path) + 1;
1371         strncpy(rbuf + 8, vol->v_path, len);
1372         *rbuflen += 8 + len;
1373         break;
1374
1375     case SPOTLIGHT_CMD_FLAGS:
1376         RSIVAL(rbuf, 0, 0x0100006b); /* Whatever this value means... flags? Helios uses 0x1eefface */
1377         *rbuflen += 4;
1378         break;
1379
1380     case SPOTLIGHT_CMD_RPC:
1381         EC_NULL( query = talloc_zero(tmp_ctx, DALLOC_CTX) );
1382         EC_NULL( reply = talloc_zero(tmp_ctx, DALLOC_CTX) );
1383         EC_NEG1_LOG( sl_unpack(query, ibuf + 22) );
1384
1385         LOG(log_debug, logtype_sl, "Spotlight RPC request:\n%s",
1386             dd_dump(query, 0));
1387
1388         EC_NULL_LOG( rpccmd = dalloc_get(query, "DALLOC_CTX", 0, "DALLOC_CTX", 0, "char *", 0) );
1389
1390         if (STRCMP(rpccmd, ==, "fetchPropertiesForContext:")) {
1391             EC_ZERO_LOG( sl_rpc_fetchPropertiesForContext(obj, query, reply, vol) );
1392         } else if (STRCMP(rpccmd, ==, "openQueryWithParams:forContext:")) {
1393             EC_ZERO_LOG( sl_rpc_openQuery(obj, query, reply, vol) );
1394         } else if (STRCMP(rpccmd, ==, "fetchQueryResultsForContext:")) {
1395             EC_ZERO_LOG( sl_rpc_fetchQueryResultsForContext(obj, query, reply, vol) );
1396         } else if (STRCMP(rpccmd, ==, "storeAttributes:forOIDArray:context:")) {
1397             EC_ZERO_LOG( sl_rpc_storeAttributesForOIDArray(obj, query, reply, vol) );
1398         } else if (STRCMP(rpccmd, ==, "fetchAttributeNamesForOIDArray:context:")) {
1399             EC_ZERO_LOG( sl_rpc_fetchAttributeNamesForOIDArray(obj, query, reply, vol) );
1400         } else if (STRCMP(rpccmd, ==, "fetchAttributes:forOIDArray:context:")) {
1401             EC_ZERO_LOG( sl_rpc_fetchAttributesForOIDArray(obj, query, reply, vol) );
1402         } else if (STRCMP(rpccmd, ==, "closeQueryForContext:")) {
1403             EC_ZERO_LOG( sl_rpc_closeQueryForContext(obj, query, reply, vol) );
1404         } else {
1405             LOG(log_error, logtype_sl, "afp_spotlight_rpc: unknown Spotlight RPC: %s", rpccmd);
1406         }
1407
1408         LOG(log_debug, logtype_sl, "Spotlight RPC reply dump:\n%s",
1409             dd_dump(reply, 0));
1410
1411         memset(rbuf, 0, 4);
1412         *rbuflen += 4;
1413
1414         EC_NEG1_LOG( len = sl_pack(reply, rbuf + 4) );
1415         *rbuflen += len;
1416         break;
1417     }
1418
1419 EC_CLEANUP:
1420     talloc_free(tmp_ctx);
1421     if (ret != AFP_OK) {
1422         *rbuflen = 0;
1423         return AFPERR_MISC;
1424     }
1425     EC_EXIT;
1426 }