Merge branch 'master' into paz-927
[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                     struct session *se = client_get_session(cl);
198
199                     session_log(se, YLOG_WARN, "%s: Error %s (%s)",
200                                 client_get_id(cl), error, addinfo);
201                     client_set_diagnostic(cl, err, error, addinfo);
202                     client_set_state(cl, Client_Error);
203                 }
204                 else
205                 {
206                     iochan_settimeout(iochan, co->session_timeout);
207                     client_set_state(cl, Client_Idle);
208                 }
209             }
210             break;
211         case ZOOM_EVENT_SEND_DATA:
212             break;
213         case ZOOM_EVENT_RECV_DATA:
214             break;
215         case ZOOM_EVENT_UNKNOWN:
216             break;
217         case ZOOM_EVENT_SEND_APDU:
218             client_set_state(co->client, Client_Working);
219             iochan_settimeout(iochan, co->operation_timeout);
220             break;
221         case ZOOM_EVENT_RECV_APDU:
222             break;
223         case ZOOM_EVENT_CONNECT:
224             co->state = Conn_Open;
225             break;
226         case ZOOM_EVENT_RECV_SEARCH:
227             client_search_response(cl);
228             break;
229         case ZOOM_EVENT_RECV_RECORD:
230             client_record_response(cl, &got_records);
231             break;
232         case ZOOM_EVENT_NONE:
233             break;
234         default:
235             yaz_log(YLOG_LOG, "Unhandled event (%d) from %s",
236                     ev, client_get_id(cl));
237             break;
238         }
239     }
240     if (got_records)
241     {
242         struct client *cl = co->client;
243         if (cl)
244         {
245             client_check_preferred_watch(cl);
246             client_got_records(cl);
247         }
248     }
249 }
250
251 static void iochan_update(struct connection *co)
252 {
253     if (co->link)
254     {
255         int m = ZOOM_connection_get_mask(co->link);
256
257         if (m == 0)
258             m = ZOOM_SELECT_READ;
259         iochan_setflags(co->iochan, m);
260         iochan_setfd(co->iochan, ZOOM_connection_get_socket(co->link));
261     }
262 }
263
264 void connection_continue(struct connection *co)
265 {
266     int r = ZOOM_connection_exec_task(co->link);
267     if (!r)
268     {
269         struct client *cl = co->client;
270
271         client_lock(cl);
272         non_block_events(co);
273         client_unlock(cl);
274     }
275     else
276         iochan_update(co);
277 }
278
279 static void connection_handler(IOCHAN iochan, int event)
280 {
281     struct connection *co = iochan_getdata(iochan);
282     struct client *cl;
283
284     cl = co->client;
285     if (!cl)
286     {
287         /* no client associated with it.. We are probably getting
288            a closed connection from the target.. Or, perhaps, an unexpected
289            package.. We will just close the connection */
290         yaz_log(YLOG_LOG, "timeout connection %p event=%d", co, event);
291         connection_destroy(co);
292     }
293     else if (event & EVENT_TIMEOUT)
294     {
295         ZOOM_connection_fire_event_timeout(co->link);
296         client_lock(cl);
297         non_block_events(co);
298         client_unlock(cl);
299
300         connection_destroy(co);
301     }
302     else
303     {
304         if (ZOOM_connection_is_idle(co->link))
305         {
306             connection_destroy(co);
307             return;
308         }
309         client_lock(cl);
310         non_block_events(co);
311
312         ZOOM_connection_fire_event_socket(co->link, event);
313
314         non_block_events(co);
315         client_unlock(cl);
316
317         iochan_update(co);
318     }
319 }
320
321 void connection_release2(struct connection *co)
322 {
323     co->client = 0;
324 }
325
326 static int connection_connect(struct connection *con, iochan_man_t iochan_man)
327 {
328     ZOOM_options zoptions = ZOOM_options_create();
329     const char *auth;
330     const char *charset;
331     const char *sru;
332     const char *sru_version = 0;
333     const char *value;
334     WRBUF w;
335
336     struct session_database *sdb = client_get_database(con->client);
337     const char *apdulog = session_setting_oneval(sdb, PZ_APDULOG);
338     const char *memcached = session_setting_oneval(sdb, PZ_MEMCACHED);
339     const char *redis = session_setting_oneval(sdb, PZ_REDIS);
340
341     assert(con);
342
343     ZOOM_options_set(zoptions, "async", "1");
344     ZOOM_options_set(zoptions, "implementationName", PACKAGE_NAME);
345     ZOOM_options_set(zoptions, "implementationVersion", VERSION);
346
347     if ((charset = session_setting_oneval(sdb, PZ_NEGOTIATION_CHARSET)))
348         ZOOM_options_set(zoptions, "charset", charset);
349     if (memcached && *memcached)
350         ZOOM_options_set(zoptions, "memcached", memcached);
351     if (redis && *redis)
352         ZOOM_options_set(zoptions, "redis", redis);
353
354     if (con->zproxy)
355     {
356         yaz_log(YLOG_LOG, "proxy=%s", con->zproxy);
357         ZOOM_options_set(zoptions, "proxy", con->zproxy);
358     }
359     if (apdulog && *apdulog)
360         ZOOM_options_set(zoptions, "apdulog", apdulog);
361
362
363     if ((sru = session_setting_oneval(sdb, PZ_SRU)) && *sru)
364         ZOOM_options_set(zoptions, "sru", sru);
365     if ((sru_version = session_setting_oneval(sdb, PZ_SRU_VERSION))
366         && *sru_version)
367         ZOOM_options_set(zoptions, "sru_version", sru_version);
368
369     if ((auth = session_setting_oneval(sdb, PZ_AUTHENTICATION)))
370     {
371         /* allow splitting user and reset with a blank always */
372         const char *cp1 = strchr(auth, ' ');
373         if (!cp1 && sru && *sru)
374             cp1 =  strchr(auth, '/');
375         if (!cp1)
376         {
377             /* Z39.50 user/password style, or no password for SRU */
378             ZOOM_options_set(zoptions, "user", auth);
379         }
380         else
381         {
382             /* now consider group as well */
383             const char *cp2 = strchr(cp1 + 1, ' ');
384
385             ZOOM_options_setl(zoptions, "user", auth, cp1 - auth);
386             if (!cp2)
387                 ZOOM_options_set(zoptions, "password", cp1 + 1);
388             else
389             {
390                 ZOOM_options_setl(zoptions, "group", cp1 + 1, cp2 - cp1 - 1);
391                 ZOOM_options_set(zoptions, "password", cp2 + 1);
392             }
393         }
394     }
395
396     value = session_setting_oneval(sdb, PZ_AUTHENTICATION_MODE);
397     if (value && *value)
398         ZOOM_options_set(zoptions, "authenticationMode", value);
399
400     if (!(con->link = ZOOM_connection_create(zoptions)))
401     {
402         yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create ZOOM Connection");
403         ZOOM_options_destroy(zoptions);
404         return -1;
405     }
406
407     w = wrbuf_alloc();
408     if (sru && *sru && !strstr(con->url, "://"))
409         wrbuf_puts(w, "http://");
410     if (strchr(con->url, '#'))
411     {
412         const char *cp = strchr(con->url, '#');
413         wrbuf_write(w, con->url, cp - con->url);
414     }
415     else
416         wrbuf_puts(w, con->url);
417
418     ZOOM_connection_connect(con->link, wrbuf_cstr(w), 0);
419
420     con->iochan = iochan_create(-1, connection_handler, 0, "connection_socket");
421     con->state = Conn_Connecting;
422     iochan_settimeout(con->iochan, con->operation_timeout);
423     iochan_setdata(con->iochan, con);
424     iochan_add(iochan_man, con->iochan);
425
426     client_set_state(con->client, Client_Connecting);
427     ZOOM_options_destroy(zoptions);
428     wrbuf_destroy(w);
429     return 0;
430 }
431
432 // Ensure that client has a connection associated
433 int client_prep_connection(struct client *cl,
434                            int operation_timeout, int session_timeout,
435                            iochan_man_t iochan_man,
436                            const struct timeval *abstime)
437 {
438     struct connection *co;
439     struct session_database *sdb = client_get_database(cl);
440     const char *zproxy = session_setting_oneval(sdb, PZ_ZPROXY);
441     const char *url = session_setting_oneval(sdb, PZ_URL);
442
443     if (zproxy && zproxy[0] == '\0')
444         zproxy = 0;
445
446     if (!url || !*url)
447         url = sdb->database->id;
448
449     yaz_log(YLOG_DEBUG, "client_prep_connection: target=%s url=%s",
450             client_get_id(cl), url);
451
452     co = client_get_connection(cl);
453     if (!co)
454     {
455         co = connection_create(cl, url, zproxy,
456                                operation_timeout, session_timeout,
457                                iochan_man);
458     }
459
460     if (co && co->link)
461         return 1;
462     else
463         return 0;
464 }
465
466 /*
467  * Local variables:
468  * c-basic-offset: 4
469  * c-file-style: "Stroustrup"
470  * indent-tabs-mode: nil
471  * End:
472  * vim: shiftwidth=4 tabstop=8 expandtab
473  */
474