Happy new year
[pazpar2-moved-to-github.git] / src / http_command.c
index 9749ce6..854de13 100644 (file)
@@ -1,5 +1,5 @@
 /* This file is part of Pazpar2.
-   Copyright (C) 2006-2009 Index Data
+   Copyright (C) 2006-2012 Index Data
 
 Pazpar2 is free software; you can redistribute it and/or modify it under
 the terms of the GNU General Public License as published by the Free
@@ -33,13 +33,40 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 #include <yaz/snprintf.h>
 #include <yaz/yaz-util.h>
 
+#include "ppmutex.h"
 #include "eventl.h"
 #include "parameters.h"
-#include "pazpar2.h"
+#include "session.h"
 #include "http.h"
 #include "settings.h"
 #include "client.h"
 
+#ifdef HAVE_MALLINFO
+#include <malloc.h>
+
+void print_meminfo(WRBUF wrbuf)
+{
+    struct mallinfo minfo;
+    minfo = mallinfo();
+    wrbuf_printf(wrbuf, "  <memory>\n"
+                        "   <arena>%d</arena>\n" 
+                        "   <uordblks>%d</uordblks>\n"
+                        "   <fordblks>%d</fordblks>\n"
+                        "   <ordblks>%d</ordblks>\n"
+                        "   <keepcost>%d</keepcost>\n"
+                        "   <hblks>%d</hblks>\n" 
+                        "   <hblkhd>%d</hblkhd>\n"
+                        "   <virt>%d</virt>\n"
+                        "   <virtuse>%d</virtuse>\n"
+                        "  </memory>\n", 
+                 minfo.arena, minfo.uordblks, minfo.fordblks,minfo.ordblks, minfo.keepcost, minfo.hblks, minfo.hblkhd, minfo.arena + minfo.hblkhd, minfo.uordblks + minfo.hblkhd);
+
+}
+#else
+#define print_meminfo(x)
+#endif
+
+
 // Update this when the protocol changes
 #define PAZPAR2_PROTOCOL_VERSION "1"
 
@@ -50,11 +77,63 @@ struct http_session {
     struct session *psession;
     unsigned int session_id;
     int timestamp;
+    int destroy_counter;
+    int activity_counter;
     NMEM nmem;
+    http_sessions_t http_sessions;
     struct http_session *next;
 };
 
-static struct http_session *session_list = 0; /* thread pr */
+struct http_sessions {
+    struct http_session *session_list;
+    YAZ_MUTEX mutex;
+    int log_level;
+};
+
+static YAZ_MUTEX g_http_session_mutex = 0;
+static int g_http_sessions = 0;
+
+int http_session_use(int delta)
+{
+    int sessions;
+    if (!g_http_session_mutex)
+        yaz_mutex_create(&g_http_session_mutex);
+    yaz_mutex_enter(g_http_session_mutex);
+    g_http_sessions += delta;
+    sessions = g_http_sessions;
+    yaz_mutex_leave(g_http_session_mutex);
+    yaz_log(YLOG_DEBUG, "%s sessions=%d", delta == 0 ? "" : (delta > 0 ? "INC" : "DEC"), sessions);
+    return sessions;
+
+}
+
+http_sessions_t http_sessions_create(void)
+{
+    http_sessions_t hs = xmalloc(sizeof(*hs));
+    hs->session_list = 0;
+    hs->mutex = 0;
+    pazpar2_mutex_create(&hs->mutex, "http_sessions");
+    hs->log_level = yaz_log_module_level("HTTP");
+    return hs;
+}
+
+void http_sessions_destroy(http_sessions_t hs)
+{
+    if (hs)
+    {
+        struct http_session *s = hs->session_list;
+        while (s)
+        {
+            struct http_session *s_next = s->next;
+            iochan_destroy(s->timeout_iochan);
+            session_destroy(s->psession);
+            nmem_destroy(s->nmem);
+            s = s_next;
+        }
+        yaz_mutex_destroy(&hs->mutex);
+        xfree(hs);
+    }
+}
 
 void http_session_destroy(struct http_session *s);
 
@@ -64,39 +143,71 @@ static void session_timeout(IOCHAN i, int event)
     http_session_destroy(s);
 }
 
