Re-factor: move work in client_check_preferred_watch to client_got_records
[pazpar2-moved-to-github.git] / src / connection.c
1 /* This file is part of Pazpar2.
2    Copyright (C) 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                     struct session *se = client_get_session(cl);
232
233                     session_log(se, YLOG_WARN, "%s: Error %s (%s)",
234                                 client_get_id(cl), error, addinfo);
235                     client_set_diagnostic(cl, err, error, addinfo);
236                     client_set_state(cl, Client_Error);
237                 }
238                 else
239                 {
240                     iochan_settimeout(iochan, co->session_timeout);
241                     client_set_state(cl, Client_Idle);
242                 }
243                 yaz_cond_broadcast(co->host->cond_ready);
244             }
245             break;
246         case ZOOM_EVENT_SEND_DATA:
247             break;
248         case ZOOM_EVENT_RECV_DATA:
249             break;
250         case ZOOM_EVENT_UNKNOWN:
251             break;
252         case ZOOM_EVENT_SEND_APDU:
253             client_set_state(co->client, Client_Working);
254             iochan_settimeout(iochan, co->operation_timeout);
255             break;
256         case ZOOM_EVENT_RECV_APDU:
257             break;
258         case ZOOM_EVENT_CONNECT:
259             co->state = Conn_Open;
260             break;
261         case ZOOM_EVENT_RECV_SEARCH:
262             client_search_response(cl);
263             break;
264         case ZOOM_EVENT_RECV_RECORD:
265             client_record_response(cl, &got_records);
266             break;
267         default:
268             yaz_log(YLOG_LOG, "Unhandled event (%d) from %s",
269                     ev, client_get_id(cl));
270             break;
271         }
272     }
273     if (got_records)
274     {
275         struct client *cl = co->client;
276         if (cl)
277             client_got_records(cl);
278     }
279 }
280
281 void connection_continue(struct connection *co)
282 {
283     int r = ZOOM_connection_exec_task(co->link);
284     if (!r)
285     {
286         struct client *cl = co->client;
287
288         client_lock(cl);
289         non_block_events(co);
290         client_unlock(cl);
291     }
292     else
293     {
294         iochan_setflags(co->iochan, ZOOM_connection_get_mask(co->link));
295         iochan_setfd(co->iochan, ZOOM_connection_get_socket(co->link));
296     }
297 }
298
299 static void connection_handler(IOCHAN iochan, int event)
300 {
301     struct connection *co = iochan_getdata(iochan);
302     struct client *cl;
303     struct host *host = co->host;
304
305     yaz_mutex_enter(host->mutex);
306     cl = co->client;
307     if (!cl)
308     {
309         /* no client associated with it.. We are probably getting
310            a closed connection from the target.. Or, perhaps, an unexpected
311            package.. We will just close the connection */
312         yaz_log(YLOG_LOG, "timeout connection %p event=%d", co, event);
313         remove_connection_from_host(co);
314         yaz_mutex_leave(host->mutex);
315         connection_destroy(co);
316     }
317     else if (event & EVENT_TIMEOUT)
318     {
319         ZOOM_connection_fire_event_timeout(co->link);
320         client_lock(cl);
321         non_block_events(co);
322         client_unlock(cl);
323
324         remove_connection_from_host(co);
325         yaz_mutex_leave(host->mutex);
326         connection_destroy(co);
327     }
328     else
329     {
330         yaz_mutex_leave(host->mutex);
331
332         client_lock(cl);
333         non_block_events(co);
334
335         ZOOM_connection_fire_event_socket(co->link, event);
336
337         non_block_events(co);
338         client_unlock(cl);
339
340         if (co->link)
341         {
342             iochan_setflags(iochan, ZOOM_connection_get_mask(co->link));
343             iochan_setfd(iochan, ZOOM_connection_get_socket(co->link));
344         }
345     }
346 }
347
348
349 // Disassociate connection from client
350 static void connection_release(struct connection *co)
351 {
352     struct client *cl = co->client;
353
354     if (!cl)
355         return;
356     client_set_connection(cl, 0);
357     co->client = 0;
358 }
359
360 void connection_release2(struct connection *co)
361 {
362     co->client = 0;
363 }
364
365 void connect_resolver_host(struct host *host, iochan_man_t iochan_man)
366 {
367     struct connection *con;
368
369     yaz_mutex_enter(host->mutex);
370     con = host->connections;
371     while (con)
372     {
373         if (con->state == Conn_Closed)
374         {
375             struct client *cl = con->client;
376             if (!host->ipport || !cl) /* unresolved or no client */
377             {
378                 remove_connection_from_host(con);
379                 yaz_mutex_leave(host->mutex);
380                 connection_destroy(con);
381             }
382             else
383             {
384                 struct session_database *sdb = client_get_database(cl);
385                 struct session *se = client_get_session(cl);
386                 if (sdb && se)
387                 {
388                     yaz_mutex_leave(host->mutex);
389                     client_start_search(cl);
390                 }
391                 else
392                 {
393                     remove_connection_from_host(con);
394                     yaz_mutex_leave(host->mutex);
395                     connection_destroy(con);
396                 }
397             }
398             /* start all over .. at some point it will be NULL */
399             yaz_mutex_enter(host->mutex);
400             con = host->connections;
401         }
402         else
403         {
404             con = con->next;
405         }
406     }
407     yaz_mutex_leave(host->mutex);
408 }
409
410 static struct host *connection_get_host(struct connection *con)
411 {
412     return con->host;
413 }
414
415 static int connection_connect(struct connection *con, iochan_man_t iochan_man)
416 {
417     struct host *host = connection_get_host(con);
418     ZOOM_options zoptions = ZOOM_options_create();
419     const char *auth;
420     const char *charset;
421     const char *sru;
422     const char *sru_version = 0;
423     const char *value;
424     WRBUF w;
425
426     struct session_database *sdb = client_get_database(con->client);
427     const char *apdulog = session_setting_oneval(sdb, PZ_APDULOG);
428     const char *memcached = session_setting_oneval(sdb, PZ_MEMCACHED);
429     const char *redis = session_setting_oneval(sdb, PZ_REDIS);
430
431     assert(con);
432
433     ZOOM_options_set(zoptions, "async", "1");
434     ZOOM_options_set(zoptions, "implementationName", PACKAGE_NAME);
435     ZOOM_options_set(zoptions, "implementationVersion", VERSION);
436
437     if ((charset = session_setting_oneval(sdb, PZ_NEGOTIATION_CHARSET)))
438         ZOOM_options_set(zoptions, "charset", charset);
439     if (memcached && *memcached)
440         ZOOM_options_set(zoptions, "memcached", memcached);
441     if (redis && *redis)
442         ZOOM_options_set(zoptions, "redis", redis);
443
444     assert(host->ipport);
445     if (host->proxy)
446     {
447         yaz_log(YLOG_LOG, "proxy=%s", host->ipport);
448         ZOOM_options_set(zoptions, "proxy", host->ipport);
449     }
450     else
451     {
452         assert(host->tproxy);
453         yaz_log(YLOG_LOG, "tproxy=%s", host->ipport);
454         ZOOM_options_set(zoptions, "tproxy", host->ipport);
455     }
456
457     if (apdulog && *apdulog)
458         ZOOM_options_set(zoptions, "apdulog", apdulog);
459
460
461     if ((sru = session_setting_oneval(sdb, PZ_SRU)) && *sru)
462         ZOOM_options_set(zoptions, "sru", sru);
463     if ((sru_version = session_setting_oneval(sdb, PZ_SRU_VERSION))
464         && *sru_version)
465         ZOOM_options_set(zoptions, "sru_version", sru_version);
466
467     if ((auth = session_setting_oneval(sdb, PZ_AUTHENTICATION)))
468     {
469         /* allow splitting user and reset with a blank always */
470         const char *cp1 = strchr(auth, ' ');
471         if (!cp1 && sru && *sru)
472             cp1 =  strchr(auth, '/');
473         if (!cp1)
474         {
475             /* Z39.50 user/password style, or no password for SRU */
476             ZOOM_options_set(zoptions, "user", auth);
477         }
478         else
479         {
480             /* now consider group as well */
481             const char *cp2 = strchr(cp1 + 1, ' ');
482
483             ZOOM_options_setl(zoptions, "user", auth, cp1 - auth);
484             if (!cp2)
485                 ZOOM_options_set(zoptions, "password", cp1 + 1);
486             else
487             {
488                 ZOOM_options_setl(zoptions, "group", cp1 + 1, cp2 - cp1 - 1);
489                 ZOOM_options_set(zoptions, "password", cp2 + 1);
490             }
491         }
492     }
493
494     value = session_setting_oneval(sdb, PZ_AUTHENTICATION_MODE);
495     if (value && *value)
496         ZOOM_options_set(zoptions, "authenticationMode", value);
497
498     if (!(con->link = ZOOM_connection_create(zoptions)))
499     {
500         yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create ZOOM Connection");
501         ZOOM_options_destroy(zoptions);
502         return -1;
503     }
504
505     w = wrbuf_alloc();
506     if (sru && *sru && !strstr(con->url, "://"))
507         wrbuf_puts(w, "http://");
508     if (strchr(con->url, '#'))
509     {
510         const char *cp = strchr(con->url, '#');
511         wrbuf_write(w, con->url, cp - con->url);
512     }
513     else
514         wrbuf_puts(w, con->url);
515
516     ZOOM_connection_connect(con->link, wrbuf_cstr(w), 0);
517
518     con->iochan = iochan_create(-1, connection_handler, 0, "connection_socket");
519     con->state = Conn_Connecting;
520     iochan_settimeout(con->iochan, con->operation_timeout);
521     iochan_setdata(con->iochan, con);
522     iochan_add(iochan_man, con->iochan);
523
524     client_set_state(con->client, Client_Connecting);
525     ZOOM_options_destroy(zoptions);
526     wrbuf_destroy(w);
527     return 0;
528 }
529
530 // Ensure that client has a connection associated
531 int client_prep_connection(struct client *cl,
532                            int operation_timeout, int session_timeout,
533                            iochan_man_t iochan_man,
534                            const struct timeval *abstime)
535 {
536     struct connection *co;
537     struct session_database *sdb = client_get_database(cl);
538     const char *zproxy = session_setting_oneval(sdb, PZ_ZPROXY);
539     const char *url = session_setting_oneval(sdb, PZ_URL);
540     const char *sru = session_setting_oneval(sdb, PZ_SRU);
541     struct host *host = 0;
542     int default_port = *sru ? 80 : 210;
543
544     if (zproxy && zproxy[0] == '\0')
545         zproxy = 0;
546
547     if (!url || !*url)
548         url = sdb->database->id;
549
550     host = find_host(client_get_session(cl)->service->server->database_hosts,
551                      url, zproxy, default_port, iochan_man);
552
553     yaz_log(YLOG_DEBUG, "client_prep_connection: target=%s url=%s",
554             client_get_id(cl), url);
555     if (!host)
556         return 0;
557
558     co = client_get_connection(cl);
559     if (co)
560     {
561         assert(co->host);
562         if (co->host == host && client_get_state(cl) == Client_Idle)
563         {
564             return 2;
565         }
566         connection_release(co);
567         co = 0;
568     }
569     if (!co)
570     {
571         int max_connections = 0;
572         int reuse_connections = 1;
573         const char *v = session_setting_oneval(client_get_database(cl),
574                                                PZ_MAX_CONNECTIONS);
575         if (v && *v)
576             max_connections = atoi(v);
577
578         v = session_setting_oneval(client_get_database(cl),
579                 PZ_REUSE_CONNECTIONS);
580         if (v && *v)
581             reuse_connections = atoi(v);
582
583         // See if someone else has an idle connection
584         // We should look at timestamps here to select the longest-idle connection
585         yaz_mutex_enter(host->mutex);
586         while (1)
587         {
588             int num_connections = 0;
589             for (co = host->connections; co; co = co->next)
590                 num_connections++;
591             if (reuse_connections)
592             {
593                 for (co = host->connections; co; co = co->next)
594                 {
595                     if (connection_is_idle(co) &&
596                         !strcmp(url, co->url) &&
597                         (!co->client || client_get_state(co->client) == Client_Idle) &&
598                         !strcmp(ZOOM_connection_option_get(co->link, "user"),
599                                 session_setting_oneval(client_get_database(cl),
600                                                        PZ_AUTHENTICATION)))
601                     {
602                         if (zproxy == 0 && co->zproxy == 0)
603                             break;
604                         if (zproxy && co->zproxy && !strcmp(zproxy, co->zproxy))
605                             break;
606                     }
607                 }
608                 if (co)
609                 {
610                     yaz_log(YLOG_LOG, "num_connections = %d (reusing)", num_connections);
611                     break;
612                 }
613             }
614             if (max_connections <= 0 || num_connections < max_connections)
615             {
616                 yaz_log(YLOG_LOG, "num_connections = %d (new); max = %d",
617                         num_connections, max_connections);
618                 break;
619             }
620             yaz_log(YLOG_LOG, "num_connections = %d (waiting) max = %d",
621                     num_connections, max_connections);
622             if (yaz_cond_wait(host->cond_ready, host->mutex, abstime))
623             {
624                 yaz_log(YLOG_LOG, "out of connections %s", client_get_id(cl));
625                 client_set_state(cl, Client_Error);
626                 yaz_mutex_leave(host->mutex);
627                 return 0;
628             }
629         }
630         if (co)
631         {
632             yaz_log(YLOG_LOG,  "%p Connection reuse. state: %d", co, co->state);
633             connection_release(co);
634             client_set_connection(cl, co);
635             co->client = cl;
636             /* ensure that connection is only assigned to this client
637                by marking the client non Idle */
638             client_set_state(cl, Client_Working);
639             yaz_mutex_leave(host->mutex);
640             co->operation_timeout = operation_timeout;
641             co->session_timeout = session_timeout;
642             /* tells ZOOM to reconnect if necessary. Disabled becuase
643                the ZOOM_connection_connect flushes the task queue */
644             ZOOM_connection_connect(co->link, 0, 0);
645         }
646         else
647         {
648             yaz_mutex_leave(host->mutex);
649             co = connection_create(cl, url, host,
650                                    operation_timeout, session_timeout,
651                                    iochan_man);
652         }
653         assert(co->host);
654     }
655
656     if (co && co->link)
657         return 1;
658     else
659         return 0;
660 }
661
662 /*
663  * Local variables:
664  * c-basic-offset: 4
665  * c-file-style: "Stroustrup"
666  * indent-tabs-mode: nil
667  * End:
668  * vim: shiftwidth=4 tabstop=8 expandtab
669  */
670