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