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