Discover lost connections immediately
[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 "client.h"
47 #include "settings.h"
48
49 /* connection counting (1) , disable connection counting (0) */
50 #if 1
51 static YAZ_MUTEX g_mutex = 0;
52 static int no_connections = 0;
53 static int total_no_connections = 0;
54
55 static int connection_use(int delta)
56 {
57     int result;
58     if (!g_mutex)
59         yaz_mutex_create(&g_mutex);
60     yaz_mutex_enter(g_mutex);
61     no_connections += delta;
62     result = no_connections;
63     if (delta > 0)
64         total_no_connections += delta;
65     yaz_mutex_leave(g_mutex);
66     if (delta == 0)
67             return result;
68     yaz_log(YLOG_LOG, "%s connections=%d", delta > 0 ? "INC" : "DEC",
69             no_connections);
70     return result;
71 }
72
73 int connections_count(void)
74 {
75     return connection_use(0);
76 }
77
78
79 #else
80 #define connection_use(x)
81 #define connections_count(x) 0
82 #define connections_count_total(x) 0
83 #endif
84
85
86 /** \brief Represents a physical, reusable  connection to a remote Z39.50 host
87  */
88 struct connection {
89     IOCHAN iochan;
90     ZOOM_connection link;
91     struct client *client;
92     char *zproxy;
93     char *url;
94     enum {
95         Conn_Closed,
96         Conn_Connecting,
97         Conn_Open
98     } state;
99     int operation_timeout;
100     int session_timeout;
101     struct connection *next; // next for same host or next in free list
102 };
103
104 static int connection_connect(struct connection *con, iochan_man_t iochan_man);
105
106 static int connection_is_idle(struct connection *co)
107 {
108     ZOOM_connection link = co->link;
109     int event;
110
111     if (co->state != Conn_Open || !link)
112         return 0;
113
114     if (!ZOOM_connection_is_idle(link))
115         return 0;
116     event = ZOOM_connection_peek_event(link);
117     if (event == ZOOM_EVENT_NONE)
118         return 1;
119     else
120         return 0;
121 }
122
123 ZOOM_connection connection_get_link(struct connection *co)
124 {
125     return co->link;
126 }
127
128 // Close connection and recycle structure
129 static void connection_destroy(struct connection *co)
130 {
131     if (co->link)
132     {
133         ZOOM_connection_destroy(co->link);
134         iochan_destroy(co->iochan);
135     }
136     yaz_log(YLOG_DEBUG, "%p Connection destroy %s", co, co->url);
137
138     if (co->client)
139     {
140         client_disconnect(co->client);
141     }
142
143     xfree(co->zproxy);
144     xfree(co->url);
145     xfree(co);
146     connection_use(-1);
147 }
148
149 // Creates a new connection for client, associated with the host of
150 // client's database
151 static struct connection *connection_create(struct client *cl,
152                                             const char *url,
153                                             const char *zproxy,
154                                             int operation_timeout,
155                                             int session_timeout,
156                                             iochan_man_t iochan_man)
157 {
158     struct connection *co;
159
160     co = xmalloc(sizeof(*co));
161
162     co->client = cl;
163     co->url = xstrdup(url);
164     co->zproxy = 0;
165     if (zproxy)
166         co->zproxy = xstrdup(zproxy);
167
168     client_set_connection(cl, co);
169     co->link = 0;
170     co->state = Conn_Closed;
171     co->operation_timeout = operation_timeout;
172     co->session_timeout = session_timeout;
173
174     connection_connect(co, iochan_man);
175
176     connection_use(1);
177     return co;
178 }
179
180 static void non_block_events(struct connection *co)
181 {
182     int got_records = 0;
183     IOCHAN iochan = co->iochan;
184     ZOOM_connection link = co->link;
185     while (1)
186     {
187         struct client *cl = co->client;
188         int ev;
189         int r = ZOOM_event_nonblock(1, &link);
190         if (!r)
191             break;
192         if (!cl)
193             continue;
194         ev = ZOOM_connection_last_event(link);
195
196 #if 1
197         yaz_log(YLOG_DEBUG, "%p Connection ZOOM_EVENT_%s", co, ZOOM_get_event_str(ev));
198 #endif
199         switch (ev)
200         {
201         case ZOOM_EVENT_TIMEOUT:
202             break;
203         case ZOOM_EVENT_END:
204             {
205                 const char *error, *addinfo;
206                 int err;
207                 if ((err = ZOOM_connection_error(link, &error, &addinfo)))
208                 {
209                     yaz_log(YLOG_LOG, "Error %s from %s",
210                             error, client_get_id(cl));
211                     client_set_diagnostic(cl, err, error, addinfo);
212                     client_set_state(cl, Client_Error);
213                 }
214                 else
215                 {
216                     iochan_settimeout(iochan, co->session_timeout);
217                     client_set_state(cl, Client_Idle);
218                 }
219             }
220             break;
221         case ZOOM_EVENT_SEND_DATA:
222             break;
223         case ZOOM_EVENT_RECV_DATA:
224             break;
225         case ZOOM_EVENT_UNKNOWN:
226             break;
227         case ZOOM_EVENT_SEND_APDU:
228             client_set_state(co->client, Client_Working);
229             iochan_settimeout(iochan, co->operation_timeout);
230             break;
231         case ZOOM_EVENT_RECV_APDU:
232             break;
233         case ZOOM_EVENT_CONNECT:
234             yaz_log(YLOG_LOG, "Connected to %s", client_get_id(cl));
235             co->state = Conn_Open;
236             break;
237         case ZOOM_EVENT_RECV_SEARCH:
238             client_search_response(cl);
239             break;
240         case ZOOM_EVENT_RECV_RECORD:
241             client_record_response(cl, &got_records);
242             break;
243         case ZOOM_EVENT_NONE:
244             break;
245         default:
246             yaz_log(YLOG_LOG, "Unhandled event (%d) from %s",
247                     ev, client_get_id(cl));
248             break;
249         }
250     }
251     if (got_records)
252     {
253         struct client *cl = co->client;
254         if (cl)
255         {
256             client_check_preferred_watch(cl);
257             client_got_records(cl);
258         }
259     }
260 }
261
262 static void iochan_update(struct connection *co)
263 {
264     if (co->link)
265     {
266         int m = ZOOM_connection_get_mask(co->link);
267
268         if (m == 0)
269             m = ZOOM_SELECT_READ;
270         iochan_setflags(co->iochan, m);
271         iochan_setfd(co->iochan, ZOOM_connection_get_socket(co->link));
272     }
273 }
274
275 void connection_continue(struct connection *co)
276 {
277     int r = ZOOM_connection_exec_task(co->link);
278     if (!r)
279     {
280         struct client *cl = co->client;
281
282         client_lock(cl);
283         non_block_events(co);
284         client_unlock(cl);
285     }
286     else
287         iochan_update(co);
288 }
289
290 static void connection_handler(IOCHAN iochan, int event)
291 {
292     struct connection *co = iochan_getdata(iochan);
293     struct client *cl;
294
295     cl = co->client;
296     if (!cl)
297     {
298         /* no client associated with it.. We are probably getting
299            a closed connection from the target.. Or, perhaps, an unexpected
300            package.. We will just close the connection */
301         yaz_log(YLOG_LOG, "timeout connection %p event=%d", co, event);
302         connection_destroy(co);
303     }
304     else if (event & EVENT_TIMEOUT)
305     {
306         ZOOM_connection_fire_event_timeout(co->link);
307         client_lock(cl);
308         non_block_events(co);
309         client_unlock(cl);
310
311         connection_destroy(co);
312     }
313     else
314     {
315         if (ZOOM_connection_is_idle(co->link))
316         {
317             connection_destroy(co);
318             return;
319         }
320         client_lock(cl);
321         non_block_events(co);
322
323         ZOOM_connection_fire_event_socket(co->link, event);
324
325         non_block_events(co);
326         client_unlock(cl);
327
328         iochan_update(co);
329     }
330 }
331
332
333 // Disassociate connection from client
334 static void connection_release(struct connection *co)
335 {
336     struct client *cl = co->client;
337
338     if (!cl)
339         return;
340     client_set_connection(cl, 0);
341     co->client = 0;
342 }
343
344 static int connection_connect(struct connection *con, iochan_man_t iochan_man)
345 {
346     ZOOM_options zoptions = ZOOM_options_create();
347     const char *auth;
348     const char *charset;
349     const char *sru;
350     const char *sru_version = 0;
351     const char *value;
352     WRBUF w;
353
354     struct session_database *sdb = client_get_database(con->client);
355     const char *apdulog = session_setting_oneval(sdb, PZ_APDULOG);
356     const char *memcached = session_setting_oneval(sdb, PZ_MEMCACHED);
357
358     assert(con);
359
360     ZOOM_options_set(zoptions, "async", "1");
361     ZOOM_options_set(zoptions, "implementationName", PACKAGE_NAME);
362     ZOOM_options_set(zoptions, "implementationVersion", VERSION);
363
364     if ((charset = session_setting_oneval(sdb, PZ_NEGOTIATION_CHARSET)))
365         ZOOM_options_set(zoptions, "charset", charset);
366     if (memcached && *memcached)
367         ZOOM_options_set(zoptions, "memcached", memcached);
368
369     if (con->zproxy)
370     {
371         yaz_log(YLOG_LOG, "proxy=%s", con->zproxy);
372         ZOOM_options_set(zoptions, "proxy", con->zproxy);
373     }
374     if (apdulog && *apdulog)
375         ZOOM_options_set(zoptions, "apdulog", apdulog);
376
377
378     if ((sru = session_setting_oneval(sdb, PZ_SRU)) && *sru)
379         ZOOM_options_set(zoptions, "sru", sru);
380     if ((sru_version = session_setting_oneval(sdb, PZ_SRU_VERSION))
381         && *sru_version)
382         ZOOM_options_set(zoptions, "sru_version", sru_version);
383
384     if ((auth = session_setting_oneval(sdb, PZ_AUTHENTICATION)))
385     {
386         /* allow splitting user and reset with a blank always */
387         const char *cp1 = strchr(auth, ' ');
388         if (!cp1 && sru && *sru)
389             cp1 =  strchr(auth, '/');
390         if (!cp1)
391         {
392             /* Z39.50 user/password style, or no password for SRU */
393             ZOOM_options_set(zoptions, "user", auth);
394         }
395         else
396         {
397             /* now consider group as well */
398             const char *cp2 = strchr(cp1 + 1, ' ');
399
400             ZOOM_options_setl(zoptions, "user", auth, cp1 - auth);
401             if (!cp2)
402                 ZOOM_options_set(zoptions, "password", cp1 + 1);
403             else
404             {
405                 ZOOM_options_setl(zoptions, "group", cp1 + 1, cp2 - cp1 - 1);
406                 ZOOM_options_set(zoptions, "password", cp2 + 1);
407             }
408         }
409     }
410
411     value = session_setting_oneval(sdb, PZ_AUTHENTICATION_MODE);
412     if (value && *value)
413         ZOOM_options_set(zoptions, "authenticationMode", value);
414
415     if (!(con->link = ZOOM_connection_create(zoptions)))
416     {
417         yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create ZOOM Connection");
418         ZOOM_options_destroy(zoptions);
419         return -1;
420     }
421
422     w = wrbuf_alloc();
423     if (sru && *sru && !strstr(con->url, "://"))
424         wrbuf_puts(w, "http://");
425     if (strchr(con->url, '#'))
426     {
427         const char *cp = strchr(con->url, '#');
428         wrbuf_write(w, con->url, cp - con->url);
429     }
430     else
431         wrbuf_puts(w, con->url);
432
433     ZOOM_connection_connect(con->link, wrbuf_cstr(w), 0);
434
435     con->iochan = iochan_create(-1, connection_handler, 0, "connection_socket");
436     con->state = Conn_Connecting;
437     iochan_settimeout(con->iochan, con->operation_timeout);
438     iochan_setdata(con->iochan, con);
439     iochan_add(iochan_man, con->iochan);
440
441     client_set_state(con->client, Client_Connecting);
442     ZOOM_options_destroy(zoptions);
443     wrbuf_destroy(w);
444     return 0;
445 }
446
447 // Ensure that client has a connection associated
448 int client_prep_connection(struct client *cl,
449                            int operation_timeout, int session_timeout,
450                            iochan_man_t iochan_man,
451                            const struct timeval *abstime)
452 {
453     struct connection *co;
454     struct session_database *sdb = client_get_database(cl);
455     const char *zproxy = session_setting_oneval(sdb, PZ_ZPROXY);
456     const char *url = session_setting_oneval(sdb, PZ_URL);
457
458     if (zproxy && zproxy[0] == '\0')
459         zproxy = 0;
460
461     if (!url || !*url)
462         url = sdb->database->id;
463
464     yaz_log(YLOG_DEBUG, "client_prep_connection: target=%s url=%s",
465             client_get_id(cl), url);
466
467     co = client_get_connection(cl);
468     if (!co)
469     {
470         co = connection_create(cl, url, zproxy,
471                                operation_timeout, session_timeout,
472                                iochan_man);
473     }
474
475     if (co && co->link)
476         return 1;
477     else
478         return 0;
479 }
480
481 /*
482  * Local variables:
483  * c-basic-offset: 4
484  * c-file-style: "Stroustrup"
485  * indent-tabs-mode: nil
486  * End:
487  * vim: shiftwidth=4 tabstop=8 expandtab
488  */
489