Remove connection_freelist
[pazpar2-moved-to-github.git] / src / connection.c
1 /* This file is part of Pazpar2.
2    Copyright (C) 2006-2010 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 "pazpar2.h"
46 #include "host.h"
47 #include "client.h"
48 #include "settings.h"
49
50
51 /** \brief Represents a physical, reusable  connection to a remote Z39.50 host
52  */
53 struct connection {
54     IOCHAN iochan;
55     ZOOM_connection link;
56     struct host *host;
57     struct client *client;
58     char *zproxy;
59     enum {
60         Conn_Resolving,
61         Conn_Connecting,
62         Conn_Open
63     } state;
64     int operation_timeout;
65     int session_timeout;
66     struct connection *next; // next for same host or next in free list
67 };
68
69 static int connection_connect(struct connection *con, iochan_man_t iochan_man);
70
71 static int connection_is_idle(struct connection *co)
72 {
73     ZOOM_connection link = co->link;
74     int event;
75
76     if (co->state != Conn_Open || !link)
77         return 0;
78
79     if (!ZOOM_connection_is_idle(link))
80         return 0;
81     event = ZOOM_connection_peek_event(link);
82     if (event == ZOOM_EVENT_NONE || event == ZOOM_EVENT_END)
83         return 1;
84     else
85         return 0;
86 }
87
88 ZOOM_connection connection_get_link(struct connection *co)
89 {
90     return co->link;
91 }
92
93 static void remove_connection_from_host(struct connection *con)
94 {
95     struct connection **conp = &con->host->connections;
96     assert(con);
97     while (*conp)
98     {
99         if (*conp == con)
100         {
101             *conp = (*conp)->next;
102             return;
103         }
104         conp = &(*conp)->next;
105     }
106     assert(*conp == 0);
107 }
108
109 // Close connection and recycle structure
110 void connection_destroy(struct connection *co)
111 {
112     if (co->link)
113     {
114         ZOOM_connection_destroy(co->link);
115         iochan_destroy(co->iochan);
116     }
117     yaz_log(YLOG_DEBUG, "Connection destroy %s", co->host->hostport);
118
119     remove_connection_from_host(co);
120     if (co->client)
121     {
122         client_disconnect(co->client);
123     }
124     xfree(co->zproxy);
125     xfree(co);
126 }
127
128 // Creates a new connection for client, associated with the host of 
129 // client's database
130 static struct connection *connection_create(struct client *cl,
131                                             int operation_timeout,
132                                             int session_timeout,
133                                             iochan_man_t iochan_man)
134 {
135     struct connection *new;
136     struct host *host = client_get_host(cl);
137
138     new = xmalloc(sizeof(*new));
139     new->host = host;
140     new->next = new->host->connections;
141     new->host->connections = new;
142     new->client = cl;
143     new->zproxy = 0;
144     client_set_connection(cl, new);
145     new->link = 0;
146     new->state = Conn_Resolving;
147     new->operation_timeout = operation_timeout;
148     new->session_timeout = session_timeout;
149     if (host->ipport)
150         connection_connect(new, iochan_man);
151     return new;
152 }
153
154 static void non_block_events(struct connection *co)
155 {
156     struct client *cl = co->client;
157     IOCHAN iochan = co->iochan;
158     ZOOM_connection link = co->link;
159     while (1)
160     {
161         int ev;
162         int r = ZOOM_event_nonblock(1, &link);
163         if (!r)
164             break;
165         ev = ZOOM_connection_last_event(link);
166 #if 0
167         yaz_log(YLOG_LOG, "ZOOM_EVENT_%s", ZOOM_get_event_str(ev));
168 #endif
169         switch (ev) 
170         {
171         case ZOOM_EVENT_END:
172             {
173                 const char *error, *addinfo;
174                 int err;
175                 if ((err = ZOOM_connection_error(link, &error, &addinfo)))
176                 {
177                     yaz_log(YLOG_LOG, "Error %s from %s",
178                             error, client_get_url(cl));
179                 }
180                 iochan_settimeout(iochan, co->session_timeout);
181                 client_set_diagnostic(cl, err);
182                 client_set_state(cl, Client_Idle);
183             }
184             break;
185         case ZOOM_EVENT_SEND_DATA:
186             break;
187         case ZOOM_EVENT_RECV_DATA:
188             break;
189         case ZOOM_EVENT_UNKNOWN:
190             break;
191         case ZOOM_EVENT_SEND_APDU:
192             client_set_state(co->client, Client_Working);
193             iochan_settimeout(iochan, co->operation_timeout);
194             break;
195         case ZOOM_EVENT_RECV_APDU:
196             break;
197         case ZOOM_EVENT_CONNECT:
198             yaz_log(YLOG_LOG, "Connected to %s", client_get_url(cl));
199             co->state = Conn_Open;
200             break;
201         case ZOOM_EVENT_RECV_SEARCH:
202             client_search_response(cl);
203             break;
204         case ZOOM_EVENT_RECV_RECORD:
205             client_record_response(cl);
206             break;
207         default:
208             yaz_log(YLOG_LOG, "Unhandled event (%d) from %s",
209                     ev, client_get_url(cl));
210         }
211     }
212 }
213
214 void connection_continue(struct connection *co)
215 {
216     non_block_events(co);
217 }
218
219 static void connection_handler(IOCHAN iochan, int event)
220 {
221     struct connection *co = iochan_getdata(iochan);
222     struct client *cl = co->client;
223     struct session *se = 0;
224
225     if (cl)
226         se = client_get_session(cl);
227     else
228     {
229         connection_destroy(co);
230         return;
231     }
232
233     if (event & EVENT_TIMEOUT)
234     {
235         if (co->state == Conn_Connecting)
236         {
237             yaz_log(YLOG_WARN,  "connect timeout %s", client_get_url(cl));
238             client_fatal(cl);
239         }
240         else
241         {
242             yaz_log(YLOG_LOG,  "idle timeout %s", client_get_url(cl));
243             connection_destroy(co);
244         }
245     }
246     else
247     {
248         non_block_events(co);
249
250         ZOOM_connection_fire_event_socket(co->link, event);
251         
252         non_block_events(co);
253     }
254 }
255
256
257 // Disassociate connection from client
258 void connection_release(struct connection *co)
259 {
260     struct client *cl = co->client;
261
262     yaz_log(YLOG_DEBUG, "Connection release %s", co->host->hostport);
263     if (!cl)
264         return;
265     client_set_connection(cl, 0);
266     co->client = 0;
267 }
268
269 void connect_resolver_host(struct host *host, iochan_man_t iochan_man)
270 {
271     struct connection *con = host->connections;
272     while (con)
273     {
274         if (con->state == Conn_Resolving)
275         {
276             if (!host->ipport) /* unresolved */
277             {
278                 connection_destroy(con);
279                 /* start all over .. at some point it will be NULL */
280                 con = host->connections;
281                 continue;
282             }
283             else if (!con->client)
284             {
285                 connection_destroy(con);
286                 /* start all over .. at some point it will be NULL */
287                 con = host->connections;
288                 continue;
289             }
290             else
291             {
292                 connection_connect(con, iochan_man);
293                 client_start_search(con->client);
294             }
295         }
296         else
297         {
298             yaz_log(YLOG_LOG, "connect_resolver_host: state=%d", con->state);
299         }
300         con = con->next;
301     }
302 }
303
304 static struct host *connection_get_host(struct connection *con)
305 {
306     return con->host;
307 }
308
309 // Callback for use by event loop
310 // We do this because ZOOM connections don't always have (the same) sockets
311 static int socketfun(IOCHAN c)
312 {
313     struct connection *co = iochan_getdata(c);
314     if (!co->link)
315         return -1;
316     return ZOOM_connection_get_socket(co->link);
317 }
318
319 // Because ZOOM always knows what events it is interested in; we may not
320 static int maskfun(IOCHAN c)
321 {
322     struct connection *co = iochan_getdata(c);
323     if (!co->link)
324         return 0;
325
326     // This is cheating a little, and assuming that eventl mask IDs are always
327     // the same as ZOOM-C's.
328     return ZOOM_connection_get_mask(co->link);
329 }
330
331 static int connection_connect(struct connection *con, iochan_man_t iochan_man)
332 {
333     ZOOM_connection link = 0;
334     struct host *host = connection_get_host(con);
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
341     struct session_database *sdb = client_get_database(con->client);
342     const char *zproxy = session_setting_oneval(sdb, PZ_ZPROXY);
343     const char *apdulog = session_setting_oneval(sdb, PZ_APDULOG);
344
345     assert(host->ipport);
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     
355     if (zproxy && *zproxy)
356     {
357         con->zproxy = xstrdup(zproxy);
358         ZOOM_options_set(zoptions, "proxy", zproxy);
359     }
360     if (apdulog && *apdulog)
361         ZOOM_options_set(zoptions, "apdulog", apdulog);
362
363     if ((auth = session_setting_oneval(sdb, PZ_AUTHENTICATION)))
364         ZOOM_options_set(zoptions, "user", auth);
365     if ((sru = session_setting_oneval(sdb, PZ_SRU)) && *sru)
366         ZOOM_options_set(zoptions, "sru", sru);
367     if ((sru_version = session_setting_oneval(sdb, PZ_SRU_VERSION)) 
368         && *sru_version)
369         ZOOM_options_set(zoptions, "sru_version", sru_version);
370
371     if (!(link = ZOOM_connection_create(zoptions)))
372     {
373         yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create ZOOM Connection");
374         ZOOM_options_destroy(zoptions);
375         return -1;
376     }
377
378     if (sru && *sru)
379     {
380         char http_hostport[512];
381         strcpy(http_hostport, "http://");
382         strcat(http_hostport, host->hostport);
383         ZOOM_connection_connect(link, http_hostport, 0);
384     }
385     else
386         ZOOM_connection_connect(link, host->ipport, 0);
387     
388     con->link = link;
389     con->iochan = iochan_create(0, connection_handler, 0);
390     con->state = Conn_Connecting;
391     iochan_settimeout(con->iochan, con->operation_timeout);
392     iochan_setdata(con->iochan, con);
393     iochan_setsocketfun(con->iochan, socketfun);
394     iochan_setmaskfun(con->iochan, maskfun);
395     iochan_add(iochan_man, con->iochan);
396
397     /* this fragment is bad DRY: from client_prep_connection */
398     client_set_state(con->client, Client_Connecting);
399     ZOOM_options_destroy(zoptions);
400     return 0;
401 }
402
403 const char *connection_get_url(struct connection *co)
404 {
405     return client_get_url(co->client);
406 }
407
408 // Ensure that client has a connection associated
409 int client_prep_connection(struct client *cl,
410                            int operation_timeout, int session_timeout,
411                            iochan_man_t iochan_man)
412 {
413     struct connection *co;
414     struct session *se = client_get_session(cl);
415     struct host *host = client_get_host(cl);
416     struct session_database *sdb = client_get_database(cl);
417     const char *zproxy = session_setting_oneval(sdb, PZ_ZPROXY);
418
419     if (zproxy && zproxy[0] == '\0')
420         zproxy = 0;
421
422     if (!host)
423         return 0;
424
425     co = client_get_connection(cl);
426
427     yaz_log(YLOG_DEBUG, "Client prep %s", client_get_url(cl));
428
429     if (!co)
430     {
431         // See if someone else has an idle connection
432         // We should look at timestamps here to select the longest-idle connection
433         for (co = host->connections; co; co = co->next)
434             if (connection_is_idle(co) &&
435                 (!co->client || client_get_session(co->client) != se) &&
436                 !strcmp(ZOOM_connection_option_get(co->link, "user"),
437                         session_setting_oneval(client_get_database(cl),
438                                                PZ_AUTHENTICATION)))
439             {
440                 if (zproxy == 0 && co->zproxy == 0)
441                     break;
442                 if (zproxy && co->zproxy && !strcmp(zproxy, co->zproxy))
443                     break;
444             }
445         if (co)
446         {
447             connection_release(co);
448             client_set_connection(cl, co);
449             co->client = cl;
450             co->operation_timeout = operation_timeout;
451             co->session_timeout = session_timeout;
452             /* tells ZOOM to reconnect if necessary. Disabled becuase
453                the ZOOM_connection_connect flushes the task queue */
454             ZOOM_connection_connect(co->link, 0, 0);
455         }
456         else
457         {
458             co = connection_create(cl, operation_timeout, session_timeout,
459                                    iochan_man);
460         }
461     }
462
463     if (co && co->link)
464         return 1;
465     else
466         return 0;
467 }
468
469 /*
470  * Local variables:
471  * c-basic-offset: 4
472  * c-file-style: "Stroustrup"
473  * indent-tabs-mode: nil
474  * End:
475  * vim: shiftwidth=4 tabstop=8 expandtab
476  */
477