Strip #-suffix for ZOOM URLs PAZ-892
[pazpar2-moved-to-github.git] / src / connection.c
1 /* This file is part of Pazpar2.
2    Copyright (C) 2006-2013 Index Data
3
4 Pazpar2 is free software; you can redistribute it and/or modify it under
5 the terms of the GNU General Public License as published by the Free
6 Software Foundation; either version 2, or (at your option) any later
7 version.
8
9 Pazpar2 is distributed in the hope that it will be useful, but WITHOUT ANY
10 WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
17
18 */
19
20 /** \file connection.c
21     \brief Z39.50 connection (low-level client)
22 */
23
24 #if HAVE_CONFIG_H
25 #include <config.h>
26 #endif
27
28 #include <stdlib.h>
29 #include <stdio.h>
30 #include <string.h>
31 #if HAVE_SYS_TIME_H
32 #include <sys/time.h>
33 #endif
34 #if HAVE_UNISTD_H
35 #include <unistd.h>
36 #endif
37
38 #include <signal.h>
39 #include <assert.h>
40
41 #include <yaz/log.h>
42 #include <yaz/comstack.h>
43 #include <yaz/tcpip.h>
44 #include "connection.h"
45 #include "session.h"
46 #include "host.h"
47 #include "client.h"
48 #include "settings.h"
49
50 /* connection counting (1) , disable connection counting (0) */
51 #if 1
52 static YAZ_MUTEX g_mutex = 0;
53 static int no_connections = 0;
54 static int total_no_connections = 0;
55
56 static int connection_use(int delta)
57 {
58     int result;
59     if (!g_mutex)
60         yaz_mutex_create(&g_mutex);
61     yaz_mutex_enter(g_mutex);
62     no_connections += delta;
63     result = no_connections;
64     if (delta > 0)
65         total_no_connections += delta;
66     yaz_mutex_leave(g_mutex);
67     if (delta == 0)
68             return result;
69     yaz_log(YLOG_LOG, "%s connections=%d", delta > 0 ? "INC" : "DEC",
70             no_connections);
71     return result;
72 }
73
74 int connections_count(void)
75 {
76     return connection_use(0);
77 }
78
79
80 #else
81 #define connection_use(x)
82 #define connections_count(x) 0
83 #define connections_count_total(x) 0
84 #endif
85
86
87 /** \brief Represents a physical, reusable  connection to a remote Z39.50 host
88  */
89 struct connection {
90     IOCHAN iochan;
91     ZOOM_connection link;
92     struct host *host;
93     struct client *client;
94     char *zproxy;
95     char *url;
96     enum {
97         Conn_Closed,
98         Conn_Connecting,
99         Conn_Open
100     } state;
101     int operation_timeout;
102     int session_timeout;
103     struct connection *next; // next for same host or next in free list
104 };
105
106 static int connection_connect(struct connection *con, iochan_man_t iochan_man);
107
108 static int connection_is_idle(struct connection *co)
109 {
110     ZOOM_connection link = co->link;
111     int event;
112
113     if (co->state != Conn_Open || !link)
114         return 0;
115
116     if (!ZOOM_connection_is_idle(link))
117         return 0;
118     event = ZOOM_connection_peek_event(link);
119     if (event == ZOOM_EVENT_NONE)
120         return 1;
121     else
122         return 0;
123 }
124
125 ZOOM_connection connection_get_link(struct connection *co)
126 {
127     return co->link;
128 }
129
130 static void remove_connection_from_host(struct connection *con)
131 {
132     struct connection **conp = &con->host->connections;
133     assert(con);
134     while (*conp)
135     {
136         if (*conp == con)
137         {
138             *conp = (*conp)->next;
139             break;
140         }
141         conp = &(*conp)->next;
142     }
143     yaz_cond_broadcast(con->host->cond_ready);
144 }
145
146 // Close connection and recycle structure
147 static void connection_destroy(struct connection *co)
148 {
149     if (co->link)
150     {
151         ZOOM_connection_destroy(co->link);
152         iochan_destroy(co->iochan);
153     }
154     yaz_log(YLOG_DEBUG, "%p Connection destroy %s", co, co->url);
155
156     if (co->client)
157     {
158         client_disconnect(co->client);
159     }
160
161     xfree(co->zproxy);
162     xfree(co->url);
163     xfree(co);
164     connection_use(-1);
165 }
166
167 // Creates a new connection for client, associated with the host of
168 // client's database
169 static struct connection *connection_create(struct client *cl,
170                                             const char *url,
171                                             struct host *host,
172                                             int operation_timeout,
173                                             int session_timeout,
174                                             iochan_man_t iochan_man)
175 {
176     struct connection *co;
177
178     co = xmalloc(sizeof(*co));
179     co->host = host;
180
181     co->client = cl;
182     co->url = xstrdup(url);
183     co->zproxy = 0;
184     client_set_connection(cl, co);
185     co->link = 0;
186     co->state = Conn_Closed;
187     co->operation_timeout = operation_timeout;
188     co->session_timeout = session_timeout;
189
190     if (host->ipport)
191         connection_connect(co, iochan_man);
192
193     yaz_mutex_enter(host->mutex);
194     co->next = co->host->connections;
195     co->host->connections = co;
196     yaz_mutex_leave(host->mutex);
197
198     connection_use(1);
199     return co;
200 }
201
202 static void non_block_events(struct connection *co)
203 {
204     int got_records = 0;
205     IOCHAN iochan = co->iochan;
206     ZOOM_connection link = co->link;
207     while (1)
208     {
209         struct client *cl = co->client;
210         int ev;
211         int r = ZOOM_event_nonblock(1, &link);
212         if (!r)
213             break;
214         if (!cl)
215             continue;
216         ev = ZOOM_connection_last_event(link);
217
218 #if 1
219         yaz_log(YLOG_DEBUG, "%p Connection ZOOM_EVENT_%s", co, ZOOM_get_event_str(ev));
220 #endif
221         switch (ev)
222         {
223         case ZOOM_EVENT_TIMEOUT:
224             break;
225         case ZOOM_EVENT_END:
226             {
227                 const char *error, *addinfo;
228                 int err;
229                 if ((err = ZOOM_connection_error(link, &error, &addinfo)))
230                 {
231                     yaz_log(YLOG_LOG, "Error %s from %s",
232                             error, client_get_id(cl));
233                     client_set_diagnostic(cl, err, error, addinfo);
234                     client_set_state(cl, Client_Error);
235                 }
236                 else
237                 {
238                     iochan_settimeout(iochan, co->session_timeout);
239                     client_set_state(cl, Client_Idle);
240                 }
241                 yaz_cond_broadcast(co->host->cond_ready);
242             }
243             break;
244         case ZOOM_EVENT_SEND_DATA:
245             break;
246         case ZOOM_EVENT_RECV_DATA:
247             break;
248         case ZOOM_EVENT_UNKNOWN:
249             break;
250         case ZOOM_EVENT_SEND_APDU:
251             client_set_state(co->client, Client_Working);
252             iochan_settimeout(iochan, co->operation_timeout);
253             break;
254         case ZOOM_EVENT_RECV_APDU:
255             break;
256         case ZOOM_EVENT_CONNECT:
257             yaz_log(YLOG_LOG, "Connected to %s", client_get_id(cl));
258             co->state = Conn_Open;
259             break;
260         case ZOOM_EVENT_RECV_SEARCH:
261             client_search_response(cl);
262             break;
263         case ZOOM_EVENT_RECV_RECORD:
264             client_record_response(cl, &got_records);
265             break;
266         default:
267             yaz_log(YLOG_LOG, "Unhandled event (%d) from %s",
268                     ev, client_get_id(cl));
269             break;
270         }
271     }
272     if (got_records)
273     {
274         struct client *cl = co->client;
275         if (cl)
276         {
277             client_check_preferred_watch(cl);
278             client_got_records(cl);
279         }
280     }
281 }
282
283 void connection_continue(struct connection *co)
284 {
285     int r = ZOOM_connection_exec_task(co->link);
286     if (!r)
287         non_block_events(co);
288     else
289     {
290         iochan_setflags(co->iochan, ZOOM_connection_get_mask(co->link));
291         iochan_setfd(co->iochan, ZOOM_connection_get_socket(co->link));
292     }
293 }
294
295 static void connection_handler(IOCHAN iochan, int event)
296 {
297     struct connection *co = iochan_getdata(iochan);
298     struct client *cl;
299     struct host *host = co->host;
300
301     yaz_mutex_enter(host->mutex);
302     cl = co->client;
303     if (!cl)
304     {
305         /* no client associated with it.. We are probably getting
306            a closed connection from the target.. Or, perhaps, an unexpected
307            package.. We will just close the connection */
308         yaz_log(YLOG_LOG, "timeout connection %p event=%d", co, event);
309         remove_connection_from_host(co);
310         yaz_mutex_leave(host->mutex);
311         connection_destroy(co);
312     }
313     else if (event & EVENT_TIMEOUT)
314     {
315         ZOOM_connection_fire_event_timeout(co->link);
316         client_lock(cl);
317         non_block_events(co);
318         client_unlock(cl);
319
320         remove_connection_from_host(co);
321         yaz_mutex_leave(host->mutex);
322         connection_destroy(co);
323     }
324     else
325     {
326         yaz_mutex_leave(host->mutex);
327
328         client_lock(cl);
329         non_block_events(co);
330
331         ZOOM_connection_fire_event_socket(co->link, event);
332
333         non_block_events(co);
334         client_unlock(cl);
335
336         if (co->link)
337         {
338             iochan_setflags(iochan, ZOOM_connection_get_mask(co->link));
339             iochan_setfd(iochan, ZOOM_connection_get_socket(co->link));
340         }
341     }
342 }
343
344
345 // Disassociate connection from client
346 static void connection_release(struct connection *co)
347 {
348     struct client *cl = co->client;
349
350     if (!cl)
351         return;
352     client_set_connection(cl, 0);
353     co->client = 0;
354 }
355
356 void connect_resolver_host(struct host *host, iochan_man_t iochan_man)
357 {
358     struct connection *con;
359
360     yaz_mutex_enter(host->mutex);
361     con = host->connections;
362     while (con)
363     {
364         if (con->state == Conn_Closed)
365         {
366             if (!host->ipport || !con->client) /* unresolved or no client */
367             {
368                 remove_connection_from_host(con);
369                 yaz_mutex_leave(host->mutex);
370                 connection_destroy(con);
371             }
372             else
373             {
374                 struct session_database *sdb = client_get_database(con->client);
375                 if (sdb)
376                 {
377                     yaz_mutex_leave(host->mutex);
378                     connection_connect(con, iochan_man);
379                     client_start_search(con->client);
380                 }
381                 else
382                 {
383                     remove_connection_from_host(con);
384                     yaz_mutex_leave(host->mutex);
385                     connection_destroy(con);
386                 }
387             }
388             /* start all over .. at some point it will be NULL */
389             yaz_mutex_enter(host->mutex);
390             con = host->connections;
391         }
392         else
393         {
394             yaz_log(YLOG_LOG, "connect_resolver_host: state=%d", con->state);
395             con = con->next;
396         }
397     }
398     yaz_mutex_leave(host->mutex);
399 }
400
401 static struct host *connection_get_host(struct connection *con)
402 {
403     return con->host;
404 }
405
406 static int connection_connect(struct connection *con, iochan_man_t iochan_man)
407 {
408     struct host *host = connection_get_host(con);
409     ZOOM_options zoptions = ZOOM_options_create();
410     const char *auth;
411     const char *charset;
412     const char *sru;
413     const char *sru_version = 0;
414     WRBUF w;
415
416     struct session_database *sdb = client_get_database(con->client);
417     const char *apdulog = session_setting_oneval(sdb, PZ_APDULOG);
418
419     assert(con);
420
421     ZOOM_options_set(zoptions, "async", "1");
422     ZOOM_options_set(zoptions, "implementationName", PACKAGE_NAME);
423     ZOOM_options_set(zoptions, "implementationVersion", VERSION);
424
425     if ((charset = session_setting_oneval(sdb, PZ_NEGOTIATION_CHARSET)))
426         ZOOM_options_set(zoptions, "charset", charset);
427
428     assert(host->ipport);
429     if (host->proxy)
430     {
431         yaz_log(YLOG_LOG, "proxy=%s", host->ipport);
432         ZOOM_options_set(zoptions, "proxy", host->ipport);
433     }
434     else
435     {
436         assert(host->tproxy);
437         yaz_log(YLOG_LOG, "tproxy=%s", host->ipport);
438         ZOOM_options_set(zoptions, "tproxy", host->ipport);
439     }
440
441     if (apdulog && *apdulog)
442         ZOOM_options_set(zoptions, "apdulog", apdulog);
443
444     if ((auth = session_setting_oneval(sdb, PZ_AUTHENTICATION)))
445     {
446         const char *cp1 = strchr(auth, ' ');
447         if (!cp1)
448             ZOOM_options_set(zoptions, "user", auth);
449         else
450         {
451             const char *cp2 = strchr(cp1 + 1, ' ');
452
453             ZOOM_options_setl(zoptions, "user", auth, cp1 - auth);
454             if (!cp2)
455                 ZOOM_options_set(zoptions, "password", cp1 + 1);
456             else
457             {
458                 ZOOM_options_setl(zoptions, "group", cp1 + 1, cp2 - cp1 - 1);
459                 ZOOM_options_set(zoptions, "password", cp2 + 1);
460             }
461         }
462     }
463     if ((sru = session_setting_oneval(sdb, PZ_SRU)) && *sru)
464         ZOOM_options_set(zoptions, "sru", sru);
465     if ((sru_version = session_setting_oneval(sdb, PZ_SRU_VERSION))
466         && *sru_version)
467         ZOOM_options_set(zoptions, "sru_version", sru_version);
468     if (!(con->link = ZOOM_connection_create(zoptions)))
469     {
470         yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create ZOOM Connection");
471         ZOOM_options_destroy(zoptions);
472         return -1;
473     }
474
475     w = wrbuf_alloc();
476     if (sru && *sru && !strstr(con->url, "://"))
477         wrbuf_puts(w, "http://");
478     if (strchr(con->url, '#'))
479     {
480         const char *cp = strchr(con->url, '#');
481         wrbuf_write(w, con->url, cp - con->url);
482     }
483     else
484         wrbuf_puts(w, con->url);
485
486     ZOOM_connection_connect(con->link, wrbuf_cstr(w), 0);
487
488     con->iochan = iochan_create(-1, connection_handler, 0, "connection_socket");
489     con->state = Conn_Connecting;
490     iochan_settimeout(con->iochan, con->operation_timeout);
491     iochan_setdata(con->iochan, con);
492     iochan_add(iochan_man, con->iochan);
493
494     client_set_state(con->client, Client_Connecting);
495     ZOOM_options_destroy(zoptions);
496     wrbuf_destroy(w);
497     return 0;
498 }
499
500 // Ensure that client has a connection associated
501 int client_prep_connection(struct client *cl,
502                            int operation_timeout, int session_timeout,
503                            iochan_man_t iochan_man,
504                            const struct timeval *abstime)
505 {
506     struct connection *co;
507     struct session_database *sdb = client_get_database(cl);
508     const char *zproxy = session_setting_oneval(sdb, PZ_ZPROXY);
509     const char *url = session_setting_oneval(sdb, PZ_URL);
510     const char *sru = session_setting_oneval(sdb, PZ_SRU);
511     struct host *host = 0;
512     int default_port = *sru ? 80 : 210;
513
514     if (zproxy && zproxy[0] == '\0')
515         zproxy = 0;
516
517     if (!url || !*url)
518         url = sdb->database->id;
519
520     host = find_host(client_get_session(cl)->service->server->database_hosts,
521                      url, zproxy, default_port, iochan_man);
522
523     yaz_log(YLOG_DEBUG, "client_prep_connection: target=%s url=%s",
524             client_get_id(cl), url);
525     if (!host)
526         return 0;
527
528     co = client_get_connection(cl);
529     if (co)
530     {
531         assert(co->host);
532         if (co->host == host && client_get_state(cl) == Client_Idle)
533         {
534             return 2;
535         }
536         connection_release(co);
537         co = 0;
538     }
539     if (!co)
540     {
541         int max_connections = 0;
542         int reuse_connections = 1;
543         const char *v = session_setting_oneval(client_get_database(cl),
544                                                PZ_MAX_CONNECTIONS);
545         if (v && *v)
546             max_connections = atoi(v);
547
548         v = session_setting_oneval(client_get_database(cl),
549                 PZ_REUSE_CONNECTIONS);
550         if (v && *v)
551             reuse_connections = atoi(v);
552
553         // See if someone else has an idle connection
554         // We should look at timestamps here to select the longest-idle connection
555         yaz_mutex_enter(host->mutex);
556         while (1)
557         {
558             int num_connections = 0;
559             for (co = host->connections; co; co = co->next)
560                 num_connections++;
561             if (reuse_connections)
562             {
563                 for (co = host->connections; co; co = co->next)
564                 {
565                     if (connection_is_idle(co) &&
566                         !strcmp(url, co->url) &&
567                         (!co->client || client_get_state(co->client) == Client_Idle) &&
568                         !strcmp(ZOOM_connection_option_get(co->link, "user"),
569                                 session_setting_oneval(client_get_database(cl),
570                                                        PZ_AUTHENTICATION)))
571                     {
572                         if (zproxy == 0 && co->zproxy == 0)
573                             break;
574                         if (zproxy && co->zproxy && !strcmp(zproxy, co->zproxy))
575                             break;
576                     }
577                 }
578                 if (co)
579                 {
580                     yaz_log(YLOG_LOG, "num_connections = %d (reusing)", num_connections);
581                     break;
582                 }
583             }
584             if (max_connections <= 0 || num_connections < max_connections)
585             {
586                 yaz_log(YLOG_LOG, "num_connections = %d (new); max = %d",
587                         num_connections, max_connections);
588                 break;
589             }
590             yaz_log(YLOG_LOG, "num_connections = %d (waiting) max = %d",
591                     num_connections, max_connections);
592             if (yaz_cond_wait(host->cond_ready, host->mutex, abstime))
593             {
594                 yaz_log(YLOG_LOG, "out of connections %s", client_get_id(cl));
595                 client_set_state(cl, Client_Error);
596                 yaz_mutex_leave(host->mutex);
597                 return 0;
598             }
599         }
600         if (co)
601         {
602             yaz_log(YLOG_LOG,  "%p Connection reuse. state: %d", co, co->state);
603             connection_release(co);
604             client_set_connection(cl, co);
605             co->client = cl;
606             /* ensure that connection is only assigned to this client
607                by marking the client non Idle */
608             client_set_state(cl, Client_Working);
609             yaz_mutex_leave(host->mutex);
610             co->operation_timeout = operation_timeout;
611             co->session_timeout = session_timeout;
612             /* tells ZOOM to reconnect if necessary. Disabled becuase
613                the ZOOM_connection_connect flushes the task queue */
614             ZOOM_connection_connect(co->link, 0, 0);
615         }
616         else
617         {
618             yaz_mutex_leave(host->mutex);
619             co = connection_create(cl, url, host,
620                                    operation_timeout, session_timeout,
621                                    iochan_man);
622         }
623         assert(co->host);
624     }
625
626     if (co && co->link)
627         return 1;
628     else
629         return 0;
630 }
631
632 /*
633  * Local variables:
634  * c-basic-offset: 4
635  * c-file-style: "Stroustrup"
636  * indent-tabs-mode: nil
637  * End:
638  * vim: shiftwidth=4 tabstop=8 expandtab
639  */
640