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