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