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