]> arthur.barton.de Git - netatalk.git/blobdiff - etc/afpd/spotlight.c
Spotlight: move init to the right place
[netatalk.git] / etc / afpd / spotlight.c
index 2b6fb6edbd0a6656e73139b97067fa330defe1cb..7551bc7174f1ed2b655fb6d664e06ce7c5f6f02c 100644 (file)
@@ -1,5 +1,5 @@
 /*
-  Copyright (c) 2012 Frank Lahm <franklahm@gmail.com>
+  Copyright (c) 2012-2014 Ralph Boehme
 
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
@@ -12,6 +12,8 @@
   GNU General Public License for more details.
 */
 
+#define USE_LIST
+
 #ifdef HAVE_CONFIG_H
 #include "config.h"
 #endif /* HAVE_CONFIG_H */
 #include <errno.h>
 #include <stdbool.h>
 #include <inttypes.h>
+#include <time.h>
+#include <utime.h>
 
+#include <atalk/list.h>
 #include <atalk/errchk.h>
 #include <atalk/util.h>
 #include <atalk/logger.h>
 #include <atalk/byteorder.h>
 #include <atalk/netatalk_conf.h>
 #include <atalk/volume.h>
+#include <atalk/spotlight.h>
+
+#include "directory.h"
+#include "etc/spotlight/sparql_parser.h"
+
+#define MAX_SL_RESULTS 20
+
+static char *tracker_to_unix_path(TALLOC_CTX *mem_ctx, const char *uri);
+static int cnid_comp_fn(const void *p1, const void *p2);
+static bool create_result_handle(slq_t *slq);
+static bool add_filemeta(sl_array_t *reqinfo,
+                         sl_array_t *fm_array,
+                         const char *path,
+                         const struct stat *sp);
+
+/************************************************
+ * Misc utility functions
+ ************************************************/
 
-#include "spotlight.h"
-
-/**************************************************************************************************
- * RPC data marshalling and unmarshalling
- **************************************************************************************************/
-
-/* FPSpotlightRPC subcommand codes */
-#define SPOTLIGHT_CMD_FLAGS   2
-#define SPOTLIGHT_CMD_RPC     3
-#define SPOTLIGHT_CMD_VOLPATH 4
-
-/* Spotlight epoch is UNIX epoch minus SPOTLIGHT_TIME_DELTA */
-#define SPOTLIGHT_TIME_DELTA INT64_C(280878921600U)
-
-#define SQ_TYPE_NULL    0x0000
-#define SQ_TYPE_COMPLEX 0x0200
-#define SQ_TYPE_INT64   0x8400
-#define SQ_TYPE_BOOL    0x0100
-#define SQ_TYPE_FLOAT   0x8500
-#define SQ_TYPE_DATA    0x0700
-#define SQ_TYPE_CNIDS   0x8700
-#define SQ_TYPE_UUID    0x0e00
-#define SQ_TYPE_DATE    0x8600
-
-#define SQ_CPX_TYPE_ARRAY              0x0a00
-#define SQ_CPX_TYPE_STRING             0x0c00
-#define SQ_CPX_TYPE_UTF16_STRING       0x1c00
-#define SQ_CPX_TYPE_DICT               0x0d00
-#define SQ_CPX_TYPE_CNIDS              0x1a00
-#define SQ_CPX_TYPE_FILEMETA           0x1b00
-
-#define SUBQ_SAFETY_LIM 20
-
-/* Can be ored and used as flags */
-#define SL_ENC_LITTLE_ENDIAN 1
-#define SL_ENC_BIG_ENDIAN    2
-#define SL_ENC_UTF_16        4
-
-static uint64_t spotlight_ntoh64(const char *buf, int encoding)
+static char *tab_level(TALLOC_CTX *mem_ctx, int level)
 {
-       if (encoding == SL_ENC_LITTLE_ENDIAN)
-               return LVAL(buf, 0);
-       else
-        return ntoh64(LVAL(buf, 0));
+    int i;
+    char *string = talloc_array(mem_ctx, char, level + 1);
+
+    for (i = 0; i < level; i++) {
+        string[i] = '\t';
+    }
+
+    string[i] = '\0';
+    return string;
 }
 
-#if 0
-static gdouble
-spotlight_ntohieee_double(tvbuff_t *tvb, gint offset, guint encoding)
+static char *dd_dump(DALLOC_CTX *dd, int nestinglevel)
 {
-       if (encoding == ENC_LITTLE_ENDIAN)
-               return tvb_get_letohieee_double(tvb, offset);
-       else
-               return tvb_get_ntohieee_double(tvb, offset);
+    const char *type;
+    int n;
+    uint64_t i;
+    sl_bool_t bl;
+    sl_time_t t;
+    struct tm *tm;
+    char datestring[256];
+    sl_cnids_t cnids;
+    char *logstring, *nested_logstring;
+    char *tab_string1, *tab_string2;
+
+    tab_string1 = tab_level(dd, nestinglevel);
+    tab_string2 = tab_level(dd, nestinglevel + 1);
+    if (tab_string1 == NULL || tab_string2 == NULL) {
+        return NULL;
+    }
+
+    logstring = talloc_asprintf(dd,
+                                "%s%s(#%lu): {\n",
+                                tab_string1,
+                                talloc_get_name(dd),
+                                talloc_array_length(dd->dd_talloc_array));
+
+    for (n = 0; n < talloc_array_length(dd->dd_talloc_array); n++) {
+        type = talloc_get_name(dd->dd_talloc_array[n]);
+        if (strequal(type, "DALLOC_CTX")
+            || strequal(type, "sl_array_t")
+            || strequal(type, "sl_filemeta_t")
+            || strequal(type, "sl_dict_t")) {
+            nested_logstring = dd_dump(dd->dd_talloc_array[n],
+                                       nestinglevel + 1);
+            if (!nested_logstring) {
+                return NULL;
+            }
+            logstring = talloc_strdup_append(logstring,
+                                             nested_logstring);
+            if (!logstring) {
+                return NULL;
+            }
+        } else if (strequal(type, "uint64_t")) {
+            memcpy(&i, dd->dd_talloc_array[n], sizeof(uint64_t));
+            logstring = talloc_asprintf_append(
+                logstring,
+                "%suint64_t: 0x%04" PRIx64 "\n",
+                tab_string2, i);
+            if (!logstring) {
+                return NULL;
+            }
+        } else if (strequal(type, "char *")) {
+            logstring = talloc_asprintf_append(
+                logstring,
+                "%sstring: %s\n",
+                tab_string2,
+                (char *)dd->dd_talloc_array[n]);
+            if (!logstring) {
+                return NULL;
+            }
+        } else if (strequal(type, "smb_ucs2_t *")) {
+            logstring = talloc_asprintf_append(
+                logstring,
+                "%sUTF16-string: %s\n",
+                tab_string2,
+                (char *)dd->dd_talloc_array[n]);
+            if (!logstring) {
+                return NULL;
+            }
+        } else if (strequal(type, "sl_bool_t")) {
+            memcpy(&bl, dd->dd_talloc_array[n], sizeof(sl_bool_t));
+            logstring = talloc_asprintf_append(
+                logstring,
+                "%sbool: %s\n",
+                tab_string2,
+                bl ? "true" : "false");
+            if (!logstring) {
+                return NULL;
+            }
+        } else if (strequal(type, "sl_nil_t")) {
+            logstring = talloc_asprintf_append(
+                logstring,
+                "%snil\n",
+                tab_string2);
+            if (!logstring) {
+                return NULL;
+            }
+        } else if (strequal(type, "sl_time_t")) {
+            memcpy(&t, dd->dd_talloc_array[n], sizeof(sl_time_t));
+            tm = localtime(&t.tv_sec);
+            strftime(datestring,
+                     sizeof(datestring),
+                     "%Y-%m-%d %H:%M:%S", tm);
+            logstring = talloc_asprintf_append(
+                logstring,
+                "%ssl_time_t: %s.%06lu\n",
+                tab_string2,
+                datestring,
+                (unsigned long)t.tv_usec);
+            if (!logstring) {
+                return NULL;
+            }
+        } else if (strequal(type, "sl_cnids_t")) {
+            memcpy(&cnids, dd->dd_talloc_array[n], sizeof(sl_cnids_t));
+            logstring = talloc_asprintf_append(
+                logstring,
+                "%sCNIDs: unkn1: 0x%" PRIx16 ", unkn2: 0x%" PRIx32 "\n",
+                tab_string2,
+                cnids.ca_unkn1,
+                cnids.ca_context);
+            if (!logstring) {
+                return NULL;
+            }
+            if (cnids.ca_cnids) {
+                nested_logstring = dd_dump(
+                    cnids.ca_cnids,
+                    nestinglevel + 2);
+                if (!nested_logstring) {
+                    return NULL;
+                }
+                logstring = talloc_strdup_append(logstring,
+                                                 nested_logstring);
+                if (!logstring) {
+                    return NULL;
+                }
+            }
+        } else {
+            logstring = talloc_asprintf_append(
+                logstring,
+                "%stype: %s\n",
+                tab_string2,
+                type);
+            if (!logstring) {
+                return NULL;
+            }
+        }
+    }
+    logstring = talloc_asprintf_append(logstring,
+                                       "%s}\n",
+                                       tab_string1);
+    if (!logstring) {
+        return NULL;
+    }
+    return logstring;
 }
 