-struct http_session *http_session_create(struct conf_service *service)
+struct http_session *http_session_create(struct conf_service *service,
+                                         http_sessions_t http_sessions,
+                                         unsigned int sesid)
 {
     NMEM nmem = nmem_create();
     struct http_session *r = nmem_malloc(nmem, sizeof(*r));
+    char tmp_str[50];
 
-    r->psession = new_session(nmem, service);
-    r->session_id = 0;
+    sprintf(tmp_str, "session#%u", sesid);
+    r->psession = new_session(nmem, service, sesid);
+    r->session_id = sesid;
     r->timestamp = 0;
     r->nmem = nmem;
-    r->next = session_list;
-    session_list = r;
-    r->timeout_iochan = iochan_create(-1, session_timeout, 0);
+    r->destroy_counter = r->activity_counter = 0;
+    r->http_sessions = http_sessions;
+
+    yaz_mutex_enter(http_sessions->mutex);
+    r->next = http_sessions->session_list;
+    http_sessions->session_list = r;
+    yaz_mutex_leave(http_sessions->mutex);
+
+    r->timeout_iochan = iochan_create(-1, session_timeout, 0, "http_session_timeout");
     iochan_setdata(r->timeout_iochan, r);
+    yaz_log(http_sessions->log_level, "Session %u created. timeout chan=%p timeout=%d", sesid, r->timeout_iochan, service->session_timeout);
     iochan_settimeout(r->timeout_iochan, service->session_timeout);
 
-    pazpar2_add_channel(r->timeout_iochan);
+    iochan_add(service->server->iochan_man, r->timeout_iochan);
+    http_session_use(1);
     return r;
 }
 
 void http_session_destroy(struct http_session *s)
 {
-    struct http_session **p;
+    int must_destroy = 0;
+
+    http_sessions_t http_sessions = s->http_sessions;
+
+    yaz_log(http_sessions->log_level, "Session %u destroy", s->session_id);
+    yaz_mutex_enter(http_sessions->mutex);
+    /* only if http_session has no active http sessions on it can be destroyed */
+    if (s->destroy_counter == s->activity_counter)
+    {
+        struct http_session **p = 0;
+        must_destroy = 1;
+        for (p = &http_sessions->session_list; *p; p = &(*p)->next)
+            if (*p == s)
+            {
+                *p = (*p)->next;
+                break;
+            }
+    }
+    yaz_mutex_leave(http_sessions->mutex);
+    if (must_destroy)
+    {   /* destroying for real */
+        yaz_log(http_sessions->log_level, "Session %u destroyed", s->session_id);
+        iochan_destroy(s->timeout_iochan);
+        session_destroy(s->psession);
+        http_session_use(-1);
+        nmem_destroy(s->nmem);
+    }
+    else {
+        yaz_log(http_sessions->log_level, "Session %u destroying delayed. Active clients (%d-%d). Waiting for new timeout.",
+                s->session_id, s->activity_counter, s->destroy_counter);
+    }
 
-    for (p = &session_list; *p; p = &(*p)->next)
-        if (*p == s)
-        {
-            *p = (*p)->next;
-            break;
-        }
-    yaz_log(YLOG_LOG, "Destroying session %u", s->session_id);
-    iochan_destroy(s->timeout_iochan);
-    destroy_session(s->psession);
-    nmem_destroy(s->nmem);
 }
 
 static const char *get_msg(enum pazpar2_error_code code)
@@ -117,6 +228,8 @@ static const char *get_msg(enum pazpar2_error_code code)
         { PAZPAR2_CONFIG_TARGET, "Target cannot be configured"},
         { PAZPAR2_RECORD_FAIL, "Record command failed"},
         { PAZPAR2_NOT_IMPLEMENTED, "Not implemented"},
+        { PAZPAR2_NO_SERVICE, "No service"},
+        { PAZPAR2_ALREADY_BLOCKED, "Already blocked in session on: "},
         { PAZPAR2_LAST_ERROR, "Last error"},
         { 0, 0 }
     };
@@ -155,13 +268,35 @@ static void error(struct http_response *rs,
     http_send_response(c);
 }
 
