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