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