+static void response_open_no_status(struct http_channel *c, const char *command)
+{
+    wrbuf_rewind(c->wrbuf);
+    wrbuf_printf(c->wrbuf, "%s<%s>",
+                 HTTP_COMMAND_RESPONSE_PREFIX, command);
+}
+
+static void response_open(struct http_channel *c, const char *command)
+{
+    response_open_no_status(c, command);
+    wrbuf_puts(c->wrbuf, "<status>OK</status>");
+}
+
+static void response_close(struct http_channel *c, const char *command)
+{
+    struct http_response *rs = c->response;
+
+    wrbuf_printf(c->wrbuf, "</%s>", command);
+    rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
+    http_send_response(c);
+}
+
 unsigned int make_sessionid(void)
 {
     static int seq = 0; /* thread pr */
     unsigned int res;
 
     seq++;
-    if (global_parameters.debug_mode)
+    if (global_parameters.predictable_sessions)
         res = seq;
     else
     {
@@ -184,10 +319,13 @@ unsigned int make_sessionid(void)
     return res;
 }
 
-static struct http_session *locate_session(struct http_request *rq, struct http_response *rs)
+static struct http_session *locate_session(struct http_channel *c)
 {
+    struct http_request *rq = c->request;
+    struct http_response *rs = c->response;
     struct http_session *p;
     const char *session = http_argbyname(rq, "session");
+    http_sessions_t http_sessions = c->http_sessions;
     unsigned int id;
 
     if (!session)
@@ -196,14 +334,29 @@ static struct http_session *locate_session(struct http_request *rq, struct http_
         return 0;
     }
     id = atoi(session);
-    for (p = session_list; p; p = p->next)
+    yaz_mutex_enter(http_sessions->mutex);
+    for (p = http_sessions->session_list; p; p = p->next)
         if (id == p->session_id)
-        {
-            iochan_activity(p->timeout_iochan);
-            return p;
-        }
-    error(rs, PAZPAR2_NO_SESSION, session);
-    return 0;
+            break;
+    if (p)
+        p->activity_counter++;
+    yaz_mutex_leave(http_sessions->mutex);
+    if (p)
+        iochan_activity(p->timeout_iochan);
+    else
+        error(rs, PAZPAR2_NO_SESSION, session);
+    return p;
+}
+
+// Call after use of locate_session, in order to increment the destroy_counter
+static void release_session(struct http_channel *c,
+                            struct http_session *session)
+{
+    http_sessions_t http_sessions = c->http_sessions;
+    yaz_mutex_enter(http_sessions->mutex);
+    if (session)
+        session->destroy_counter++;
+    yaz_mutex_leave(http_sessions->mutex);
 }
 
 // Decode settings parameters and apply to session
@@ -239,12 +392,14 @@ static int process_settings(struct session *se, struct http_request *rq,
 static void cmd_exit(struct http_channel *c)
 {
     yaz_log(YLOG_WARN, "exit");
+
+    response_open(c, "exit");
+    response_close(c, "exit");
     http_close_server(c->server);
 }
 
 static void cmd_init(struct http_channel *c)
 {
-    char buf[1024];
     struct http_request *r = c->request;
     const char *clear = http_argbyname(r, "clear");
     const char *content_type = http_lookup_header(r->headers, "Content-Type");
@@ -279,27 +434,33 @@ static void cmd_init(struct http_channel *c)
         service = locate_service(c->server, service_name);
         if (!service)
         {
-            error(rs, PAZPAR2_MALFORMED_PARAMETER_VALUE, "service");
+            error(rs, PAZPAR2_NO_SERVICE, service_name ? service_name : "unnamed");
             return;
         }
-        service_incref(service);
     }
-    s = http_session_create(service);
+    sesid = make_sessionid();
+    s = http_session_create(service, c->http_sessions, sesid);
     
-    yaz_log(YLOG_DEBUG, "HTTP Session init");
+    yaz_log(c->http_sessions->log_level, "Session init %u ", sesid);
     if (!clear || *clear == '0')
         session_init_databases(s->psession);
     else
-        yaz_log(YLOG_LOG, "No databases preloaded");
+        yaz_log(YLOG_LOG, "Session %u init: No databases preloaded", sesid);
     
-    sesid = make_sessionid();
-    s->session_id = sesid;
     if (process_settings(s->psession, c->request, c->response) < 0)
         return;
-    sprintf(buf, HTTP_COMMAND_RESPONSE_PREFIX "<init><status>OK</status><session>%u</session>"
-            "<protocol>" PAZPAR2_PROTOCOL_VERSION "</protocol></init>", sesid);
-    rs->payload = nmem_strdup(c->nmem, buf);
-    http_send_response(c);
+
+    response_open(c, "init");
+    wrbuf_printf(c->wrbuf, "<session>%d", sesid);
+    if (c->server->server_id)
+    {
+        wrbuf_puts(c->wrbuf, ".");
+        wrbuf_puts(c->wrbuf, c->server->server_id);
+    }
+    wrbuf_puts(c->wrbuf, "</session>"
+               "<protocol>" PAZPAR2_PROTOCOL_VERSION "</protocol>");
+    
+    response_close(c, "init");
 }
 
 static void apply_local_setting(void *client_data,
@@ -316,7 +477,7 @@ static void cmd_settings(struct http_channel *c)
 {
     struct http_response *rs = c->response;
     struct http_request *rq = c->request;
-    struct http_session *s = locate_session(rq, rs);
+    struct http_session *s = locate_session(c);
     const char *content_type = http_lookup_header(rq->headers, "Content-Type");
 
     if (!s)
@@ -330,6 +491,7 @@ static void cmd_settings(struct http_channel *c)
         if (!doc)
         {
             error(rs, PAZPAR2_MALFORMED_SETTING, 0);
+            release_session(c,s);
             return;
         }
         root_n = xmlDocGetRootElement(doc);
@@ -339,148 +501,156 @@ static void cmd_settings(struct http_channel *c)
         xmlFreeDoc(doc);
     }
     if (process_settings(s->psession, rq, rs) < 0)
+    {
+        release_session(c, s);
         return;
-    rs->payload = HTTP_COMMAND_RESPONSE_PREFIX "<settings><status>OK</status></settings>";
-    http_send_response(c);
+    }
+    response_open(c, "settings");
+    response_close(c, "settings");
+    release_session(c, s);
 }
 
-// Compares two hitsbytarget nodes by hitcount
-static int cmp_ht(const void *p1, const void *p2)
+static void termlist_response(struct http_channel *c, struct http_session *s)
 {
-    const struct hitsbytarget *h1 = p1;
-    const struct hitsbytarget *h2 = p2;
-    return h2->hits - h1->hits;
-}
+    struct http_request *rq = c->request;
+    const char *name = http_argbyname(rq, "name");
+    const char *nums = http_argbyname(rq, "num");
+    int num = 15;
+    int status;
 
-// This implements functionality somewhat similar to 'bytarget', but in a termlist form
-static void targets_termlist(WRBUF wrbuf, struct session *se, int num,
-                             NMEM nmem)
-{
-    struct hitsbytarget *ht;
-    int count, i;
+    if (nums)
+        num = atoi(nums);
 
-    ht = hitsbytarget(se, &count, nmem);
-    qsort(ht, count, sizeof(struct hitsbytarget), cmp_ht);
-    for (i = 0; i < count && i < num && ht[i].hits > 0; i++)
-    {
+    status = session_active_clients(s->psession);
 
-        // do only print terms which have display names
-    
-        wrbuf_puts(wrbuf, "<term>\n");
+    response_open_no_status(c, "termlist");
+    wrbuf_printf(c->wrbuf, "<activeclients>%d</activeclients>\n", status);
 
-        wrbuf_puts(wrbuf, "<id>");
-        wrbuf_xmlputs(wrbuf, ht[i].id);
-        wrbuf_puts(wrbuf, "</id>\n");
-        
-        wrbuf_puts(wrbuf, "<name>");
-        if (!ht[i].name || !ht[i].name[0])
-            wrbuf_xmlputs(wrbuf, "NO TARGET NAME");
-        else
-            wrbuf_xmlputs(wrbuf, ht[i].name);
-        wrbuf_puts(wrbuf, "</name>\n");
-        
-        wrbuf_printf(wrbuf, "<frequency>%d</frequency>\n", ht[i].hits);
-        
-        wrbuf_puts(wrbuf, "<state>");
-        wrbuf_xmlputs(wrbuf, ht[i].state);
-        wrbuf_puts(wrbuf, "</state>\n");
-        
-        wrbuf_printf(wrbuf, "<diagnostic>%d</diagnostic>\n", 
-                     ht[i].diagnostic);
-        wrbuf_puts(wrbuf, "</term>\n");
+    perform_termlist(c, s->psession, name, num);
+
+    response_close(c, "termlist");
+}
+
+static void termlist_result_ready(void *data)
+{
+    struct http_channel *c = (struct http_channel *) data;
+    struct http_session *s = locate_session(c);
+    if (s) {
+        yaz_log(c->http_sessions->log_level, "Session %u termlist watch released", s->session_id);
+        termlist_response(c, s);
+        release_session(c,s);
     }
 }
 
 static void cmd_termlist(struct http_channel *c)
 {
-    struct http_response *rs = c->response;
     struct http_request *rq = c->request;
-    struct http_session *s = locate_session(rq, rs);
-    struct termlist_score **p;
-    int len;
-    int i;
-    const char *name = http_argbyname(rq, "name");
-    const char *nums = http_argbyname(rq, "num");
-    int num = 15;
-    int status;
-
+    struct http_response *rs = c->response;
+    struct http_session *s = locate_session(c);
+    const char *block = http_argbyname(rq, "block");
+    int active_clients;
     if (!s)
         return;
 
-    status = session_active_clients(s->psession);
-
-    if (!name)
-        name = "subject";
-    if (strlen(name) > 255)
-        return;
-    if (nums)
-        num = atoi(nums);
-
-    wrbuf_rewind(c->wrbuf);
+    active_clients = session_active_clients(s->psession);
 
-    wrbuf_puts(c->wrbuf, "<termlist>\n");
-    wrbuf_printf(c->wrbuf, "<activeclients>%d</activeclients>\n", status);
-    while (*name)
+    if (block && !strcmp("1", block) && active_clients)
     {
-        char tname[256];
-        const char *tp;
-
-        if (!(tp = strchr(name, ',')))
-            tp = name + strlen(name);
-        strncpy(tname, name, tp - name);
-        tname[tp - name] = '\0';
-
-        wrbuf_puts(c->wrbuf, "<list name=\"");
-        wrbuf_xmlputs(c->wrbuf, tname);
-        wrbuf_puts(c->wrbuf, "\">\n");
-        if (!strcmp(tname, "xtargets"))
-            targets_termlist(c->wrbuf, s->psession, num, c->nmem);
+        // if there is already a watch/block. we do not block this one
+        if (session_set_watch(s->psession, SESSION_WATCH_TERMLIST,
+                              termlist_result_ready, c, c) != 0)
+        {
+            yaz_log(YLOG_WARN, "Session %u: Attempt to block multiple times on termlist block. Not supported!", s->session_id);
+            error(rs, PAZPAR2_ALREADY_BLOCKED, "termlist");
+        }
         else
         {
-            p = termlist(s->psession, tname, &len);
-            if (p)
-                for (i = 0; i < len && i < num; i++){
-                    // prevnt sending empty term elements
-                    if (!p[i]->term || !p[i]->term[0])
-                        continue;
-
-                    wrbuf_puts(c->wrbuf, "<term>");
-                    wrbuf_puts(c->wrbuf, "<name>");
-                    wrbuf_xmlputs(c->wrbuf, p[i]->term);
-                    wrbuf_puts(c->wrbuf, "</name>");
-                        
-                    wrbuf_printf(c->wrbuf, 
-                                 "<frequency>%d</frequency>", 
-                                 p[i]->frequency);
-                    wrbuf_puts(c->wrbuf, "</term>\n");
-               }
+            yaz_log(c->http_sessions->log_level, "Session %u: Blocking on command termlist", s->session_id);
         }
-        wrbuf_puts(c->wrbuf, "</list>\n");
-        name = tp;
-        if (*name == ',')
-            name++;
+        release_session(c, s);
+        return;
     }
-    wrbuf_puts(c->wrbuf, "</termlist>\n");
-    rs->payload = nmem_strdup(rq->channel->nmem, wrbuf_cstr(c->wrbuf));
-    http_send_response(c);
+
+    termlist_response(c, s);
+    release_session(c, s);
 }
 
+size_t session_get_memory_status(struct session *session);
 
-static void cmd_bytarget(struct http_channel *c)
+static void session_status(struct http_channel *c, struct http_session *s)
 {
-    struct http_response *rs = c->response;
-    struct http_request *rq = c->request;
-    struct http_session *s = locate_session(rq, rs);
-    struct hitsbytarget *ht;
-    const char *settings = http_argbyname(rq, "settings");
-    int count, i;
+    size_t session_nmem;
+    wrbuf_printf(c->wrbuf, "<http_count>%u</http_count>\n", s->activity_counter);
+    wrbuf_printf(c->wrbuf, "<http_nmem>%zu</http_nmem>\n", nmem_total(s->nmem) );
+    session_nmem = session_get_memory_status(s->psession);
+    wrbuf_printf(c->wrbuf, "<session_nmem>%zu</session_nmem>\n", session_nmem);
+}
 
+static void cmd_session_status(struct http_channel *c)
+{
+    struct http_session *s = locate_session(c);
     if (!s)
         return;
-    ht = hitsbytarget(s->psession, &count, c->nmem);
-    wrbuf_rewind(c->wrbuf);
-    wrbuf_puts(c->wrbuf, HTTP_COMMAND_RESPONSE_PREFIX "<bytarget><status>OK</status>");
 
+    response_open(c, "session-status");
+    session_status(c, s);
+    response_close(c, "session-status");
+    release_session(c, s);
+}
+
+int sessions_count(void);
+int clients_count(void);
+#ifdef HAVE_RESULTSETS_COUNT
+int resultsets_count(void);
+#else
+#define resultsets_count()      0
+#endif
+
+static void cmd_server_status(struct http_channel *c)
+{
+    int sessions   = sessions_count();
+    int clients    = clients_count();
+    int resultsets = resultsets_count();
+
+    response_open(c, "server-status");
+    wrbuf_printf(c->wrbuf, "\n  <sessions>%u</sessions>\n", sessions);
+    wrbuf_printf(c->wrbuf, "  <clients>%u</clients>\n",   clients);
+    /* Only works if yaz has been compiled with enabling of this */
+    wrbuf_printf(c->wrbuf, "  <resultsets>%u</resultsets>\n",resultsets);
+    print_meminfo(c->wrbuf);
+
+/* TODO add all sessions status                         */
+/*    http_sessions_t http_sessions = c->http_sessions; */
+/*    struct http_session *p;                           */
+/*
+    yaz_mutex_enter(http_sessions->mutex);
+    for (p = http_sessions->session_list; p; p = p->next)
+    {
+        p->activity_counter++;
+        wrbuf_puts(c->wrbuf, "<session-status>\n");
+        wrbuf_printf(c->wrbuf, "<id>%s</id>\n", p->session_id);
+        yaz_mutex_leave(http_sessions->mutex);
+        session_status(c, p);
+        wrbuf_puts(c->wrbuf, "</session-status>\n");
+        yaz_mutex_enter(http_sessions->mutex);
+        p->activity_counter--;
+    }
+    yaz_mutex_leave(http_sessions->mutex);
+*/
+    response_close(c, "server-status");
+    xmalloc_trav(0);
+}
+
+static void bytarget_response(struct http_channel *c, struct http_session *s) {
+    int count, i;
+    struct hitsbytarget *ht;
+    struct http_request *rq = c->request;
+    const char *settings = http_argbyname(rq, "settings");
+
+    ht = get_hitsbytarget(s->psession, &count, c->nmem);
+    response_open(c, "bytarget");
+    if (count == 0)
+        yaz_log(YLOG_WARN, "Empty bytarget Response. No targets found!");
     for (i = 0; i < count; i++)
     {
         wrbuf_puts(c->wrbuf, "\n<target>");
@@ -496,8 +666,16 @@ static void cmd_bytarget(struct http_channel *c)
             wrbuf_puts(c->wrbuf, "</name>\n");
         }
 
-        wrbuf_printf(c->wrbuf, "<hits>%d</hits>\n", ht[i].hits);
+        wrbuf_printf(c->wrbuf, "<hits>" ODR_INT_PRINTF "</hits>\n", ht[i].hits);
         wrbuf_printf(c->wrbuf, "<diagnostic>%d</diagnostic>\n", ht[i].diagnostic);
+        if (ht[i].diagnostic)
+        {
+            wrbuf_puts(c->wrbuf, "<addinfo>");
+            if (ht[i].addinfo)
+                wrbuf_xmlputs(c->wrbuf, ht[i].addinfo);
+            wrbuf_puts(c->wrbuf, "</addinfo>\n");
+        }
+
         wrbuf_printf(c->wrbuf, "<records>%d</records>\n", ht[i].records);
 
         wrbuf_puts(c->wrbuf, "<state>");
@@ -506,16 +684,65 @@ static void cmd_bytarget(struct http_channel *c)
         if (settings && *settings == '1')
         {
             wrbuf_puts(c->wrbuf, "<settings>\n");
-            wrbuf_puts(c->wrbuf, wrbuf_cstr(ht[i].settings_xml));
+            wrbuf_puts(c->wrbuf, ht[i].settings_xml);
             wrbuf_puts(c->wrbuf, "</settings>\n");
         }
+        if (ht[i].suggestions_xml && ht[i].suggestions_xml[0]) {
+            wrbuf_puts(c->wrbuf, "<suggestions>");
+            wrbuf_puts(c->wrbuf, ht[i].suggestions_xml);
+            wrbuf_puts(c->wrbuf, "</suggestions>");
+        }
         wrbuf_puts(c->wrbuf, "</target>");
-        wrbuf_destroy(ht[i].settings_xml);
     }
+    response_close(c, "bytarget");
+}
 
-    wrbuf_puts(c->wrbuf, "</bytarget>");
-    rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
-    http_send_response(c);
+static void bytarget_result_ready(void *data)
+{
+    struct http_channel *c = (struct http_channel *) data;
+    struct http_session *s = locate_session(c);
+    if (s) {
+        yaz_log(c->http_sessions->log_level, "Session %u: bytarget watch released", s->session_id);
+        bytarget_response(c, s);
+        release_session(c, s);
+    }
+    else {
+        yaz_log(c->http_sessions->log_level, "No Session found for released bytarget watch");
+    }
+}
+
+
+static void cmd_bytarget(struct http_channel *c)
+{
+    struct http_request *rq = c->request;
+    struct http_response *rs = c->response;
+    struct http_session *s = locate_session(c);
+    const char *block = http_argbyname(rq, "block");
+    int no_active;
+
+    if (!s)
+        return;
+
+    no_active = session_active_clients(s->psession);
+
+    if (block && !strcmp("1",block) && no_active)
+    {
+        // if there is already a watch/block. we do not block this one
+        if (session_set_watch(s->psession, SESSION_WATCH_BYTARGET,
+                              bytarget_result_ready, c, c) != 0)
+        {
+            yaz_log(YLOG_WARN, "Session %u: Attempt to block multiple times on bytarget block. Not supported!", s->session_id);
+            error(rs, PAZPAR2_ALREADY_BLOCKED, "bytarget"); 
+        }
+        else
+        {
+            yaz_log(c->http_sessions->log_level, "Session %u: Blocking on command bytarget", s->session_id);
+        }
+        release_session(c, s);
+        return;
+    }
+    bytarget_response(c, s);
+    release_session(c, s);
 }
 
 static void write_metadata(WRBUF w, struct conf_service *service,
@@ -531,8 +758,16 @@ static void write_metadata(WRBUF w, struct conf_service *service,
             continue;
         for (md = ml[imeta]; md; md = md->next)
         {
-            wrbuf_printf(w, "\n<md-%s>", cmd->name);
+            struct record_metadata_attr *attr = md->attributes;
+            wrbuf_printf(w, "\n<md-%s", cmd->name);
 
+            for (; attr; attr = attr->next)
+            {
+                wrbuf_printf(w, " %s=\"", attr->name);
+                wrbuf_xmlputs(w, attr->value);
+                wrbuf_puts(w, "\"");
+            }
+            wrbuf_puts(w, ">");
             switch (cmd->type)
             {
                 case Metadata_type_generic:
@@ -545,6 +780,7 @@ static void write_metadata(WRBUF w, struct conf_service *service,
                     break;
                 default:
                     wrbuf_puts(w, "[can't represent]");
+                    break;
             }
             wrbuf_printf(w, "</md-%s>", cmd->name);
         }
@@ -558,7 +794,7 @@ static void write_subrecord(struct record *r, WRBUF w,
         client_get_database(r->client), PZ_NAME);
 
     wrbuf_puts(w, "<location id=\"");
-    wrbuf_xmlputs(w, client_get_database(r->client)->database->url);
+    wrbuf_xmlputs(w, client_get_id(r->client));
     wrbuf_puts(w, "\" ");
 
     wrbuf_puts(w, "name=\"");
@@ -618,11 +854,10 @@ void show_raw_reset(void *data, struct http_channel *c, void *data2)
 
 static void cmd_record_ready(void *data);
 
-static void cmd_record(struct http_channel *c)
+static void show_record(struct http_channel *c, struct http_session *s)
 {
     struct http_response *rs = c->response;
     struct http_request *rq = c->request;
-    struct http_session *s = locate_session(rq, rs);
     struct record_cluster *rec, *prev_r, *next_r;
     struct record *r;
     struct conf_service *service;
@@ -639,7 +874,7 @@ static void cmd_record(struct http_channel *c)
         return;
     }
     wrbuf_rewind(c->wrbuf);
-    if (!(rec = show_single(s->psession, idstr, &prev_r, &next_r)))
+    if (!(rec = show_single_start(s->psession, idstr, &prev_r, &next_r)))
     {
         if (session_active_clients(s->psession) == 0)
         {
@@ -660,7 +895,8 @@ static void cmd_record(struct http_channel *c)
         int i;
         struct record*r = rec->records;
         int binary = 0;
-
+        const char *nativesyntax = http_argbyname(rq, "nativesyntax");
+        
         if (binarystr && *binarystr != '0')
             binary = 1;
 
@@ -669,20 +905,20 @@ static void cmd_record(struct http_channel *c)
         if (!r)
         {
             error(rs, PAZPAR2_RECORD_FAIL, "no record at offset given");
-            return;
         }
         else
         {
             http_channel_observer_t obs =
                 http_add_observer(c, r->client, show_raw_reset);
             int ret = client_show_raw_begin(r->client, r->position,
-                                        syntax, esn, 
-                                        obs /* data */,
-                                        show_raw_record_error,
-                                        (binary ? 
-                                         show_raw_record_ok_binary : 
-                                         show_raw_record_ok),
-                                        (binary ? 1 : 0));
+                                            syntax, esn,
+                                            obs /* data */,
+                                            show_raw_record_error,
+                                            (binary ? 
+                                             show_raw_record_ok_binary : 
+                                             show_raw_record_ok),
+                                            (binary ? 1 : 0),
+                                            nativesyntax);
             if (ret == -1)
             {
                 http_remove_observer(obs);
@@ -692,8 +928,8 @@ static void cmd_record(struct http_channel *c)
     }
     else
     {
-        wrbuf_puts(c->wrbuf, HTTP_COMMAND_RESPONSE_PREFIX "<record>\n");
-        wrbuf_puts(c->wrbuf, "<recid>");
+        response_open_no_status(c, "record");
+        wrbuf_puts(c->wrbuf, "\n<recid>");
         wrbuf_xmlputs(c->wrbuf, rec->recid);
         wrbuf_puts(c->wrbuf, "</recid>\n");
         if (prev_r)
@@ -713,24 +949,36 @@ static void cmd_record(struct http_channel *c)
         write_metadata(c->wrbuf, service, rec->metadata, 1);
         for (r = rec->records; r; r = r->next)
             write_subrecord(r, c->wrbuf, service, 1);
-        wrbuf_puts(c->wrbuf, "</record>\n");
-        rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
-        http_send_response(c);
+        response_close(c, "record");
     }
+    show_single_stop(s->psession, rec);
 }
 
 static void cmd_record_ready(void *data)
 {
     struct http_channel *c = (struct http_channel *) data;
+    struct http_session *s = locate_session(c);
+    if (s) {
+        yaz_log(c->http_sessions->log_level, "Session %u: record watch released", s->session_id);
+        show_record(c, s);
+        release_session(c,s);
+    }
+}
 
-    cmd_record(c);
+static void cmd_record(struct http_channel *c)
+{
+    struct http_session *s = locate_session(c);
+    if (s) {
+        show_record(c, s);
+        release_session(c,s);
+    }
 }
 
-static void show_records(struct http_channel *c, int active)
+
+static void show_records(struct http_channel *c, struct http_session *s, int active)
 {
     struct http_request *rq = c->request;
     struct http_response *rs = c->response;
-    struct http_session *s = locate_session(rq, rs);
     struct record_cluster **rl;
     struct reclist_sortparms *sp;
     const char *start = http_argbyname(rq, "start");
@@ -739,7 +987,7 @@ static void show_records(struct http_channel *c, int active)
     int startn = 0;
     int numn = 20;
     int total;
-    int total_hits;
+    Odr_int total_hits;
     int i;
 
     if (!s)
@@ -759,15 +1007,15 @@ static void show_records(struct http_channel *c, int active)
     {
         error(rs, PAZPAR2_MALFORMED_PARAMETER_VALUE, "sort");
         return;
-    }
 
-    rl = show(s->psession, sp, startn, &numn, &total, &total_hits, c->nmem);
+    }
+    
+    rl = show_range_start(s->psession, sp, startn, &numn, &total, &total_hits);
 
-    wrbuf_rewind(c->wrbuf);
-    wrbuf_puts(c->wrbuf, HTTP_COMMAND_RESPONSE_PREFIX "<show>\n<status>OK</status>\n");
-    wrbuf_printf(c->wrbuf, "<activeclients>%d</activeclients>\n", active);
+    response_open(c, "show");
+    wrbuf_printf(c->wrbuf, "\n<activeclients>%d</activeclients>\n", active);
     wrbuf_printf(c->wrbuf, "<merged>%d</merged>\n", total);
-    wrbuf_printf(c->wrbuf, "<total>%d</total>\n", total_hits);
+    wrbuf_printf(c->wrbuf, "<total>" ODR_INT_PRINTF "</total>\n", total_hits);
     wrbuf_printf(c->wrbuf, "<start>%d</start>\n", startn);
     wrbuf_printf(c->wrbuf, "<num>%d</num>\n", numn);
 
@@ -785,100 +1033,121 @@ static void show_records(struct http_channel *c, int active)
         if (ccount > 1)
             wrbuf_printf(c->wrbuf, "<count>%d</count>\n", ccount);
        if (strstr(sort, "relevance"))
-           wrbuf_printf(c->wrbuf, "<relevance>%d</relevance>\n", rec->relevance);
+           wrbuf_printf(c->wrbuf, "<relevance>%d</relevance>\n",
+                         rec->relevance_score);
         wrbuf_puts(c->wrbuf, "<recid>");
         wrbuf_xmlputs(c->wrbuf, rec->recid);
         wrbuf_puts(c->wrbuf, "</recid>\n");
         wrbuf_puts(c->wrbuf, "</hit>\n");
     }
 
-    wrbuf_puts(c->wrbuf, "</show>\n");
-    rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
-    http_send_response(c);
+    show_range_stop(s->psession, rl);
+
+    response_close(c, "show");
 }
 
 static void show_records_ready(void *data)
 {
     struct http_channel *c = (struct http_channel *) data;
-
-    show_records(c, -1);
+    struct http_session *s = locate_session(c);
+    if (s) {
+        yaz_log(c->http_sessions->log_level, "Session %u: show watch released", s->session_id);
+        show_records(c, s, -1);
+    }
+    else {
+        /* some error message  */
+    }
+    release_session(c,s);
 }
 
 static void cmd_show(struct http_channel *c)
 {
-    struct http_request *rq = c->request;
+    struct http_request  *rq = c->request;
     struct http_response *rs = c->response;
-    struct http_session *s = locate_session(rq, rs);
+    struct http_session *s = locate_session(c);
     const char *block = http_argbyname(rq, "block");
+    const char *sort = http_argbyname(rq, "sort");
+    struct reclist_sortparms *sp;
     int status;
 
     if (!s)
         return;
 
+    if (!sort)
+        sort = "relevance";
+    
+    if (!(sp = reclist_parse_sortparms(c->nmem, sort, s->psession->service)))
+    {
+        error(c->response, PAZPAR2_MALFORMED_PARAMETER_VALUE, "sort");
+        release_session(c, s);
+        return;
+    }
+    session_sort(s->psession, sp->name, sp->increasing);
+
     status = session_active_clients(s->psession);
 
     if (block)
     {
-        if (status && reclist_get_num_records(s->psession->reclist) == 0)
+        if (!strcmp(block, "preferred") && !session_is_preferred_clients_ready(s->psession) && reclist_get_num_records(s->psession->reclist) == 0)
+        {
+            // if there is already a watch/block. we do not block this one
+            if (session_set_watch(s->psession, SESSION_WATCH_SHOW_PREF,
+                                  show_records_ready, c, c) == 0)
+            {
+                yaz_log(c->http_sessions->log_level,
+                        "Session %u: Blocking on command show (preferred targets)", s->session_id);
+            }
+            else
+            {
+                yaz_log(YLOG_WARN, "Attempt to block multiple times on show (preferred targets) block. Not supported!");
+                error(rs, PAZPAR2_ALREADY_BLOCKED, "show (preferred targets)"); 
+            }
+            release_session(c, s);
+            return;
+
+        }
+        else if (status)
         {
             // if there is already a watch/block. we do not block this one
             if (session_set_watch(s->psession, SESSION_WATCH_SHOW,
-                                  show_records_ready, c, c) != 0)
+                                  show_records_ready, c, c) != 0
+                )
+            {
+                yaz_log(YLOG_WARN, "Attempt to block multiple times on show block. Not supported!");
+                error(rs, PAZPAR2_ALREADY_BLOCKED, "show"); 
+            }
+            else
             {
-                yaz_log(YLOG_DEBUG, "Blocking on cmd_show");
+                yaz_log(c->http_sessions->log_level, "Session %u: Blocking on command show", s->session_id);
             }
+            release_session(c, s);
             return;
         }
     }
-
-    show_records(c, status);
+    show_records(c, s, status);
+    release_session(c, s);
 }
 
 static void cmd_ping(struct http_channel *c)
 {
-    struct http_request *rq = c->request;
-    struct http_response *rs = c->response;
-    struct http_session *s = locate_session(rq, rs);
+    struct http_session *s = locate_session(c);
     if (!s)
         return;
-    rs->payload = HTTP_COMMAND_RESPONSE_PREFIX "<ping><status>OK</status></ping>";
-    http_send_response(c);
-}
-
-static int utf_8_valid(const char *str)
-{
-    yaz_iconv_t cd = yaz_iconv_open("utf-8", "utf-8");
-    if (cd)
-    {
-        /* check that query is UTF-8 encoded */
-        char *inbuf = (char *) str; /* we know iconv does not alter this */
-        size_t inbytesleft = strlen(inbuf);
-
-        size_t outbytesleft = strlen(inbuf) + 10;
-        char *out = xmalloc(outbytesleft);
-        char *outbuf = out;
-        size_t r = yaz_iconv(cd, &inbuf, &inbytesleft, &outbuf, &outbytesleft);
-
-        /* if OK, try flushing the rest  */
-        if (r != (size_t) (-1))
-            r = yaz_iconv(cd, 0, 0, &outbuf, &outbytesleft);
-        yaz_iconv_close(cd);
-        xfree(out);
-        if (r == (size_t) (-1))
-            return 0;
-    }
-    return 1;
+    response_open(c, "ping");
+    response_close(c, "ping");
+    release_session(c, s);
 }
 
 static void cmd_search(struct http_channel *c)
 {
     struct http_request *rq = c->request;
     struct http_response *rs = c->response;
-    struct http_session *s = locate_session(rq, rs);
+    struct http_session *s = locate_session(c);
     const char *query = http_argbyname(rq, "query");
     const char *filter = http_argbyname(rq, "filter");
     const char *maxrecs = http_argbyname(rq, "maxrecs");
     const char *startrecs = http_argbyname(rq, "startrecs");
+    const char *limit = http_argbyname(rq, "limit");
     enum pazpar2_error_code code;
     const char *addinfo = 0;
 
@@ -887,29 +1156,32 @@ static void cmd_search(struct http_channel *c)
     if (!query)
     {
         error(rs, PAZPAR2_MISSING_PARAMETER, "query");
+        release_session(c, s);
         return;
     }
-    if (!utf_8_valid(query))
+    if (!yaz_utf8_check(query))
     {
         error(rs, PAZPAR2_MALFORMED_PARAMETER_ENCODING, "query");
+        release_session(c, s);
         return;
     }
-    code = search(s->psession, query, startrecs, maxrecs, filter, &addinfo);
+    code = session_search(s->psession, query, startrecs, maxrecs, filter, limit,
+                          &addinfo, "relevance", 0);
     if (code)
     {
         error(rs, code, addinfo);
+        release_session(c, s);
         return;
     }
-    rs->payload = HTTP_COMMAND_RESPONSE_PREFIX "<search><status>OK</status></search>";
-    http_send_response(c);
+    response_open(c, "search");
+    response_close(c, "search");
+    release_session(c, s);
 }
 
 
 static void cmd_stat(struct http_channel *c)
 {
-    struct http_request *rq = c->request;
-    struct http_response *rs = c->response;
-    struct http_session *s = locate_session(rq, rs);
+    struct http_session *s = locate_session(c);
     struct statistics stat;
     int clients;
 
@@ -921,14 +1193,14 @@ static void cmd_stat(struct http_channel *c)
     clients = session_active_clients(s->psession);
     statistics(s->psession, &stat);
 
-    if (stat.num_clients > 0) {
+    if (stat.num_clients > 0)
+    {
        progress = (stat.num_clients  - clients) / (float)stat.num_clients;
     }
 
-    wrbuf_rewind(c->wrbuf);
-    wrbuf_puts(c->wrbuf, HTTP_COMMAND_RESPONSE_PREFIX "<stat>");
+    response_open_no_status(c, "stat");
     wrbuf_printf(c->wrbuf, "<activeclients>%d</activeclients>\n", clients);
-    wrbuf_printf(c->wrbuf, "<hits>%d</hits>\n", stat.num_hits);
+    wrbuf_printf(c->wrbuf, "<hits>" ODR_INT_PRINTF "</hits>\n", stat.num_hits);
     wrbuf_printf(c->wrbuf, "<records>%d</records>\n", stat.num_records);
     wrbuf_printf(c->wrbuf, "<clients>%d</clients>\n", stat.num_clients);
     wrbuf_printf(c->wrbuf, "<unconnected>%d</unconnected>\n", stat.num_no_connection);
@@ -938,20 +1210,17 @@ static void cmd_stat(struct http_channel *c)
     wrbuf_printf(c->wrbuf, "<failed>%d</failed>\n", stat.num_failed);
     wrbuf_printf(c->wrbuf, "<error>%d</error>\n", stat.num_error);
     wrbuf_printf(c->wrbuf, "<progress>%.2f</progress>\n", progress);
-    wrbuf_puts(c->wrbuf, "</stat>");
-    rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
-    http_send_response(c);
+    response_close(c, "stat");
+    release_session(c, s);
 }
 
 static void cmd_info(struct http_channel *c)
 {
     char yaz_version_str[20];
-    struct http_response *rs = c->response;
 
-    wrbuf_rewind(c->wrbuf);
-    wrbuf_puts(c->wrbuf, HTTP_COMMAND_RESPONSE_PREFIX "<info>\n");
+    response_open_no_status(c, "info");
     wrbuf_puts(c->wrbuf, " <version>\n");
-    wrbuf_puts(c->wrbuf, "<pazpar2");
+    wrbuf_puts(c->wrbuf, "  <pazpar2");
 #ifdef PAZPAR2_VERSION_SHA1
     wrbuf_printf(c->wrbuf, " sha1=\"%s\"", PAZPAR2_VERSION_SHA1);
 #endif
@@ -959,7 +1228,6 @@ static void cmd_info(struct http_channel *c)
     wrbuf_xmlputs(c->wrbuf, VERSION);
     wrbuf_puts(c->wrbuf, "</pazpar2>");
 
-
     yaz_version(yaz_version_str, 0);
     wrbuf_puts(c->wrbuf, "  <yaz compiled=\"");
     wrbuf_xmlputs(c->wrbuf, YAZ_VERSION);
@@ -969,9 +1237,9 @@ static void cmd_info(struct http_channel *c)
 
     wrbuf_puts(c->wrbuf, " </version>\n");
     
-    wrbuf_puts(c->wrbuf, "</info>");
-    rs->payload = nmem_strdup(c->nmem, wrbuf_cstr(c->wrbuf));
-    http_send_response(c);
+    info_services(c->server, c->wrbuf);
+
+    response_close(c, "info");
 }
 
 struct {
@@ -986,6 +1254,8 @@ struct {
     { "search", cmd_search },
     { "termlist", cmd_termlist },
     { "exit", cmd_exit },
+    { "session-status", cmd_session_status },
+    { "server-status", cmd_server_status },
     { "ping", cmd_ping },
     { "record", cmd_record },
     { "info", cmd_info },