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