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