getaddrinfo/host sub system gone
[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 void connection_continue(struct connection *co)
263 {
264     int r = ZOOM_connection_exec_task(co->link);
265     if (!r)
266     {
267         struct client *cl = co->client;
268
269         client_lock(cl);
270         non_block_events(co);
271         client_unlock(cl);
272     }
273     else
274     {
275         iochan_setflags(co->iochan, ZOOM_connection_get_mask(co->link));
276         iochan_setfd(co->iochan, ZOOM_connection_get_socket(co->link));
277     }
278 }
279
280 static void connection_handler(IOCHAN iochan, int event)
281 {
282     struct connection *co = iochan_getdata(iochan);
283     struct client *cl;
284
285     cl = co->client;
286     if (!cl)
287     {
288         /* no client associated with it.. We are probably getting
289            a closed connection from the target.. Or, perhaps, an unexpected
290            package.. We will just close the connection */
291         yaz_log(YLOG_LOG, "timeout connection %p event=%d", co, event);
292         connection_destroy(co);
293     }
294     else if (event & EVENT_TIMEOUT)
295     {
296         ZOOM_connection_fire_event_timeout(co->link);
297         client_lock(cl);
298         non_block_events(co);
299         client_unlock(cl);
300
301         connection_destroy(co);
302     }
303     else
304     {
305         client_lock(cl);
306         non_block_events(co);
307
308         ZOOM_connection_fire_event_socket(co->link, event);
309
310         non_block_events(co);
311         client_unlock(cl);
312
313         if (co->link)
314         {
315             iochan_setflags(iochan, ZOOM_connection_get_mask(co->link));
316             iochan_setfd(iochan, ZOOM_connection_get_socket(co->link));
317         }
318     }
319 }
320
321
322 // Disassociate connection from client
323 static void connection_release(struct connection *co)
324 {
325     struct client *cl = co->client;
326
327     if (!cl)
328         return;
329     client_set_connection(cl, 0);
330     co->client = 0;
331 }
332
333 static int connection_connect(struct connection *con, iochan_man_t iochan_man)
334 {
335     ZOOM_options zoptions = ZOOM_options_create();
336     const char *auth;
337     const char *charset;
338     const char *sru;
339     const char *sru_version = 0;
340     const char *value;
341     WRBUF w;
342
343     struct session_database *sdb = client_get_database(con->client);
344     const char *apdulog = session_setting_oneval(sdb, PZ_APDULOG);
345     const char *memcached = session_setting_oneval(sdb, PZ_MEMCACHED);
346
347     assert(con);
348
349     ZOOM_options_set(zoptions, "async", "1");
350     ZOOM_options_set(zoptions, "implementationName", PACKAGE_NAME);
351     ZOOM_options_set(zoptions, "implementationVersion", VERSION);
352
353     if ((charset = session_setting_oneval(sdb, PZ_NEGOTIATION_CHARSET)))
354         ZOOM_options_set(zoptions, "charset", charset);
355     if (memcached && *memcached)
356         ZOOM_options_set(zoptions, "memcached", memcached);
357
358     if (con->zproxy)
359     {
360         yaz_log(YLOG_LOG, "proxy=%s", con->zproxy);
361         ZOOM_options_set(zoptions, "proxy", con->zproxy);
362     }
363     if (apdulog && *apdulog)
364         ZOOM_options_set(zoptions, "apdulog", apdulog);
365
366
367     if ((sru = session_setting_oneval(sdb, PZ_SRU)) && *sru)
368         ZOOM_options_set(zoptions, "sru", sru);
369     if ((sru_version = session_setting_oneval(sdb, PZ_SRU_VERSION))
370         && *sru_version)
371         ZOOM_options_set(zoptions, "sru_version", sru_version);
372
373     if ((auth = session_setting_oneval(sdb, PZ_AUTHENTICATION)))
374     {
375         /* allow splitting user and reset with a blank always */
376         const char *cp1 = strchr(auth, ' ');
377         if (!cp1 && sru && *sru)
378             cp1 =  strchr(auth, '/');
379         if (!cp1)
380         {
381             /* Z39.50 user/password style, or no password for SRU */
382             ZOOM_options_set(zoptions, "user", auth);
383         }
384         else
385         {
386             /* now consider group as well */
387             const char *cp2 = strchr(cp1 + 1, ' ');
388
389             ZOOM_options_setl(zoptions, "user", auth, cp1 - auth);
390             if (!cp2)
391                 ZOOM_options_set(zoptions, "password", cp1 + 1);
392             else
393             {
394                 ZOOM_options_setl(zoptions, "group", cp1 + 1, cp2 - cp1 - 1);
395                 ZOOM_options_set(zoptions, "password", cp2 + 1);
396             }
397         }
398     }
399
400     value = session_setting_oneval(sdb, PZ_AUTHENTICATION_MODE);
401     if (value && *value)
402         ZOOM_options_set(zoptions, "authenticationMode", value);
403
404     if (!(con->link = ZOOM_connection_create(zoptions)))
405     {
406         yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create ZOOM Connection");
407         ZOOM_options_destroy(zoptions);
408         return -1;
409     }
410
411     w = wrbuf_alloc();
412     if (sru && *sru && !strstr(con->url, "://"))
413         wrbuf_puts(w, "http://");
414     if (strchr(con->url, '#'))
415     {
416         const char *cp = strchr(con->url, '#');
417         wrbuf_write(w, con->url, cp - con->url);
418     }
419     else
420         wrbuf_puts(w, con->url);
421
422     ZOOM_connection_connect(con->link, wrbuf_cstr(w), 0);
423
424     con->iochan = iochan_create(-1, connection_handler, 0, "connection_socket");
425     con->state = Conn_Connecting;
426     iochan_settimeout(con->iochan, con->operation_timeout);
427     iochan_setdata(con->iochan, con);
428     iochan_add(iochan_man, con->iochan);
429
430     client_set_state(con->client, Client_Connecting);
431     ZOOM_options_destroy(zoptions);
432     wrbuf_destroy(w);
433     return 0;
434 }
435
436 // Ensure that client has a connection associated
437 int client_prep_connection(struct client *cl,
438                            int operation_timeout, int session_timeout,
439                            iochan_man_t iochan_man,
440                            const struct timeval *abstime)
441 {
442     struct connection *co;
443     struct session_database *sdb = client_get_database(cl);
444     const char *zproxy = session_setting_oneval(sdb, PZ_ZPROXY);
445     const char *url = session_setting_oneval(sdb, PZ_URL);
446
447     if (zproxy && zproxy[0] == '\0')
448         zproxy = 0;
449
450     if (!url || !*url)
451         url = sdb->database->id;
452
453     yaz_log(YLOG_DEBUG, "client_prep_connection: target=%s url=%s",
454             client_get_id(cl), url);
455
456     co = client_get_connection(cl);
457     if (!co)
458     {
459         co = connection_create(cl, url, zproxy,
460                                operation_timeout, session_timeout,
461                                iochan_man);
462     }
463
464     if (co && co->link)
465         return 1;
466     else
467         return 0;
468 }
469
470 /*
471  * Local variables:
472  * c-basic-offset: 4
473  * c-file-style: "Stroustrup"
474  * indent-tabs-mode: nil
475  * End:
476  * vim: shiftwidth=4 tabstop=8 expandtab
477  */
478