-/*
-* Returns the UTF-16 string encoding, by checking the 2-byte byte order mark.
-* If there is no byte order mark, -1 is returned.
-*/
-static guint
-spotlight_get_utf16_string_encoding(tvbuff_t *tvb, gint offset, gint query_length, guint encoding) {
-       guint utf16_encoding;
-
-       /* check for byte order mark */
-       utf16_encoding = ENC_BIG_ENDIAN;
-       if (query_length >= 2) {
-               guint16 byte_order_mark;
-               if (encoding == ENC_LITTLE_ENDIAN)
-                       byte_order_mark = tvb_get_letohs(tvb, offset);
-               else
-                       byte_order_mark = tvb_get_ntohs(tvb, offset);
-
-               if (byte_order_mark == 0xFFFE) {
-                       utf16_encoding = ENC_BIG_ENDIAN | ENC_UTF_16;
-               }
-               else if (byte_order_mark == 0xFEFF) {
-                       utf16_encoding = ENC_LITTLE_ENDIAN | ENC_UTF_16;
-               }
-       }
-
-       return utf16_encoding;
+static int cnid_comp_fn(const void *p1, const void *p2)
+{
+    const uint64_t *cnid1 = p1, *cnid2 = p2;
+    if (*cnid1 == *cnid2) {
+        return 0;
+    }
+    if (*cnid1 < *cnid2) {
+        return -1;
+    }
+    return 1;
 }
 
-static gint
-spotlight_int64(tvbuff_t *tvb, proto_tree *tree, gint offset, guint encoding)
+static int sl_createCNIDArray(slq_t *slq, const DALLOC_CTX *p)
 {
-       gint count, i;
-       guint64 query_data64;
+    EC_INIT;
+    uint64_t *cnids = NULL;
 
-       query_data64 = spotlight_ntoh64(tvb, offset, encoding);
-       count = query_data64 >> 32;
-       offset += 8;
+    EC_NULL( cnids = talloc_array(slq, uint64_t, talloc_array_length(p)) );
 
-       i = 0;
-       while (i++ < count) {
-               query_data64 = spotlight_ntoh64(tvb, offset, encoding);
-               proto_tree_add_text(tree, tvb, offset, 8, "int64: 0x%016" G_GINT64_MODIFIER "x", query_data64);
-               offset += 8;
-       }
+    for (int i = 0; i < talloc_array_length(p); i++) {
+        memcpy(&cnids[i], p->dd_talloc_array[i], sizeof(uint64_t));
+    }
+    qsort(cnids, talloc_array_length(p), sizeof(uint64_t), cnid_comp_fn);
 
-       return count;
+    slq->slq_cnids = cnids;
+    slq->slq_cnids_num = talloc_array_length(p);
+
+EC_CLEANUP:
+    if (ret != 0) {
+        if (cnids)
+            talloc_free(cnids);
+    }
+    EC_EXIT;
 }
 
-static gint
-spotlight_date(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, gint offset, guint encoding)
+static char *tracker_to_unix_path(TALLOC_CTX *mem_ctx, const char *uri)
 {
-       gint count, i;
-       guint64 query_data64;
-       nstime_t t;
-
-       query_data64 = spotlight_ntoh64(tvb, offset, encoding);
-       count = query_data64 >> 32;
-       offset += 8;
-
-       if (count > SUBQ_SAFETY_LIM) {
-               expert_add_info_format(pinfo, tree, PI_MALFORMED, PI_ERROR,
-                                                          "Subquery count (%d) > safety limit (%d)", count, SUBQ_SAFETY_LIM);
-               return -1;
-       }
-
-       i = 0;
-       while (i++ < count) {
-               query_data64 = spotlight_ntoh64(tvb, offset, encoding) >> 24;
-               t.secs = query_data64 - SPOTLIGHT_TIME_DELTA;
-               t.nsecs = 0;
-               proto_tree_add_time(tree, hf_afp_spotlight_date, tvb, offset, 8, &t);
-               offset += 8;
-       }
-
-       return count;
+    GFile *f;
+    char *path;
+    char *talloc_path = NULL;
+
+    f = g_file_new_for_uri(uri);
+    if (!f) {
+        return NULL;
+    }
+
+    path = g_file_get_path(f);
+    g_object_unref(f);
+
+    if (!path) {
+        return NULL;
+    }
+
+    talloc_path = talloc_strdup(mem_ctx, path);
+    g_free(path);
+
+    return talloc_path;
 }
 
-static gint
-spotlight_uuid(tvbuff_t *tvb, proto_tree *tree, gint offset, guint encoding)
+/**
+ * Add requested metadata for a query result element
+ *
+ * This could be rewritten to something more sophisticated like
+ * querying metadata from Tracker.
+ *
+ * If path or sp is NULL, simply add nil values for all attributes.
+ **/
+static bool add_filemeta(sl_array_t *reqinfo,
+                         sl_array_t *fm_array,
+                         const char *path,
+                         const struct stat *sp)
 {
-       gint count, i;
-       guint64 query_data64;
+    sl_array_t *meta;
+    sl_nil_t nil;
+    int i, metacount;
+    uint64_t uint64var;
+    sl_time_t sl_time;
+    char *p, *name;
+
+    metacount = talloc_array_length(reqinfo->dd_talloc_array);
+    if (metacount == 0 || path == NULL || sp == NULL) {
+        dalloc_add_copy(fm_array, &nil, sl_nil_t);
+        return true;
+    }
 
-       query_data64 = spotlight_ntoh64(tvb, offset, encoding);
-       count = query_data64 >> 32;
-       offset += 8;
+    meta = talloc_zero(fm_array, sl_array_t);
+
+    for (i = 0; i < metacount; i++) {
+        if (strequal(reqinfo->dd_talloc_array[i], "kMDItemDisplayName")
+            || strequal(reqinfo->dd_talloc_array[i], "kMDItemFSName")) {
+            if ((p = strrchr(path, '/'))) {
+                name = dalloc_strdup(meta, p + 1);
+                dalloc_add(meta, name, "char *");
+            }
+        } else if (strequal(reqinfo->dd_talloc_array[i],
+                            "kMDItemPath")) {
+            name = dalloc_strdup(meta, path);
+            dalloc_add(meta, name, "char *");
+        } else if (strequal(reqinfo->dd_talloc_array[i],
+                            "kMDItemFSSize")) {
+            uint64var = sp->st_size;
+            dalloc_add_copy(meta, &uint64var, uint64_t);
+        } else if (strequal(reqinfo->dd_talloc_array[i],
+                            "kMDItemFSOwnerUserID")) {
+            uint64var = sp->st_uid;
+            dalloc_add_copy(meta, &uint64var, uint64_t);
+        } else if (strequal(reqinfo->dd_talloc_array[i],
+                            "kMDItemFSOwnerGroupID")) {
+            uint64var = sp->st_gid;
+            dalloc_add_copy(meta, &uint64var, uint64_t);
+        } else if (strequal(reqinfo->dd_talloc_array[i],
+                            "kMDItemFSContentChangeDate")) {
+            sl_time.tv_sec = sp->st_mtime;
+            dalloc_add_copy(meta, &sl_time, sl_time_t);
+        } else {
+            dalloc_add_copy(meta, &nil, sl_nil_t);
+        }
+    }
+
+    dalloc_add(fm_array, meta, sl_array_t);
+    return true;
+}
+
+/**
+ * Allocate result handle used in the async Tracker cursor result
+ * handler for storing results
+ **/
+static bool create_result_handle(slq_t *slq)
+{
+    sl_nil_t nil = 0;
+    struct sl_rslts *query_results;
+
+    if (slq->query_results) {
+        LOG(log_error, logtype_sl,"unexpected existing result handle");
+        return false;
+    }
+
+    query_results = talloc_zero(slq, struct sl_rslts);
 
-       i = 0;
-       while (i++ < count) {
-               proto_tree_add_item(tree, hf_afp_spotlight_uuid, tvb, offset, 16, ENC_BIG_ENDIAN);
-               offset += 16;
-       }
+    /* CNIDs */
+    query_results->cnids = talloc_zero(query_results, sl_cnids_t);
+    if (query_results->cnids == NULL) {
+        return false;
+    }
+    query_results->cnids->ca_cnids = talloc_zero(query_results->cnids,
+                                                 DALLOC_CTX);
+    if (query_results->cnids->ca_cnids == NULL) {
+        return false;
+    }
+
+    query_results->cnids->ca_unkn1 = 0xadd;
+    query_results->cnids->ca_context = slq->slq_ctx2;
+
+    /* FileMeta */
+    query_results->fm_array = talloc_zero(query_results, sl_array_t);
+    if (query_results->fm_array == NULL) {
+        return false;
+    }
 
-       return count;
+    /* For some reason the list of results always starts with a nil entry */
+    dalloc_add_copy(query_results->fm_array, &nil, sl_nil_t);
+
+    slq->query_results = query_results;
+    return true;
 }
 
-static gint
-spotlight_float(tvbuff_t *tvb, proto_tree *tree, gint offset, guint encoding)
+static bool add_results(sl_array_t *array, slq_t *slq)
 {
-       gint count, i;
-       guint64 query_data64;
-       gdouble fval;
-
-       query_data64 = spotlight_ntoh64(tvb, offset, encoding);
-       count = query_data64 >> 32;
-       offset += 8;
-
-       i = 0;
-       while (i++ < count) {
-               fval = spotlight_ntohieee_double(tvb, offset, encoding);
-               proto_tree_add_text(tree, tvb, offset, 8, "float: %f", fval);
-               offset += 8;
-       }
-
-       return count;
+    sl_filemeta_t *fm;
+    uint64_t status = 0;
+
+    /* FileMeta */
+    fm = talloc_zero(array, sl_filemeta_t);
+    if (!fm) {
+        return false;
+    }
+
+    dalloc_add_copy(array, &status, uint64_t);
+    dalloc_add(array, slq->query_results->cnids, sl_cnids_t);
+    if (slq->query_results->num_results > 0) {
+        dalloc_add(fm, slq->query_results->fm_array, sl_array_t);
+    }
+    dalloc_add(array, fm, sl_filemeta_t);
+
+    /* This ensure the results get clean up after been sent to the client */
+    talloc_steal(array, slq->query_results);
+    slq->query_results = NULL;
+
+    if (!create_result_handle(slq)) {
+        LOG(log_error, logtype_sl, "couldn't add result handle");
+        slq->slq_state = SLQ_STATE_ERROR;
+        return false;
+    }
+
+    return true;
 }
 
-static gint
-spotlight_CNID_array(tvbuff_t *tvb, proto_tree *tree, gint offset, guint encoding)
+/******************************************************************************
+ * Spotlight queries
+ ******************************************************************************/
+
+static ATALK_LIST_HEAD(sl_queries);
+static ATALK_LIST_HEAD(sl_cancelled_queries);
+
+/**
+ * Add a query to the list of active queries
+ **/
+static void slq_add(slq_t *slq)
 {
-       gint count;
-       guint64 query_data64;
-       guint16 unknown1;
-       guint32 unknown2;
-
-       query_data64 = spotlight_ntoh64(tvb, offset, encoding);
-       count = query_data64 & 0xffff;
-       unknown1 = (query_data64 & 0xffff0000) >> 16;
-       unknown2 = query_data64 >> 32;
-
-       proto_tree_add_text(tree, tvb, offset + 2, 2, "unknown1: 0x%04" G_GINT16_MODIFIER "x",
-               unknown1);
-       proto_tree_add_text(tree, tvb, offset + 4, 4, "unknown2: 0x%08" G_GINT32_MODIFIER "x",
-               unknown2);
-       offset += 8;
-
-
-       while (count --) {
-               query_data64 = spotlight_ntoh64(tvb, offset, encoding);
-               proto_tree_add_text(tree, tvb, offset, 8, "CNID: %" G_GINT64_MODIFIER "u",
-                       query_data64);
-               offset += 8;
-       }
-
-       return 0;
+    list_add(&(slq->slq_list), &sl_queries);
 }
 
-static const char *spotlight_get_qtype_string(guint64 query_type)
+/**
+ * Add a query to the list of active queries
+ **/
+static void slq_cancelled_add(slq_t *slq)
 {
-       switch (query_type) {
-       case SQ_TYPE_NULL:
-               return "null";
-       case SQ_TYPE_COMPLEX:
-               return "complex";
-       case SQ_TYPE_INT64:
-               return "int64";
-       case SQ_TYPE_BOOL:
-               return "bool";
-       case SQ_TYPE_FLOAT:
-               return "float";
-       case SQ_TYPE_DATA:
-               return "data";
-       case SQ_TYPE_CNIDS:
-               return "CNIDs";
-       default:
-               return "unknown";
-       }
+    list_add(&(slq->slq_list), &sl_cancelled_queries);
 }
 
-static const char *spotlight_get_cpx_qtype_string(guint64 cpx_query_type)
+/**
+ * Remove a query from the active list
+ **/
+static void slq_remove(slq_t *slq)
 {
-       switch (cpx_query_type) {
-       case SQ_CPX_TYPE_ARRAY:
-               return "array";
-       case SQ_CPX_TYPE_STRING:
-               return "string";
-       case SQ_CPX_TYPE_UTF16_STRING:
-               return "utf-16 string";
-       case SQ_CPX_TYPE_DICT:
-               return "dictionary";
-       case SQ_CPX_TYPE_CNIDS:
-               return "CNIDs";
-       case SQ_CPX_TYPE_FILEMETA:
-               return "FileMeta";
-       default:
-               return "unknown";
-       }
+    struct list_head *p;
+    slq_t *q = NULL;
+
+    list_for_each(p, &sl_queries) {
+        q = list_entry(p, slq_t, slq_list);
+        if ((q->slq_ctx1 == slq->slq_ctx1) && (q->slq_ctx2 == slq->slq_ctx2)) {
+            list_del(p);
+            break;
+        }
+    }
+
+    return;
 }
 
-static gint
-spotlight_dissect_query_loop(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, gint offset,
-                             guint64 cpx_query_type, gint count, gint toc_offset, guint encoding)
+static slq_t *slq_for_ctx(uint64_t ctx1, uint64_t ctx2)
 {
-       gint i, j;
-       gint subquery_count;
-       gint toc_index;
-       guint64 query_data64;
-       gint query_length;
-       guint64 query_type;
-       guint64 complex_query_type;
-       guint unicode_encoding;
-       guint8 mark_exists;
-
-       proto_item *item_query;
-       proto_tree *sub_tree;
-
-       /*
-        * This loops through a possibly nested query data structure.
-        * The outermost one is always without count and called from
-        * dissect_spotlight() with count = INT_MAX thus the while (...)
-        * loop terminates if (offset >= toc_offset).
-        * If nested structures are found, these will have an encoded element
-        * count which is used in a recursive call to
-        * spotlight_dissect_query_loop as count parameter, thus in this case
-        * the while (...) loop will terminate when count reaches 0.
-        */
-       while ((offset < (toc_offset - 8)) && (count > 0)) {
-               query_data64 = spotlight_ntoh64(tvb, offset, encoding);
-               query_length = (query_data64 & 0xffff) * 8;
-               if (query_length == 0) {
-                       /* XXX - report this as an error */
-                       break;
-               }
-               query_type = (query_data64 & 0xffff0000) >> 16;
-
-               switch (query_type) {
-               case SQ_TYPE_COMPLEX:
-                       toc_index = (gint)((query_data64 >> 32) - 1);
-                       query_data64 = spotlight_ntoh64(tvb, toc_offset + toc_index * 8, encoding);
-                       complex_query_type = (query_data64 & 0xffff0000) >> 16;
-
-                       switch (complex_query_type) {
-                       case SQ_CPX_TYPE_ARRAY:
-                       case SQ_CPX_TYPE_DICT:
-                               subquery_count = (gint)(query_data64 >> 32);
-                               item_query = proto_tree_add_text(tree, tvb, offset, query_length,
-                                                                "%s, toc index: %u, children: %u",
-                                                                spotlight_get_cpx_qtype_string(complex_query_type),
-                                                                toc_index + 1,
-                                                                subquery_count);
-                               break;
-                       case SQ_CPX_TYPE_STRING:
-                               subquery_count = 1;
-                               query_data64 = spotlight_ntoh64(tvb, offset + 8, encoding);
-                               query_length = (query_data64 & 0xffff) * 8;
-                               item_query = proto_tree_add_text(tree, tvb, offset, query_length + 8,
-                                                                "%s, toc index: %u, string: '%s'",
-                                                                spotlight_get_cpx_qtype_string(complex_query_type),
-                                                                toc_index + 1,
-                                                                tvb_get_ephemeral_string(tvb, offset + 16, query_length - 8));
-                               break;
-                       case SQ_CPX_TYPE_UTF16_STRING:
-                               /*
-                               * This is an UTF-16 string.
-                               * Dissections show the typical byte order mark 0xFFFE or 0xFEFF, respectively.
-                               * However the existence of such a mark can not be assumed.
-                               * If the mark is missing, big endian encoding is assumed.
-                               */
-
-                               subquery_count = 1;
-                               query_data64 = spotlight_ntoh64(tvb, offset + 8, encoding);
-                               query_length = (query_data64 & 0xffff) * 8;
-
-                               unicode_encoding = spotlight_get_utf16_string_encoding(tvb, offset + 16, query_length - 8, encoding);
-                               mark_exists = (unicode_encoding & ENC_UTF_16);
-                               unicode_encoding &= ~ENC_UTF_16;
-
-                               item_query = proto_tree_add_text(tree, tvb, offset, query_length + 8,
-                                                                "%s, toc index: %u, utf-16 string: '%s'",
-                                                                spotlight_get_cpx_qtype_string(complex_query_type),
-                                                                toc_index + 1,
-                                                                tvb_get_ephemeral_unicode_string(tvb, offset + (mark_exists ? 18 : 16),
-                                                                query_length - (mark_exists? 10 : 8), unicode_encoding));
-                               break;
-                       default:
-                               subquery_count = 1;
-                               item_query = proto_tree_add_text(tree, tvb, offset, query_length,
-                                                                "type: %s (%s), toc index: %u, children: %u",
-                                                                spotlight_get_qtype_string(query_type),
-                                                                spotlight_get_cpx_qtype_string(complex_query_type),
-                                                                toc_index + 1,
-                                                                subquery_count);
-                               break;
-                       }
-
-                       sub_tree = proto_item_add_subtree(item_query, ett_afp_spotlight_query_line);
-                       offset += 8;
-                       offset = spotlight_dissect_query_loop(tvb, pinfo, sub_tree, offset, complex_query_type, subquery_count, toc_offset, encoding);
-                       count--;
-                       break;
-               case SQ_TYPE_NULL:
-                       subquery_count = (gint)(query_data64 >> 32);
-                       if (subquery_count > count) {
-                               item_query = proto_tree_add_text(tree, tvb, offset, query_length, "null");
-                               expert_add_info_format(pinfo, item_query, PI_MALFORMED, PI_ERROR,
-                                       "Subquery count (%d) > query count (%d)", subquery_count, count);
-                               count = 0;
-                       } else if (subquery_count > 20) {
-                               item_query = proto_tree_add_text(tree, tvb, offset, query_length, "null");
-                               expert_add_info_format(pinfo, item_query, PI_PROTOCOL, PI_WARN,
-                                       "Abnormal number of subqueries (%d)", subquery_count);
-                               count -= subquery_count;
-                       } else {
-                               for (i = 0; i < subquery_count; i++, count--)
-                                       proto_tree_add_text(tree, tvb, offset, query_length, "null");
-                       }
-                       offset += query_length;
-                       break;
-               case SQ_TYPE_BOOL:
-                       proto_tree_add_text(tree, tvb, offset, query_length, "bool: %s",
-                                                        (query_data64 >> 32) ? "true" : "false");
-                       count--;
-                       offset += query_length;
-                       break;
-               case SQ_TYPE_INT64:
-                       item_query = proto_tree_add_text(tree, tvb, offset, 8, "int64");
-                       sub_tree = proto_item_add_subtree(item_query, ett_afp_spotlight_query_line);
-                       j = spotlight_int64(tvb, sub_tree, offset, encoding);
-                       count -= j;
-                       offset += query_length;
-                       break;
-               case SQ_TYPE_UUID:
-                       item_query = proto_tree_add_text(tree, tvb, offset, 8, "UUID");
-                       sub_tree = proto_item_add_subtree(item_query, ett_afp_spotlight_query_line);
-                       j = spotlight_uuid(tvb, sub_tree, offset, encoding);
-                       count -= j;
-                       offset += query_length;
-                       break;
-               case SQ_TYPE_FLOAT:
-                       item_query = proto_tree_add_text(tree, tvb, offset, 8, "float");
-                       sub_tree = proto_item_add_subtree(item_query, ett_afp_spotlight_query_line);
-                       j = spotlight_float(tvb, sub_tree, offset, encoding);
-                       count -= j;
-                       offset += query_length;
-                       break;
-               case SQ_TYPE_DATA:
-                       switch (cpx_query_type) {
-                       case SQ_CPX_TYPE_STRING:
-                               proto_tree_add_text(tree, tvb, offset, query_length, "string: '%s'",
-                                                   tvb_get_ephemeral_string(tvb, offset + 8, query_length - 8));
-                               break;
-                       case SQ_CPX_TYPE_UTF16_STRING: {
-                               /* description see above */
-                               unicode_encoding = spotlight_get_utf16_string_encoding(tvb, offset + 8, query_length, encoding);
-                               mark_exists = (unicode_encoding & ENC_UTF_16);
-                               unicode_encoding &= ~ENC_UTF_16;
-
-                               proto_tree_add_text(tree, tvb, offset, query_length, "utf-16 string: '%s'",
-                                                   tvb_get_ephemeral_unicode_string(tvb, offset + (mark_exists ? 10 : 8),
-                                                               query_length - (mark_exists? 10 : 8), unicode_encoding));
-                               break;
-                       }
-                       case SQ_CPX_TYPE_FILEMETA:
-                               if (query_length <= 8) {
-                                       /* item_query = */ proto_tree_add_text(tree, tvb, offset, query_length, "filemeta (empty)");
-                               } else {
-                                       item_query = proto_tree_add_text(tree, tvb, offset, query_length, "filemeta");
-                                       sub_tree = proto_item_add_subtree(item_query, ett_afp_spotlight_query_line);
-                                       (void)dissect_spotlight(tvb, pinfo, sub_tree, offset + 8);
-                               }
-                               break;
-                       }
-                       count--;
-                       offset += query_length;
-                       break;
-               case SQ_TYPE_CNIDS:
-                       if (query_length <= 8) {
-                               /* item_query = */ proto_tree_add_text(tree, tvb, offset, query_length, "CNID Array (empty)");
-                       } else {
-                               item_query = proto_tree_add_text(tree, tvb, offset, query_length, "CNID Array");
-                               sub_tree = proto_item_add_subtree(item_query, ett_afp_spotlight_query_line);
-                               spotlight_CNID_array(tvb, sub_tree, offset + 8, encoding);
-                       }
-                       count--;
-                       offset += query_length;
-                       break;
-               case SQ_TYPE_DATE:
-                       if ((j = spotlight_date(tvb, pinfo, tree, offset, encoding)) == -1)
-                               return offset;
-                       count -= j;
-                       offset += query_length;
-                       break;
-               default:
-                       proto_tree_add_text(tree, tvb, offset, query_length, "type: %s",
-                                                        spotlight_get_qtype_string(query_type));
-                       count--;
-                       offset += query_length;
-                       break;
-               }
-       }
-
-       return offset;
+    slq_t *q = NULL;
+    struct list_head *p;
+
+    list_for_each(p, &sl_queries) {
+        q = list_entry(p, slq_t, slq_list);
+        if ((q->slq_ctx1 == ctx1) && (q->slq_ctx2 == ctx2)) {
+            break;
+        }
+        q = NULL;
+    }
+
+    return q;
 }
 
-static gint
-dissect_spotlight(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, gint offset)
+/**
+ * Remove a query from the active queue and free it
+ **/
+static void slq_destroy(slq_t *slq)
 {
-       guint encoding;
-       gint i;
-       guint64 toc_offset;
-       guint64 querylen;
-       gint toc_entries;
-       guint64 toc_entry;
-
-       proto_item *item_queries_data;
-       proto_tree *sub_tree_queries;
-       proto_item *item_toc;
-       proto_tree *sub_tree_toc;
-
-       if (strncmp(tvb_get_ephemeral_string(tvb, offset, 8), "md031234", 8) == 0)
-               encoding = ENC_BIG_ENDIAN;
-       else
-               encoding = ENC_LITTLE_ENDIAN;
-       proto_tree_add_text(tree,
-                           tvb,
-                           offset,
-                           8,
-                           "Endianess: %s",
-                           encoding == ENC_BIG_ENDIAN ?
-                           "Big Endian" : "Litte Endian");
-       offset += 8;
-
-       toc_offset = (spotlight_ntoh64(tvb, offset, encoding) >> 32) * 8;
-       if (toc_offset < 8) {
-               proto_tree_add_text(tree,
-                                   tvb,
-                                   offset,
-                                   8,
-                                   "ToC Offset: %" G_GINT64_MODIFIER "u < 8 (bogus)",
-                                   toc_offset);
-               return -1;
-       }
-       toc_offset -= 8;
-       if (offset + toc_offset + 8 > G_MAXINT) {
-               proto_tree_add_text(tree,
-                                   tvb,
-                                   offset,
-                                   8,
-                                   "ToC Offset: %" G_GINT64_MODIFIER "u > %u (bogus)",
-                                   toc_offset,
-                                   G_MAXINT - 8 - offset);
-               return -1;
-       }
-       querylen = (spotlight_ntoh64(tvb, offset, encoding) & 0xffffffff) * 8;
-       if (querylen < 8) {
-               proto_tree_add_text(tree,
-                                   tvb,
-                                   offset,
-                                   8,
-                                   "ToC Offset: %" G_GINT64_MODIFIER "u Bytes, Query length: %" G_GINT64_MODIFIER "u < 8 (bogus)",
-                                   toc_offset,
-                                   querylen);
-               return -1;
-       }
-       querylen -= 8;
-       if (querylen > G_MAXINT) {
-               proto_tree_add_text(tree,
-                                   tvb,
-                                   offset,
-                                   8,
-                                   "ToC Offset: %" G_GINT64_MODIFIER "u Bytes, Query length: %" G_GINT64_MODIFIER "u > %u (bogus)",
-                                   toc_offset,
-                                   querylen,
-                                   G_MAXINT);
-               return -1;
-       }
-       proto_tree_add_text(tree,
-                           tvb,
-                           offset,
-                           8,
-                           "ToC Offset: %" G_GINT64_MODIFIER "u Bytes, Query length: %" G_GINT64_MODIFIER "u Bytes",
-                           toc_offset,
-                           querylen);
-       offset += 8;
-
-       toc_entries = (gint)(spotlight_ntoh64(tvb, offset + (gint)toc_offset, encoding) & 0xffff);
-
-       item_queries_data = proto_tree_add_text(tree,
-                                               tvb,
-                                               offset,
-                                               (gint)toc_offset,
-                                               "Spotlight RPC data");
-       sub_tree_queries = proto_item_add_subtree(item_queries_data, ett_afp_spotlight_queries);
-
-       /* Queries */
-       offset = spotlight_dissect_query_loop(tvb, pinfo, sub_tree_queries, offset, SQ_CPX_TYPE_ARRAY, INT_MAX, offset + (gint)toc_offset + 8, encoding);
-
-       /* ToC */
-       if (toc_entries < 1) {
-               proto_tree_add_text(tree,
-                                   tvb,
-                                   offset,
-                                   (gint)querylen - (gint)toc_offset,
-                                   "Complex types ToC (%u < 1 - bogus)",
-                                   toc_entries);
-               return -1;
-       }
-       toc_entries -= 1;
-       item_toc = proto_tree_add_text(tree,
-                                      tvb,
-                                      offset,
-                                      (gint)querylen - (gint)toc_offset,
-                                      "Complex types ToC (%u entries)",
-                                      toc_entries);
-       sub_tree_toc = proto_item_add_subtree(item_toc, ett_afp_spotlight_toc);
-       proto_tree_add_text(sub_tree_toc, tvb, offset, 2, "Number of entries (%u)", toc_entries);
-       proto_tree_add_text(sub_tree_toc, tvb, offset + 2, 2, "unknown");
-       proto_tree_add_text(sub_tree_toc, tvb, offset + 4, 4, "unknown");
-
-       offset += 8;
-       for (i = 0; i < toc_entries; i++, offset += 8) {
-               toc_entry = spotlight_ntoh64(tvb, offset, encoding);
-               if ((((toc_entry & 0xffff0000) >> 16) == SQ_CPX_TYPE_ARRAY)
-                   || (((toc_entry & 0xffff0000) >> 16) == SQ_CPX_TYPE_DICT)) {
-                       proto_tree_add_text(sub_tree_toc,
-                                           tvb,
-                                           offset,
-                                           8,
-                                           "%u: count: %" G_GINT64_MODIFIER "u, type: %s, offset: %" G_GINT64_MODIFIER "u",
-                                           i+1,
-                                           toc_entry >> 32,
-                                           spotlight_get_cpx_qtype_string((toc_entry & 0xffff0000) >> 16),
-                                           (toc_entry & 0xffff) * 8);
-               } else if ((((toc_entry & 0xffff0000) >> 16) == SQ_CPX_TYPE_STRING)
-                       || (((toc_entry & 0xffff0000) >> 16) == SQ_CPX_TYPE_UTF16_STRING)) {
-                       proto_tree_add_text(sub_tree_toc,
-                                           tvb,
-                                           offset,
-                                           8,
-                                           "%u: pad byte count: %" G_GINT64_MODIFIER "x, type: %s, offset: %" G_GINT64_MODIFIER "u",
-                                           i+1,
-                                           8 - (toc_entry >> 32),
-                                           spotlight_get_cpx_qtype_string((toc_entry & 0xffff0000) >> 16),
-                                           (toc_entry & 0xffff) * 8);
-               }
-               else {
-                       proto_tree_add_text(sub_tree_toc,
-                                           tvb,
-                                           offset,
-                                           8,
-                                           "%u: unknown: 0x%08" G_GINT64_MODIFIER "x, type: %s, offset: %" G_GINT64_MODIFIER "u",
-                                           i+1,
-                                           toc_entry >> 32,
-                                           spotlight_get_cpx_qtype_string((toc_entry & 0xffff0000) >> 16),
-                                           (toc_entry & 0xffff) * 8);
-               }
-
-
-       }
-
-       return offset;
+    if (slq == NULL) {
+        return;
+    }
+    slq_remove(slq);
+    talloc_free(slq);
 }
-#endif
 
-static DALLOC_CTX *unpack_spotlight(TALLOC_CTX *mem_ctx, char *ibuf, size_t ibuflen)
+/**
+ * Cancel a query
+ **/
+static void slq_cancel(slq_t *slq)
+{
+    g_cancellable_cancel(slq->cancellable);
+    slq->slq_state = SLQ_STATE_CANCEL_PENDING;
+    slq_remove(slq);
+    slq_cancelled_add(slq);
+}
+
+/**
+ * talloc destructor cb
+ **/
+static int slq_free_cb(slq_t *slq)
+{
+    if (slq->tracker_cursor) {
+        g_object_unref(slq->tracker_cursor);
+    }
+    if (slq->cancellable) {
+        g_object_unref(slq->cancellable);
+    }
+    return 0;
+}
+
+/**
+ * Free all cancelled queries
+ **/
+static void slq_cancelled_cleanup(void)
+{
+    struct list_head *p;
+    slq_t *q = NULL;
+
+    list_for_each(p, &sl_cancelled_queries) {
+        q = list_entry(p, slq_t, slq_list);
+        if (q->slq_state == SLQ_STATE_CANCELLED) {
+            list_del(p);
+            talloc_free(q);
+        }
+    }
+
+    return;
+}
+
+/************************************************
+ * Tracker async callbacks
+ ************************************************/
+
+static void tracker_con_cb(GObject      *object,
+                           GAsyncResult *res,
+                           gpointer      user_data)
+{
+    struct sl_ctx *sl_ctx = user_data;
+    GError *error = NULL;
+
+    sl_ctx->tracker_con = tracker_sparql_connection_get_finish(res,
+                                                               &error);
+    if (error) {
+        LOG(log_error, logtype_sl, "Could not connect to Tracker: %s",
+            error->message);
+        sl_ctx->tracker_con = NULL;
+        g_error_free(error);
+        return;
+    }
+
+    LOG(log_info, logtype_sl, "connected to Tracker");
+}
+
+static void tracker_cursor_cb(GObject      *object,
+                              GAsyncResult *res,
+                              gpointer      user_data)
+{
+    GError *error = NULL;
+    slq_t *slq = user_data;
+    gboolean more_results;
+    const gchar *uri;
+    char *path;
+    int result;
+    struct stat sb;
+    uint64_t uint64var;
+    bool ok;
+    cnid_t did, id;
+
+    if (g_cancellable_is_cancelled(slq->cancellable)) {
+        slq->slq_state = SLQ_STATE_CANCELLED;
+        return;
+    }
+
+    more_results = tracker_sparql_cursor_next_finish(slq->tracker_cursor,
+                                                     res,
+                                                     &error);
+
+    if (error) {
+        LOG(log_error, logtype_sl, "Tracker cursor: %s", error->message);
+        g_error_free(error);
+        slq->slq_state = SLQ_STATE_ERROR;
+        return;
+    }
+
+    if (!more_results) {
+        slq->slq_state = SLQ_STATE_DONE;
+        return;
+    }
+
+    uri = tracker_sparql_cursor_get_string(slq->tracker_cursor, 0, NULL);
+    if (uri == NULL) {
+        /*
+         * Not sure how this could happen if
+         * tracker_sparql_cursor_next_finish() returns true, but I've
+         * seen it.
+         */
+        LOG(log_debug, logtype_sl, "no URI for result");
+        goto exit;
+    }
+
+    path = tracker_to_unix_path(slq->query_results, uri);
+    if (path == NULL) {
+        LOG(log_error, logtype_sl, "error converting Tracker URI: %s", uri);
+        slq->slq_state = SLQ_STATE_ERROR;
+        return;
+    }
+
+    result = access(path, R_OK);
+    if (result != 0) {
+        goto exit;
+    }
+
+    id = cnid_for_path(slq->slq_vol->v_cdb, slq->slq_vol->v_path, path, &did);
+    if (id == CNID_INVALID) {
+        LOG(log_error, logtype_sl, "cnid_for_path error: %s", path);
+        goto exit;
+    }
+    uint64var = ntohl(id);
+
+    if (slq->slq_cnids) {
+        ok = bsearch(&uint64var, slq->slq_cnids, slq->slq_cnids_num,
+                     sizeof(uint64_t), cnid_comp_fn);
+        if (!ok) {
+            goto exit;
+        }
+    }
+
+    dalloc_add_copy(slq->query_results->cnids->ca_cnids,
+                    &uint64var, uint64_t);
+    ok = add_filemeta(slq->slq_reqinfo, slq->query_results->fm_array,
+                      path, &sb);
+    if (!ok) {
+        LOG(log_error, logtype_sl, "add_filemeta error");
+        slq->slq_state = SLQ_STATE_ERROR;
+        return;
+    }
+
+    slq->query_results->num_results++;
+
+exit:
+    if (slq->query_results->num_results < MAX_SL_RESULTS) {
+        tracker_sparql_cursor_next_async(slq->tracker_cursor,
+                                         slq->cancellable,
+                                         tracker_cursor_cb,
+                                         slq);
+    }
+}
+
+static void tracker_query_cb(GObject      *object,
+                             GAsyncResult *res,
+                             gpointer      user_data)
+{
+    bool ok;
+    GError *error = NULL;
+    slq_t *slq = user_data;
+
+    if (g_cancellable_is_cancelled(slq->cancellable)) {
+        slq->slq_state = SLQ_STATE_CANCELLED;
+        return;
+    }
+
+    slq->tracker_cursor = tracker_sparql_connection_query_finish(
+        TRACKER_SPARQL_CONNECTION(object),
+        res,
+        &error);
+
+    if (error) {
+        slq->slq_state = SLQ_STATE_ERROR;
+        LOG(log_error, logtype_sl, "Tracker query error: %s", error->message);
+        g_error_free(error);
+        return;
+    }
+
+    slq->slq_state = SLQ_STATE_RESULTS;
+
+    ok = create_result_handle(slq);
+    if (!ok) {
+        LOG(log_error, logtype_sl, "create_result_handle error");
+        slq->slq_state = SLQ_STATE_ERROR;
+        return;
+    }
+
+    tracker_sparql_cursor_next_async(slq->tracker_cursor,
+                                     slq->slq_obj->sl_ctx->cancellable,
+                                     tracker_cursor_cb,
+                                     slq);
+}
+
+/*******************************************************************************
+ * Spotlight RPC functions
+ ******************************************************************************/
+
+static int sl_rpc_fetchPropertiesForContext(const AFPObj *obj,
+                                            const DALLOC_CTX *query,
+                                            DALLOC_CTX *reply,
+                                            const struct vol *v)
 {
     EC_INIT;
-       int len;
-    DALLOC_CTX *query;
 
-    EC_NULL_LOG( query = talloc_zero(mem_ctx, DALLOC_CTX) );
+    char *s;
+    sl_dict_t *dict;
+    sl_array_t *array;
+    sl_uuid_t uuid;
+
+    if (!v->v_uuid) {
+        EC_FAIL_LOG("missing UUID for volume: %s", v->v_localname);
+    }
+    dict = talloc_zero(reply, sl_dict_t);
+
+    /* key/val 1 */
+    s = dalloc_strdup(dict, "kMDSStoreMetaScopes");
+    dalloc_add(dict, s, char *);
+
+    array = talloc_zero(dict, sl_array_t);
+    s = dalloc_strdup(array, "kMDQueryScopeComputer");
+    dalloc_add(array, s, char *);
+    dalloc_add(dict, array, sl_array_t);
+
+    /* key/val 2 */
+    s = dalloc_strdup(dict, "kMDSStorePathScopes");
+    dalloc_add(dict, s, char *);
+
+    array = talloc_zero(dict, sl_array_t);
+    s = dalloc_strdup(array, v->v_path);
+    dalloc_add(array, s, char *);
+    dalloc_add(dict, array, sl_array_t);
+
+    /* key/val 3 */
+    s = dalloc_strdup(dict, "kMDSStoreUUID");
+    dalloc_add(dict, s, char *);
+
+    memcpy(uuid.sl_uuid, v->v_uuid, 16);
+    dalloc_add_copy(dict, &uuid, sl_uuid_t);
+
+    /* key/val 4 */
+    s = dalloc_strdup(dict, "kMDSStoreHasPersistentUUID");
+    dalloc_add(dict, s, char *);
+    sl_bool_t b = true;
+    dalloc_add_copy(dict, &b, sl_bool_t);
+
+    dalloc_add(reply, dict, sl_dict_t);
+
+EC_CLEANUP:
+    EC_EXIT;
+}
+
+static int sl_rpc_openQuery(AFPObj *obj,
+                            const DALLOC_CTX *query,
+                            DALLOC_CTX *reply,
+                            struct vol *v)
+{
+    EC_INIT;
+    char *sl_query;
+    uint64_t *uint64;
+    DALLOC_CTX *reqinfo;
+    sl_array_t *array;
+    sl_cnids_t *cnids;
+    slq_t *slq;
+    char slq_host[MAXPATHLEN + 1];
+    uint16_t convflags = v->v_mtou_flags;
+    uint64_t result;
+    gchar *sparql_query;
+    GError *error = NULL;
+
+    array = talloc_zero(reply, sl_array_t);
+
+    if (obj->sl_ctx->tracker_con == NULL) {
+        EC_FAIL;
+    }
+
+    /* Allocate and initialize query object */
+    slq = talloc_zero(obj->sl_ctx, slq_t);
+    slq->slq_state = SLQ_STATE_NEW;
+    slq->slq_obj = obj;
+    slq->slq_vol = v;
+    slq->slq_allow_expr = obj->options.flags & OPTION_SPOTLIGHT_EXPR ? true : false;
+    slq->slq_result_limit = obj->options.sparql_limit;
+    slq->cancellable = g_cancellable_new();
+    talloc_set_destructor(slq, slq_free_cb);
+
+    LOG(log_debug, logtype_sl, "Spotlight: expr: %s, limit: %" PRIu64,
+        slq->slq_allow_expr ? "yes" : "no", slq->slq_result_limit);
+
+    /* convert spotlight query charset to host charset */
+    sl_query = dalloc_value_for_key(query, "DALLOC_CTX", 0,
+                                    "DALLOC_CTX", 1,
+                                    "kMDQueryString");
+    if (sl_query == NULL) {
+        EC_FAIL;
+    }
+    ret = convert_charset(CH_UTF8_MAC, v->v_volcharset, v->v_maccharset,
+                          sl_query, strlen(sl_query), slq_host, MAXPATHLEN,
+                          &convflags);
+    if (ret == -1) {
+        LOG(log_error, logtype_sl, "charset conversion failed");
+        EC_FAIL;
+    }
+    slq->slq_qstring = talloc_strdup(slq, slq_host);
+    LOG(log_debug, logtype_sl, "Spotlight query: \"%s\"", slq->slq_qstring);
+
+    slq->slq_time = time(NULL);
+    uint64 = dalloc_get(query, "DALLOC_CTX", 0, "DALLOC_CTX", 0, "uint64_t", 1);
+    if (uint64 == NULL) {
+        EC_FAIL;
+    }
+    slq->slq_ctx1 = *uint64;
 
-    ibuf++;
-    ibuflen--;
+    uint64 = dalloc_get(query, "DALLOC_CTX", 0, "DALLOC_CTX", 0, "uint64_t", 2);
+    if (uint64 == NULL) {
+        EC_FAIL;
+    }
+    slq->slq_ctx2 = *uint64;
+
+    reqinfo = dalloc_value_for_key(query, "DALLOC_CTX", 0, "DALLOC_CTX", 1,
+                                   "kMDAttributeArray");
+    if (reqinfo == NULL) {
+        EC_FAIL;
+    }
+    slq->slq_reqinfo = talloc_steal(slq, reqinfo);
+
+    cnids = dalloc_value_for_key(query, "DALLOC_CTX", 0, "DALLOC_CTX", 1,
+                                 "kMDQueryItemArray");
+    if (cnids) {
+        EC_ZERO_LOG( sl_createCNIDArray(slq, cnids->ca_cnids) );
+    }
+
+    ret = map_spotlight_to_sparql_query(slq, &sparql_query);
+    if (ret != 0) {
+        LOG(log_debug, logtype_sl, "mapping retured non-zero");
+        EC_FAIL;
+    }
+    LOG(log_debug, logtype_sl, "SPARQL query: \"%s\"", sparql_query);
+
+    tracker_sparql_connection_query_async(obj->sl_ctx->tracker_con,
+                                          sparql_query,
+                                          slq->cancellable,
+                                          tracker_query_cb,
+                                          slq);
+    if (error) {
+        LOG(log_error, logtype_sl, "Couldn't query the Tracker Store: '%s'",
+            error->message);
+        g_clear_error(&error);
+        EC_FAIL;
+    }
 
+    slq->slq_state = SLQ_STATE_RUNNING;
+    slq_add(slq);
 
 EC_CLEANUP:
     if (ret != 0) {
-        talloc_free(query);
-        query = NULL;
+        slq_destroy(slq);
+        result = UINT64_MAX;
+        ret = 0;
+    } else {
+        result = 0;
     }
-       return query;
+
+    dalloc_add_copy(array, &result, uint64_t);
+    dalloc_add(reply, array, sl_array_t);
+    EC_EXIT;
 }
 
-/**************************************************************************************************
- * AFP functions
- **************************************************************************************************/
-int afp_spotlight_rpc(AFPObj *obj, char *ibuf, size_t ibuflen, char *rbuf, size_t *rbuflen)
+static int sl_rpc_fetchQueryResultsForContext(const AFPObj *obj,
+                                              const DALLOC_CTX *query,
+                                              DALLOC_CTX *reply,
+                                              const struct vol *v)
 {
     EC_INIT;
-    TALLOC_CTX *tmp_ctx = talloc_new(NULL);
-    uint16_t vid;
-    int cmd;
-    int endianess = SL_ENC_LITTLE_ENDIAN;
-    struct vol      *vol;
+    slq_t *slq = NULL;
+    uint64_t *uint64, ctx1, ctx2, status;
+    sl_array_t *array;
+    bool ok;
+
+    array = talloc_zero(reply, sl_array_t);
+    if (array == NULL) {
+        return false;
+    }
 
-    *rbuflen = 0;
+    /* Context */
+    uint64 = dalloc_get(query, "DALLOC_CTX", 0, "DALLOC_CTX", 0, "uint64_t", 1);
+    if (uint64 == NULL) {
+        EC_FAIL;
+    }
+    ctx1 = *uint64;
+    uint64 = dalloc_get(query, "DALLOC_CTX", 0, "DALLOC_CTX", 0, "uint64_t", 2);
+    if (uint64 == NULL) {
+        EC_FAIL;
+    }
+    ctx2 = *uint64;
 
-    ibuf += 2;
-    ibuflen -= 2;
+    /* Get query for context */
+    slq = slq_for_ctx(ctx1, ctx2);
+    if (slq == NULL) {
+        EC_FAIL;
+    }
 
-    vid = SVAL(ibuf, 0);
-    LOG(logtype_default, log_note, "afp_spotlight_rpc(vid: %" PRIu16 ")", vid);
+    switch (slq->slq_state) {
+    case SLQ_STATE_RUNNING:
+    case SLQ_STATE_RESULTS:
+    case SLQ_STATE_DONE:
+        ok = add_results(array, slq);
+        if (!ok) {
+            LOG(log_error, logtype_sl, "error adding results");
+            EC_FAIL;
+        }
+        if (slq->slq_state == SLQ_STATE_RESULTS) {
+            tracker_sparql_cursor_next_async(
+                slq->tracker_cursor,
+                slq->cancellable,
+                tracker_cursor_cb,
+                slq);
+        }
+        break;
 
-    if ((vol = getvolbyvid(vid)) == NULL) {
-        LOG(logtype_default, log_error, "afp_spotlight_rpc: bad volume id: %" PRIu16 ")", vid);
-        ret = AFPERR_ACCESS;
-        goto EC_CLEANUP;
+    case SLQ_STATE_ERROR:
+        LOG(log_error, logtype_sl, "query in error state");
+        EC_FAIL;
+
+    default:
+        LOG(log_error, logtype_sl, "unexpected query state %d", slq->slq_state);
+        EC_FAIL;
     }
 
-    /*    IVAL(ibuf, 2): unknown, always 0x00008004, some flags ? */
+    dalloc_add(reply, array, sl_array_t);
+    EC_EXIT;
 
-    cmd = RIVAL(ibuf, 6);
-    LOG(logtype_default, log_note, "afp_spotlight_rpc(cmd: %d)", cmd);
+EC_CLEANUP:
+    slq_destroy(slq);
+    status = UINT64_MAX;
+    dalloc_add_copy(array, &status, uint64_t);
+    dalloc_add(reply, array, sl_array_t);
+    EC_EXIT;
+}
 
-    /*    IVAL(ibuf, 10: unknown, always 0x00000000 */
+static int sl_rpc_storeAttributesForOIDArray(const AFPObj *obj,
+                                             const DALLOC_CTX *query,
+                                             DALLOC_CTX *reply,
+                                             const struct vol *vol)
+{
+    EC_INIT;
+    uint64_t uint64;
+    sl_array_t *array;
+    sl_cnids_t *cnids;
+    sl_time_t *sl_time;
+    cnid_t id;
+    char *path;
+    struct dir *dir;
+
+    EC_NULL_LOG( cnids = dalloc_get(query, "DALLOC_CTX", 0, "sl_cnids_t", 2) );
+    memcpy(&uint64, cnids->ca_cnids->dd_talloc_array[0], sizeof(uint64_t));
+    id = (cnid_t)uint64;
+    LOG(log_debug, logtype_sl, "CNID: %" PRIu32, id);
+
+    if (htonl(id) == DIRDID_ROOT) {
+        path = vol->v_path;
+    } else if (id < CNID_START) {
+        EC_FAIL;
+    } else {
+        cnid_t did;
+        char buffer[12 + MAXPATHLEN + 1];
+
+        did = htonl(id);
+        EC_NULL_LOG( path = cnid_resolve(vol->v_cdb, &did, buffer, sizeof(buffer)) );
+        EC_NULL_LOG( dir = dirlookup(vol, did) );
+        EC_NEG1_LOG( movecwd(vol, dir) );
+    }
 
-       switch (cmd) {
+    /*
+     * We're possibly supposed to update attributes in two places: the
+     * database and the filesystem.  Due to the lack of documentation
+     * and not yet implemented database updates, we cherry pick attributes
+     * that seems to be candidates for updating filesystem metadata.
+     */
+
+    if ((sl_time = dalloc_value_for_key(query, "DALLOC_CTX", 0, "DALLOC_CTX", 1, "DALLOC_CTX", 1, "kMDItemFSContentChangeDate"))) {
+        struct utimbuf utimes;
+        utimes.actime = utimes.modtime = sl_time->tv_sec;
+        utime(path, &utimes);
+    }
 
-       case SPOTLIGHT_CMD_VOLPATH: {
-        RSIVAL(rbuf, 0, ntohs(vid));
-        RSIVAL(rbuf, 4, 0);
-        int len = strlen(vol->v_path) + 1;
-        strncpy(rbuf + 8, vol->v_path, len);
-        *rbuflen += 8 + len;
-               break;
+    array = talloc_zero(reply, sl_array_t);
+    uint64_t sl_res = 0;
+    dalloc_add_copy(array, &sl_res, uint64_t);
+    dalloc_add(reply, array, sl_array_t);
+
+EC_CLEANUP:
+    EC_EXIT;
+}
+
+static int sl_rpc_fetchAttributeNamesForOIDArray(const AFPObj *obj, const DALLOC_CTX *query, DALLOC_CTX *reply, const struct vol *vol)
+{
+    EC_INIT;
+    uint64_t uint64;
+    sl_cnids_t *cnids;
+    cnid_t id;
+    char *path;
+    struct dir *dir;
+
+    EC_NULL_LOG( cnids = dalloc_get(query, "DALLOC_CTX", 0, "sl_cnids_t", 1) );
+    memcpy(&uint64, cnids->ca_cnids->dd_talloc_array[0], sizeof(uint64_t));
+    id = (cnid_t)uint64;
+    LOG(log_debug, logtype_sl, "sl_rpc_fetchAttributeNamesForOIDArray: CNID: %" PRIu32, id);
+
+    if (htonl(id) == DIRDID_ROOT) {
+        path = vol->v_path;
+    } else if (id < CNID_START) {
+        EC_FAIL;
+    } else {
+        cnid_t did;
+        char buffer[12 + MAXPATHLEN + 1];
+
+        did = htonl(id);
+        EC_NULL_LOG( path = cnid_resolve(vol->v_cdb, &did, buffer, sizeof(buffer)) );
+        EC_NULL_LOG( dir = dirlookup(vol, did) );
+        EC_NEG1_LOG( movecwd(vol, dir) );
     }
-       case SPOTLIGHT_CMD_FLAGS:
-               break;
 
-       case SPOTLIGHT_CMD_RPC:
-        /* IVAL(buf, 14): our reply in SPOTLIGHT_CMD_FLAGS */
-        /* IVAL(buf, 18): length */
-        /* IVAL(buf, 22): endianess, ignored, we assume little endian */
-               break;
-       }
+    /* Result array */
+    sl_array_t *array = talloc_zero(reply, sl_array_t);
+    dalloc_add(reply, array, sl_array_t);
+
+    /* Return result value 0 */
+    uint64_t sl_res = 0;
+    dalloc_add_copy(array, &sl_res, uint64_t);
+
+    /* Return CNID array */
+    sl_cnids_t *replycnids = talloc_zero(reply, sl_cnids_t);
+    replycnids->ca_cnids = talloc_zero(cnids, DALLOC_CTX);
+    replycnids->ca_unkn1 = 0xfec;
+    replycnids->ca_context = cnids->ca_context;
+    uint64 = (uint64_t)id;
+    dalloc_add_copy(replycnids->ca_cnids, &uint64, uint64_t);
+    dalloc_add(array, replycnids, sl_cnids_t);
+
+    /* Return filemeta array */
+
+    /*
+     * FIXME: this should return the real attributes from all known metadata sources
+     * (Tracker and filesystem)
+     */
+    sl_array_t *mdattrs = talloc_zero(reply, sl_array_t);
+    dalloc_add(mdattrs, dalloc_strdup(mdattrs, "kMDItemFSName"), "char *");
+    dalloc_add(mdattrs, dalloc_strdup(mdattrs, "kMDItemDisplayName"), "char *");
+    dalloc_add(mdattrs, dalloc_strdup(mdattrs, "kMDItemFSSize"), "char *");
+    dalloc_add(mdattrs, dalloc_strdup(mdattrs, "kMDItemFSOwnerUserID"), "char *");
+    dalloc_add(mdattrs, dalloc_strdup(mdattrs, "kMDItemFSOwnerGroupID"), "char *");
+    dalloc_add(mdattrs, dalloc_strdup(mdattrs, "kMDItemFSContentChangeDate"), "char *");
+
+    sl_filemeta_t *fmeta = talloc_zero(reply, sl_filemeta_t);
+    dalloc_add(fmeta, mdattrs, sl_array_t);
+    dalloc_add(array, fmeta, sl_filemeta_t);
 
 EC_CLEANUP:
-    talloc_free(tmp_ctx);
-    if (ret != AFP_OK) {
-        
+    EC_EXIT;
+}
+
+static int sl_rpc_fetchAttributesForOIDArray(AFPObj *obj, const DALLOC_CTX *query, DALLOC_CTX *reply, const struct vol *vol)
+{
+    EC_INIT;
+    uint64_t uint64;
+    sl_cnids_t *cnids, *replycnids;
+    cnid_t id, did;
+    struct dir *dir;
+    sl_array_t *array, *reqinfo, *fm_array;
+    char buffer[12 + MAXPATHLEN + 1];
+    char *name, *path;
+    sl_filemeta_t *fm;
+    sl_nil_t nil;
+    uint64_t sl_res;
+    struct stat sb;
+
+    array = talloc_zero(reply, sl_array_t);
+    replycnids = talloc_zero(reply, sl_cnids_t);
+    replycnids->ca_cnids = talloc_zero(replycnids, DALLOC_CTX);
+    fm = talloc_zero(array, sl_filemeta_t);
+    fm_array = talloc_zero(fm, sl_array_t);
+
+    if (array == NULL || replycnids == NULL || replycnids->ca_cnids == NULL
+        || fm == NULL || fm_array == NULL) {
+        EC_FAIL;
     }
+
+    reqinfo = dalloc_get(query, "DALLOC_CTX", 0, "sl_array_t", 1);
+    if (reqinfo == NULL) {
+        EC_FAIL;
+    }
+    cnids = dalloc_get(query, "DALLOC_CTX", 0, "sl_cnids_t", 2);
+    if (cnids == NULL) {
+        EC_FAIL;
+    }
+
+    memcpy(&uint64, cnids->ca_cnids->dd_talloc_array[0], sizeof(uint64_t));
+    id = (cnid_t)uint64;
+
+    if (htonl(id) == DIRDID_ROOT) {
+        path = talloc_strdup(reply, vol->v_path);
+    } else if (id < CNID_START) {
+        EC_FAIL;
+    } else {
+        did = htonl(id);
+        EC_NULL( name = cnid_resolve(vol->v_cdb, &did, buffer, sizeof(buffer)) );
+        EC_NULL( dir = dirlookup(vol, did) );
+        EC_NULL( path = talloc_asprintf(reply, "%s/%s", bdata(dir->d_fullpath), name) );
+    }
+
+    EC_ZERO( stat(path, &sb) );
+
+    sl_res = 0;
+    dalloc_add_copy(array, &sl_res, uint64_t);
+
+    replycnids->ca_unkn1 = 0xfec;
+    replycnids->ca_context = cnids->ca_context;
+    uint64 = (uint64_t)id;
+    dalloc_add_copy(replycnids->ca_cnids, &uint64, uint64_t);
+    dalloc_add(array, replycnids, sl_cnids_t);
+    dalloc_add(fm, fm_array, fm_array_t);
+    dalloc_add_copy(fm_array, &nil, sl_nil_t);
+    add_filemeta(reqinfo, fm_array, path, &sb);
+
+    /* Now add result */
+    dalloc_add(array, fm, sl_filemeta_t);
+    dalloc_add(reply, array, sl_array_t);
+    EC_EXIT;
+
+EC_CLEANUP:
+    sl_res = UINT64_MAX;
+    dalloc_add_copy(array, &sl_res, uint64_t);
+    dalloc_add(array, fm, sl_filemeta_t);
+    dalloc_add(reply, array, sl_array_t);
     EC_EXIT;
 }
 
-/**************************************************************************************************
- * Testing
- **************************************************************************************************/
+static int sl_rpc_closeQueryForContext(const AFPObj *obj,
+                                       const DALLOC_CTX *query,
+                                       DALLOC_CTX *reply,
+                                       const struct vol *v)
+{
+    EC_INIT;
+    slq_t *slq = NULL;
+    uint64_t *uint64, ctx1, ctx2;
+    sl_array_t *array;
+    uint64_t sl_result;
+
+    array = talloc_zero(reply, sl_array_t);
 
-#ifdef SPOT_TEST_MAIN
+    /* Context */
+    uint64 = dalloc_get(query, "DALLOC_CTX", 0, "DALLOC_CTX", 0, "uint64_t", 1);
+    if (uint64 == NULL) {
+        EC_FAIL;
+    }
+    ctx1 = *uint64;
+    uint64 = dalloc_get(query, "DALLOC_CTX", 0, "DALLOC_CTX", 0, "uint64_t", 2);
+    if (uint64 == NULL) {
+        EC_FAIL;
+    }
+    ctx2 = *uint64;
+
+    /* Get query for context and free it */
+    slq = slq_for_ctx(ctx1, ctx2);
+    if (slq == NULL) {
+        EC_FAIL;
+    }
 
-static const char *neststrings[] = {
-    "",
-    "    ",
-    "        ",
-    "            ",
-    "                ",
-    "                    ",
-    "                        "
-};
+    switch (slq->slq_state) {
+    case SLQ_STATE_DONE:
+    case SLQ_STATE_ERROR:
+        slq_destroy(slq);
+        break;
 
-static int dd_dump(DALLOC_CTX *dd, int nestinglevel)
+    case SLQ_STATE_RUNNING:
+    case SLQ_STATE_RESULTS:
+        slq_cancel(slq);
+        break;
+
+    default:
+        LOG(log_error, logtype_sl, "Unexpected state %d", slq->slq_state);
+        EC_FAIL;
+    }
+
+    sl_result = 0;
+
+EC_CLEANUP:
+    if (ret != 0) {
+        sl_result = UINT64_MAX;
+    }
+    dalloc_add_copy(array, &sl_result, uint64_t);
+    dalloc_add(reply, array, sl_array_t);
+    EC_EXIT;
+}
+
+/******************************************************************************
+ * Spotlight functions
+ ******************************************************************************/
+
+int spotlight_init(AFPObj *obj)
 {
-    const char *type;
+    static bool initialized = false;
+    const char *attributes;
+    struct sl_ctx *sl_ctx;
 
-    printf("%sArray(#%d): {\n", neststrings[nestinglevel], talloc_array_length(dd->dd_talloc_array));
+    if (initialized) {
+        return 0;
+    }
 
-    for (int n = 0; n < talloc_array_length(dd->dd_talloc_array); n++) {
+    LOG(log_info, logtype_sl, "Initializing Spotlight");
 
-        type = talloc_get_name(dd->dd_talloc_array[n]);
+    sl_ctx = talloc_zero(NULL, struct sl_ctx);
+    obj->sl_ctx = sl_ctx;
 
-        if (STRCMP(type, ==, "int64_t")) {
-            int64_t i;
-            memcpy(&i, dd->dd_talloc_array[n], sizeof(int64_t));
-            printf("%s%d:\t%" PRId64 "\n", neststrings[nestinglevel + 1], n, i);
-        } else if (STRCMP(type, ==, "uint32_t")) {
-            uint32_t i;
-            memcpy(&i, dd->dd_talloc_array[n], sizeof(uint32_t));
-            printf("%s%d:\t%" PRIu32 "\n", neststrings[nestinglevel + 1], n, i);
-        } else if (STRCMP(type, ==, "char *")) {
-            char *s;
-            memcpy(&s, dd->dd_talloc_array[n], sizeof(char *));
-            printf("%s%d:\t%s\n", neststrings[nestinglevel + 1], n, s);
-        } else if (STRCMP(type, ==, "_Bool")) {
-            bool bl;
-            memcpy(&bl, dd->dd_talloc_array[n], sizeof(bool));
-            printf("%s%d:\t%s\n", neststrings[nestinglevel + 1], n, bl ? "true" : "false");
-        } else if (STRCMP(type, ==, "dd_t")) {
-            DALLOC_CTX *nested;
-            memcpy(&nested, dd->dd_talloc_array[n], sizeof(DALLOC_CTX *));
-            dd_dump(nested, nestinglevel + 1);
-        } else if (STRCMP(type, ==, "cnid_array_t")) {
-            cnid_array_t *cnids;
-            memcpy(&cnids, dd->dd_talloc_array[n], sizeof(cnid_array_t *));
-            printf("%s%d:\tunkn1: %" PRIu16 ", unkn2: %" PRIu32,
-                   neststrings[nestinglevel + 1], n, cnids->ca_unkn1, cnids->ca_unkn2);
-            if (cnids->ca_cnids)
-                dd_dump(cnids->ca_cnids, nestinglevel + 1);
-        }
+    attributes = atalk_iniparser_getstring(obj->iniconfig, INISEC_GLOBAL,
+                                           "spotlight attributes", NULL);
+    if (attributes) {
+        configure_spotlight_attributes(attributes);
     }
-    printf("%s}\n", neststrings[nestinglevel]);
+
+    /*
+     * Tracker uses glibs event dispatching, so we need a mainloop
+     */
+    sl_ctx->mainloop = g_main_loop_new(NULL, false);
+    sl_ctx->cancellable = g_cancellable_new();
+
+    setenv("DBUS_SESSION_BUS_ADDRESS", "unix:path=" _PATH_STATEDIR "spotlight.ipc", 1);
+    setenv("XDG_DATA_HOME", _PATH_STATEDIR, 0);
+    setenv("XDG_CACHE_HOME", _PATH_STATEDIR, 0);
+    setenv("TRACKER_USE_LOG_FILES", "1", 0);
+
+    tracker_sparql_connection_get_async(sl_ctx->cancellable,
+                                        tracker_con_cb, sl_ctx);
+
+    initialized = true;
+    return 0;
 }
 
-#include <stdarg.h>
+/******************************************************************************
+ * AFP functions
+ ******************************************************************************/
 
-int main(int argc, char **argv)
+int afp_spotlight_rpc(AFPObj *obj, char *ibuf, size_t ibuflen,
+                      char *rbuf, size_t *rbuflen)
 {
-    TALLOC_CTX *mem_ctx = talloc_new(NULL);
-    DALLOC_CTX *dd = talloc_zero(mem_ctx, DALLOC_CTX);
-    int64_t i;
+    EC_INIT;
+    TALLOC_CTX *tmp_ctx = talloc_new(NULL);
+    uint16_t vid;
+    int cmd;
+    struct vol      *vol;
+    DALLOC_CTX *query;
+    DALLOC_CTX *reply;
+    char *rpccmd;
+    int len;
+    bool event;
 
-    set_processname("spot");
-    setuplog("default:info", "/dev/tty");
+    *rbuflen = 0;
 
-    LOG(logtype_default, log_info, "Start");
+    if (!(obj->options.flags & OPTION_SPOTLIGHT)) {
+        return AFPERR_NOOP;
+    }
 
-    i = 2;
-    dalloc_add(dd, &i, int64_t);
+    spotlight_init(obj);
 
-    i = 1;
-    dalloc_add(dd, &i, int64_t);
+    /*
+     * Process finished glib events
+     */
+    event = true;
+    while (event) {
+        event = g_main_context_iteration(NULL, false);
+    }
+    slq_cancelled_cleanup();
 
+    ibuf += 2;
+    ibuflen -= 2;
 
-    char *str = talloc_strdup(dd, "hello world");
-    dalloc_add(dd, &str, char *);
+    vid = SVAL(ibuf, 0);
+    LOG(log_debug, logtype_sl, "afp_spotlight_rpc(vid: %" PRIu16 ")", vid);
 
-    bool b = true;
-    dalloc_add(dd, &b, bool);
+    if ((vol = getvolbyvid(vid)) == NULL) {
+        LOG(log_error, logtype_sl, "afp_spotlight_rpc: bad volume id: %" PRIu16 ")", vid);
+        ret = AFPERR_ACCESS;
+        goto EC_CLEANUP;
+    }
 
-    b = false;
-    dalloc_add(dd, &b, bool);
+    /*    IVAL(ibuf, 2): unknown, always 0x00008004, some flags ? */
 
+    cmd = RIVAL(ibuf, 6);
+    LOG(log_debug, logtype_sl, "afp_spotlight_rpc(cmd: %d)", cmd);
 
-    /* add a nested array */
-    DALLOC_CTX *nested = talloc_zero(dd, DALLOC_CTX);
-    i = 3;
-    dalloc_add(nested, &i, int64_t);
-    dalloc_add(dd, &nested, DALLOC_CTX);
+    /*    IVAL(ibuf, 10: unknown, always 0x00000000 */
 
-    /* test a CNID array */
-    uint32_t id = 16;
-    cnid_array_t *cnids = talloc_zero(dd, cnid_array_t);
+    switch (cmd) {
 
-    cnids->ca_cnids = talloc_zero(cnids, DALLOC_CTX);
+    case SPOTLIGHT_CMD_OPEN:
+    case SPOTLIGHT_CMD_OPEN2:
+        RSIVAL(rbuf, 0, ntohs(vid));
+        RSIVAL(rbuf, 4, 0);
+        len = strlen(vol->v_path) + 1;
+        strncpy(rbuf + 8, vol->v_path, len);
+        *rbuflen += 8 + len;
+        break;
+
+    case SPOTLIGHT_CMD_FLAGS:
+        RSIVAL(rbuf, 0, 0x0100006b); /* Whatever this value means... flags? Helios uses 0x1eefface */
+        *rbuflen += 4;
+        break;
+
+    case SPOTLIGHT_CMD_RPC:
+        EC_NULL( query = talloc_zero(tmp_ctx, DALLOC_CTX) );
+        EC_NULL( reply = talloc_zero(tmp_ctx, DALLOC_CTX) );
+        EC_NEG1_LOG( sl_unpack(query, ibuf + 22) );
+
+        LOG(log_debug, logtype_sl, "Spotlight RPC request:\n%s",
+            dd_dump(query, 0));
+
+        EC_NULL_LOG( rpccmd = dalloc_get(query, "DALLOC_CTX", 0, "DALLOC_CTX", 0, "char *", 0) );
+
+        if (STRCMP(rpccmd, ==, "fetchPropertiesForContext:")) {
+            EC_ZERO_LOG( sl_rpc_fetchPropertiesForContext(obj, query, reply, vol) );
+        } else if (STRCMP(rpccmd, ==, "openQueryWithParams:forContext:")) {
+            EC_ZERO_LOG( sl_rpc_openQuery(obj, query, reply, vol) );
+        } else if (STRCMP(rpccmd, ==, "fetchQueryResultsForContext:")) {
+            EC_ZERO_LOG( sl_rpc_fetchQueryResultsForContext(obj, query, reply, vol) );
+        } else if (STRCMP(rpccmd, ==, "storeAttributes:forOIDArray:context:")) {
+            EC_ZERO_LOG( sl_rpc_storeAttributesForOIDArray(obj, query, reply, vol) );
+        } else if (STRCMP(rpccmd, ==, "fetchAttributeNamesForOIDArray:context:")) {
+            EC_ZERO_LOG( sl_rpc_fetchAttributeNamesForOIDArray(obj, query, reply, vol) );
+        } else if (STRCMP(rpccmd, ==, "fetchAttributes:forOIDArray:context:")) {
+            EC_ZERO_LOG( sl_rpc_fetchAttributesForOIDArray(obj, query, reply, vol) );
+        } else if (STRCMP(rpccmd, ==, "closeQueryForContext:")) {
+            EC_ZERO_LOG( sl_rpc_closeQueryForContext(obj, query, reply, vol) );
+        } else {
+            LOG(log_error, logtype_sl, "afp_spotlight_rpc: unknown Spotlight RPC: %s", rpccmd);
+        }
 
-    cnids->ca_unkn1 = 1;
-    cnids->ca_unkn2 = 2;
+        LOG(log_debug, logtype_sl, "Spotlight RPC reply dump:\n%s",
+            dd_dump(reply, 0));
 
-    dalloc_add(cnids->ca_cnids, &id, uint32_t);
-    dalloc_add(dd, &cnids, cnid_array_t);
+        memset(rbuf, 0, 4);
+        *rbuflen += 4;
 
-    dd_dump(dd, 0);
+        EC_NEG1_LOG( len = sl_pack(reply, rbuf + 4) );
+        *rbuflen += len;
+        break;
+    }
 
-    talloc_free(mem_ctx);
-    return 0;
+EC_CLEANUP:
+    talloc_free(tmp_ctx);
+    if (ret != AFP_OK) {
+        *rbuflen = 0;
+        return AFPERR_MISC;
+    }
+    EC_EXIT;
 }
-#endif