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