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