iochan_man_t in logic.c gone
[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; /* thread pr */
72
73 static int connection_connect(struct connection *con, iochan_man_t iochan_man);
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                                             iochan_man_t iochan_man)
140 {
141     struct connection *new;
142     struct host *host = client_get_host(cl);
143
144     if ((new = connection_freelist))
145         connection_freelist = new->next;
146     else
147     {
148         new = xmalloc(sizeof (struct connection));
149         new->ibuf = 0;
150         new->ibufsize = 0;
151     }
152     new->host = host;
153     new->next = new->host->connections;
154     new->host->connections = new;
155     new->client = cl;
156     new->zproxy = 0;
157     client_set_connection(cl, new);
158     new->link = 0;
159     new->state = Conn_Resolving;
160     new->operation_timeout = operation_timeout;
161     new->session_timeout = session_timeout;
162     if (host->ipport)
163         connection_connect(new, iochan_man);
164     return new;
165 }
166
167 static void non_block_events(struct connection *co)
168 {
169     struct client *cl = co->client;
170     IOCHAN iochan = co->iochan;
171     ZOOM_connection link = co->link;
172     while (1)
173     {
174         int ev;
175         int r = ZOOM_event_nonblock(1, &link);
176         if (!r)
177             break;
178         ev = ZOOM_connection_last_event(link);
179 #if 0
180         yaz_log(YLOG_LOG, "ZOOM_EVENT_%s", ZOOM_get_event_str(ev));
181 #endif
182         switch (ev) 
183         {
184         case ZOOM_EVENT_END:
185             {
186                 const char *error, *addinfo;
187                 int err;
188                 if ((err = ZOOM_connection_error(link, &error, &addinfo)))
189                 {
190                     yaz_log(YLOG_LOG, "Error %s from %s",
191                             error, client_get_url(cl));
192                 }
193                 iochan_settimeout(iochan, co->session_timeout);
194                 client_set_diagnostic(cl, err);
195                 client_set_state(cl, Client_Idle);
196             }
197             break;
198         case ZOOM_EVENT_SEND_DATA:
199             break;
200         case ZOOM_EVENT_RECV_DATA:
201             break;
202         case ZOOM_EVENT_UNKNOWN:
203             break;
204         case ZOOM_EVENT_SEND_APDU:
205             client_set_state(co->client, Client_Working);
206             iochan_settimeout(iochan, co->operation_timeout);
207             break;
208         case ZOOM_EVENT_RECV_APDU:
209             break;
210         case ZOOM_EVENT_CONNECT:
211             yaz_log(YLOG_LOG, "Connected to %s", client_get_url(cl));
212             co->state = Conn_Open;
213             break;
214         case ZOOM_EVENT_RECV_SEARCH:
215             client_search_response(cl);
216             break;
217         case ZOOM_EVENT_RECV_RECORD:
218             client_record_response(cl);
219             break;
220         default:
221             yaz_log(YLOG_LOG, "Unhandled event (%d) from %s",
222                     ev, client_get_url(cl));
223         }
224     }
225 }
226
227 void connection_continue(struct connection *co)
228 {
229     non_block_events(co);
230 }
231
232 static void connection_handler(IOCHAN iochan, int event)
233 {
234     struct connection *co = iochan_getdata(iochan);
235     struct client *cl = co->client;
236     struct session *se = 0;
237
238     if (cl)
239         se = client_get_session(cl);
240     else
241     {
242         connection_destroy(co);
243         return;
244     }
245
246     if (event & EVENT_TIMEOUT)
247     {
248         if (co->state == Conn_Connecting)
249         {
250             yaz_log(YLOG_WARN,  "connect timeout %s", client_get_url(cl));
251             client_fatal(cl);
252         }
253         else
254         {
255             yaz_log(YLOG_LOG,  "idle timeout %s", client_get_url(cl));
256             connection_destroy(co);
257         }
258     }
259     else
260     {
261         non_block_events(co);
262
263         ZOOM_connection_fire_event_socket(co->link, event);
264         
265         non_block_events(co);
266     }
267 }
268
269
270 // Disassociate connection from client
271 void connection_release(struct connection *co)
272 {
273     struct client *cl = co->client;
274
275     yaz_log(YLOG_DEBUG, "Connection release %s", co->host->hostport);
276     if (!cl)
277         return;
278     client_set_connection(cl, 0);
279     co->client = 0;
280 }
281
282 void connect_resolver_host(struct host *host, iochan_man_t iochan_man)
283 {
284     struct connection *con = host->connections;
285     while (con)
286     {
287         if (con->state == Conn_Resolving)
288         {
289             if (!host->ipport) /* unresolved */
290             {
291                 connection_destroy(con);
292                 /* start all over .. at some point it will be NULL */
293                 con = host->connections;
294                 continue;
295             }
296             else if (!con->client)
297             {
298                 connection_destroy(con);
299                 /* start all over .. at some point it will be NULL */
300                 con = host->connections;
301                 continue;
302             }
303             else
304             {
305                 connection_connect(con, iochan_man);
306                 client_start_search(con->client);
307             }
308         }
309         else
310         {
311             yaz_log(YLOG_LOG, "connect_resolver_host: state=%d", con->state);
312         }
313         con = con->next;
314     }
315 }
316
317 static struct host *connection_get_host(struct connection *con)
318 {
319     return con->host;
320 }
321
322 // Callback for use by event loop
323 // We do this because ZOOM connections don't always have (the same) sockets
324 static int socketfun(IOCHAN c)
325 {
326     struct connection *co = iochan_getdata(c);
327     if (!co->link)
328         return -1;
329     return ZOOM_connection_get_socket(co->link);
330 }
331
332 // Because ZOOM always knows what events it is interested in; we may not
333 static int maskfun(IOCHAN c)
334 {
335     struct connection *co = iochan_getdata(c);
336     if (!co->link)
337         return 0;
338
339     // This is cheating a little, and assuming that eventl mask IDs are always
340     // the same as ZOOM-C's.
341     return ZOOM_connection_get_mask(co->link);
342 }
343
344 static int connection_connect(struct connection *con, iochan_man_t iochan_man)
345 {
346     ZOOM_connection link = 0;
347     struct host *host = connection_get_host(con);
348     ZOOM_options zoptions = ZOOM_options_create();
349     const char *auth;
350     const char *charset;
351     const char *sru;
352     const char *sru_version = 0;
353
354     struct session_database *sdb = client_get_database(con->client);
355     const char *zproxy = session_setting_oneval(sdb, PZ_ZPROXY);
356     const char *apdulog = session_setting_oneval(sdb, PZ_APDULOG);
357
358     assert(host->ipport);
359     assert(con);
360
361     ZOOM_options_set(zoptions, "async", "1");
362     ZOOM_options_set(zoptions, "implementationName", PACKAGE_NAME);
363     ZOOM_options_set(zoptions, "implementationVersion", VERSION);
364         
365     if ((charset = session_setting_oneval(sdb, PZ_NEGOTIATION_CHARSET)))
366         ZOOM_options_set(zoptions, "charset", charset);
367     
368     if (zproxy && *zproxy)
369     {
370         con->zproxy = xstrdup(zproxy);
371         ZOOM_options_set(zoptions, "proxy", zproxy);
372     }
373     if (apdulog && *apdulog)
374         ZOOM_options_set(zoptions, "apdulog", apdulog);
375
376     if ((auth = session_setting_oneval(sdb, PZ_AUTHENTICATION)))
377         ZOOM_options_set(zoptions, "user", auth);
378     if ((sru = session_setting_oneval(sdb, PZ_SRU)) && *sru)
379         ZOOM_options_set(zoptions, "sru", sru);
380     if ((sru_version = session_setting_oneval(sdb, PZ_SRU_VERSION)) 
381         && *sru_version)
382         ZOOM_options_set(zoptions, "sru_version", sru_version);
383
384     if (!(link = ZOOM_connection_create(zoptions)))
385     {
386         yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create ZOOM Connection");
387         ZOOM_options_destroy(zoptions);
388         return -1;
389     }
390
391     if (sru && *sru)
392     {
393         char http_hostport[512];
394         strcpy(http_hostport, "http://");
395         strcat(http_hostport, host->hostport);
396         ZOOM_connection_connect(link, http_hostport, 0);
397     }
398     else
399         ZOOM_connection_connect(link, host->ipport, 0);
400     
401     con->link = link;
402     con->iochan = iochan_create(0, connection_handler, 0);
403     con->state = Conn_Connecting;
404     iochan_settimeout(con->iochan, con->operation_timeout);
405     iochan_setdata(con->iochan, con);
406     iochan_setsocketfun(con->iochan, socketfun);
407     iochan_setmaskfun(con->iochan, maskfun);
408     iochan_add(iochan_man, con->iochan);
409
410     /* this fragment is bad DRY: from client_prep_connection */
411     client_set_state(con->client, Client_Connecting);
412     ZOOM_options_destroy(zoptions);
413     return 0;
414 }
415
416 const char *connection_get_url(struct connection *co)
417 {
418     return client_get_url(co->client);
419 }
420
421 // Ensure that client has a connection associated
422 int client_prep_connection(struct client *cl,
423                            int operation_timeout, int session_timeout,
424                            iochan_man_t iochan_man)
425 {
426     struct connection *co;
427     struct session *se = client_get_session(cl);
428     struct host *host = client_get_host(cl);
429     struct session_database *sdb = client_get_database(cl);
430     const char *zproxy = session_setting_oneval(sdb, PZ_ZPROXY);
431
432     if (zproxy && zproxy[0] == '\0')
433         zproxy = 0;
434
435     if (!host)
436         return 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             co->operation_timeout = operation_timeout;
464             co->session_timeout = session_timeout;
465             /* tells ZOOM to reconnect if necessary. Disabled becuase
466                the ZOOM_connection_connect flushes the task queue */
467             ZOOM_connection_connect(co->link, 0, 0);
468         }
469         else
470         {
471             co = connection_create(cl, operation_timeout, session_timeout,
472                                    iochan_man);
473         }
474     }
475
476     if (co && co->link)
477         return 1;
478     else
479         return 0;
480 }
481
482 /*
483  * Local variables:
484  * c-basic-offset: 4
485  * c-file-style: "Stroustrup"
486  * indent-tabs-mode: nil
487  * End:
488  * vim: shiftwidth=4 tabstop=8 expandtab
489  */
490