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