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