02509cf422798594e3358cc68633e8e0ea67167d
[pazpar2-moved-to-github.git] / src / connection.c
1 /* This file is part of Pazpar2.
2    Copyright (C) 2006-2012 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(void)
75 {
76     return connection_use(0);
77 }
78
79
80 #else
81 #define connection_use(x)
82 #define connections_count(x) 0
83 #define connections_count_total(x) 0
84 #endif
85
86
87 /** \brief Represents a physical, reusable  connection to a remote Z39.50 host
88  */
89 struct connection {
90     IOCHAN iochan;
91     ZOOM_connection link;
92     struct host *host;
93     struct client *client;
94     char *zproxy;
95     enum {
96         Conn_Closed,
97         Conn_Connecting,
98         Conn_Open
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->url);
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                                             struct host *host,
169                                             int operation_timeout,
170                                             int session_timeout,
171                                             iochan_man_t iochan_man)
172 {
173     struct connection *co;
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_Closed;
183     co->operation_timeout = operation_timeout;
184     co->session_timeout = session_timeout;
185     
186     if (host->ipport)
187         connection_connect(co, iochan_man);
188
189     yaz_mutex_enter(host->mutex);
190     co->next = co->host->connections;
191     co->host->connections = co;
192     yaz_mutex_leave(host->mutex);
193
194     connection_use(1);
195     return co;
196 }
197
198 static void non_block_events(struct connection *co)
199 {
200     int got_records = 0;
201     IOCHAN iochan = co->iochan;
202     ZOOM_connection link = co->link;
203     while (1)
204     {
205         struct client *cl = co->client;
206         int ev;
207         int r = ZOOM_event_nonblock(1, &link);
208         if (!r)
209             break;
210         if (!cl)
211             continue;
212         ev = ZOOM_connection_last_event(link);
213         
214 #if 1
215         yaz_log(YLOG_DEBUG, "%p Connection ZOOM_EVENT_%s", co, ZOOM_get_event_str(ev));
216 #endif
217         switch (ev) 
218         {
219         case ZOOM_EVENT_END:
220             {
221                 const char *error, *addinfo;
222                 int err;
223                 if ((err = ZOOM_connection_error(link, &error, &addinfo)))
224                 {
225                     yaz_log(YLOG_LOG, "Error %s from %s",
226                             error, client_get_id(cl));
227                     client_set_diagnostic(cl, err, addinfo);
228                     client_set_state(cl, Client_Error);
229                 }
230                 else
231                 {
232                     iochan_settimeout(iochan, co->session_timeout);
233                     client_set_state(cl, Client_Idle);
234                 }
235                 yaz_cond_broadcast(co->host->cond_ready);
236             }
237             break;
238         case ZOOM_EVENT_SEND_DATA:
239             break;
240         case ZOOM_EVENT_RECV_DATA:
241             break;
242         case ZOOM_EVENT_UNKNOWN:
243             break;
244         case ZOOM_EVENT_SEND_APDU:
245             client_set_state(co->client, Client_Working);
246             iochan_settimeout(iochan, co->operation_timeout);
247             break;
248         case ZOOM_EVENT_RECV_APDU:
249             break;
250         case ZOOM_EVENT_CONNECT:
251             yaz_log(YLOG_LOG, "Connected to %s", client_get_id(cl));
252             co->state = Conn_Open;
253             break;
254         case ZOOM_EVENT_RECV_SEARCH:
255             client_search_response(cl);
256             break;
257         case ZOOM_EVENT_RECV_RECORD:
258             client_record_response(cl);
259             got_records = 1;
260             break;
261         default:
262             yaz_log(YLOG_LOG, "Unhandled event (%d) from %s",
263                     ev, client_get_id(cl));
264             break;
265         }
266     }
267     if (got_records)
268     {
269         struct client *cl = co->client;
270         if (cl)
271         {
272             client_check_preferred_watch(cl);
273             client_got_records(cl);
274         }
275     }
276 }
277
278 void connection_continue(struct connection *co)
279 {
280     int r = ZOOM_connection_exec_task(co->link);
281     if (!r)
282     {
283         const char *error, *addinfo;
284         int err;
285         if ((err = ZOOM_connection_error(co->link, &error, &addinfo)))
286         {
287             if (co->client)
288             {
289                 yaz_log(YLOG_LOG, "Error %s from %s",
290                         error, client_get_id(co->client));
291                 client_set_diagnostic(co->client, err, addinfo);
292                 client_set_state_nb(co->client, Client_Error);
293             }
294         }
295     }
296     else
297     {
298         iochan_setflags(co->iochan, ZOOM_connection_get_mask(co->link));
299         iochan_setfd(co->iochan, ZOOM_connection_get_socket(co->link));
300     }
301 }
302
303 static void connection_handler(IOCHAN iochan, int event)
304 {
305     struct connection *co = iochan_getdata(iochan);
306     struct client *cl;
307     struct host *host = co->host;
308
309     yaz_mutex_enter(host->mutex);
310     cl = co->client;
311     if (!cl) 
312     {
313         /* no client associated with it.. We are probably getting
314            a closed connection from the target.. Or, perhaps, an unexpected
315            package.. We will just close the connection */
316         yaz_log(YLOG_LOG, "timeout connection %p event=%d", co, event);
317         remove_connection_from_host(co);
318         yaz_mutex_leave(host->mutex);
319         connection_destroy(co);
320     }
321     else if (event & EVENT_TIMEOUT)
322     {
323         if (co->state == Conn_Connecting)
324         {
325             yaz_log(YLOG_WARN, "%p connect timeout %s", co, client_get_id(cl));
326
327             client_set_state(cl, Client_Error);
328             remove_connection_from_host(co);
329             yaz_mutex_leave(host->mutex);
330             connection_destroy(co);
331         }
332         else
333         {
334             yaz_log(YLOG_LOG,  "%p Connection idle timeout %s", co, client_get_id(cl));
335             remove_connection_from_host(co);
336             yaz_mutex_leave(host->mutex);
337             connection_destroy(co);
338         }
339     }
340     else
341     {
342         yaz_mutex_leave(host->mutex);
343
344         client_lock(cl);
345         non_block_events(co);
346
347         ZOOM_connection_fire_event_socket(co->link, event);
348         
349         non_block_events(co);
350         client_unlock(cl);
351
352         if (co->link)
353         {
354             iochan_setflags(iochan, ZOOM_connection_get_mask(co->link));
355             iochan_setfd(iochan, ZOOM_connection_get_socket(co->link));
356         }
357     }
358 }
359
360
361 // Disassociate connection from client
362 static void connection_release(struct connection *co)
363 {
364     struct client *cl = co->client;
365
366     if (!cl)
367         return;
368     client_set_connection(cl, 0);
369     co->client = 0;
370 }
371
372 void connect_resolver_host(struct host *host, iochan_man_t iochan_man)
373 {
374     struct connection *con;
375
376 start:
377     yaz_mutex_enter(host->mutex);
378     con = host->connections;
379     while (con)
380     {
381         if (con->state == Conn_Closed)
382         {
383             if (!host->ipport) /* unresolved */
384             {
385                 remove_connection_from_host(con);
386                 yaz_mutex_leave(host->mutex);
387                 connection_destroy(con);
388                 goto start;
389                 /* start all over .. at some point it will be NULL */
390             }
391             else if (!con->client)
392             {
393                 remove_connection_from_host(con);
394                 yaz_mutex_leave(host->mutex);
395                 connection_destroy(con);
396                 /* start all over .. at some point it will be NULL */
397                 goto start;
398             }
399             else
400             {
401                 yaz_mutex_leave(host->mutex);
402                 connection_connect(con, iochan_man);
403                 client_start_search(con->client);
404                 goto start;
405             }
406         }
407         else
408         {
409             yaz_log(YLOG_LOG, "connect_resolver_host: state=%d", con->state);
410             con = con->next;
411         }
412     }
413     yaz_mutex_leave(host->mutex);
414 }
415
416 static struct host *connection_get_host(struct connection *con)
417 {
418     return con->host;
419 }
420
421 static int connection_connect(struct connection *con, iochan_man_t iochan_man)
422 {
423     struct host *host = connection_get_host(con);
424     ZOOM_options zoptions = ZOOM_options_create();
425     const char *auth;
426     const char *charset;
427     const char *sru;
428     const char *sru_version = 0;
429
430     struct session_database *sdb = client_get_database(con->client);
431     const char *apdulog = session_setting_oneval(sdb, PZ_APDULOG);
432
433     assert(con);
434
435     ZOOM_options_set(zoptions, "async", "1");
436     ZOOM_options_set(zoptions, "implementationName", PACKAGE_NAME);
437     ZOOM_options_set(zoptions, "implementationVersion", VERSION);
438         
439     if ((charset = session_setting_oneval(sdb, PZ_NEGOTIATION_CHARSET)))
440         ZOOM_options_set(zoptions, "charset", charset);
441     
442     assert(host->ipport);
443     if (host->proxy)
444     {
445         yaz_log(YLOG_LOG, "proxy=%s", host->ipport);
446         ZOOM_options_set(zoptions, "proxy", host->ipport);
447     }
448     else
449     {
450         assert(host->tproxy);
451         yaz_log(YLOG_LOG, "tproxy=%s", host->ipport);
452         ZOOM_options_set(zoptions, "tproxy", host->ipport);
453     }   
454
455     if (apdulog && *apdulog)
456         ZOOM_options_set(zoptions, "apdulog", apdulog);
457
458     if ((auth = session_setting_oneval(sdb, PZ_AUTHENTICATION)))
459         ZOOM_options_set(zoptions, "user", auth);
460     if ((sru = session_setting_oneval(sdb, PZ_SRU)) && *sru)
461         ZOOM_options_set(zoptions, "sru", sru);
462     if ((sru_version = session_setting_oneval(sdb, PZ_SRU_VERSION)) 
463         && *sru_version)
464         ZOOM_options_set(zoptions, "sru_version", sru_version);
465     if (!(con->link = ZOOM_connection_create(zoptions)))
466     {
467         yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create ZOOM Connection");
468         ZOOM_options_destroy(zoptions);
469         return -1;
470     }
471
472     if (sru && *sru)
473     {
474         char http_hostport[512];
475         strcpy(http_hostport, "http://");
476         strcat(http_hostport, host->url);
477         yaz_log(YLOG_LOG, "SRU connect to : %s", http_hostport);
478         ZOOM_connection_connect(con->link, http_hostport, 0);
479     }
480     else
481     {
482         ZOOM_connection_connect(con->link, host->url, 0);
483     }
484     con->iochan = iochan_create(-1, connection_handler, 0, "connection_socket");
485     con->state = Conn_Connecting;
486     iochan_settimeout(con->iochan, con->operation_timeout);
487     iochan_setdata(con->iochan, con);
488     iochan_add(iochan_man, con->iochan);
489
490     client_set_state(con->client, Client_Connecting);
491     ZOOM_options_destroy(zoptions);
492     return 0;
493 }
494
495 // Ensure that client has a connection associated
496 int client_prep_connection(struct client *cl,
497                            int operation_timeout, int session_timeout,
498                            iochan_man_t iochan_man,
499                            const struct timeval *abstime,
500                            int ok_with_working)
501 {
502     struct connection *co;
503     struct session_database *sdb = client_get_database(cl);
504     const char *zproxy = session_setting_oneval(sdb, PZ_ZPROXY);
505     const char *url = session_setting_oneval(sdb, PZ_URL);
506     const char *sru = session_setting_oneval(sdb, PZ_SRU);
507     struct host *host = 0;
508     int default_port = *sru ? 80 : 210;
509
510     if (zproxy && zproxy[0] == '\0')
511         zproxy = 0;
512
513     if (!url || !*url)
514         url = sdb->database->id;
515
516     host = find_host(client_get_session(cl)->service->server->database_hosts,
517                      url, zproxy, default_port, iochan_man);
518
519     yaz_log(YLOG_DEBUG, "client_prep_connection: target=%s url=%s",
520             client_get_id(cl), url);
521     if (!host)
522         return 0;
523
524     co = client_get_connection(cl);
525
526     if (co)
527     {
528         assert(co->host);
529         if (co->host == host && (client_get_state(cl) == Client_Idle
530                                  || ok_with_working))
531         {
532             return 2;
533         }
534         client_incref(cl);
535         connection_release(co);
536         co = 0;
537     }
538     if (!co)
539     {
540         int max_connections = 0;
541         int reuse_connections = 1;
542         const char *v = session_setting_oneval(client_get_database(cl),
543                                                PZ_MAX_CONNECTIONS);
544         if (v && *v)
545             max_connections = atoi(v);
546         
547         v = session_setting_oneval(client_get_database(cl),
548                 PZ_REUSE_CONNECTIONS);
549         if (v && *v)
550             reuse_connections = atoi(v);
551
552         // See if someone else has an idle connection
553         // We should look at timestamps here to select the longest-idle connection
554         yaz_mutex_enter(host->mutex);
555         while (1)
556         {
557             int num_connections = 0;
558             for (co = host->connections; co; co = co->next)
559                 num_connections++;
560             if (reuse_connections)
561             {
562                 for (co = host->connections; co; co = co->next)
563                 {
564                     if (connection_is_idle(co) &&
565                         (!co->client || client_get_state(co->client) == Client_Idle) &&
566                         !strcmp(ZOOM_connection_option_get(co->link, "user"),
567                                 session_setting_oneval(client_get_database(cl),
568                                                        PZ_AUTHENTICATION)))
569                     {
570                         if (zproxy == 0 && co->zproxy == 0)
571                             break;
572                         if (zproxy && co->zproxy && !strcmp(zproxy, co->zproxy))
573                             break;
574                     }
575                 }
576                 if (co)
577                 {
578                     yaz_log(YLOG_LOG, "num_connections = %d (reusing)", num_connections);
579                     break;
580                 }
581             }
582             if (max_connections <= 0 || num_connections < max_connections)
583             {
584                 yaz_log(YLOG_LOG, "num_connections = %d (new); max = %d",
585                         num_connections, max_connections);
586                 break;
587             }
588             yaz_log(YLOG_LOG, "num_connections = %d (waiting) max = %d",
589                     num_connections, max_connections);
590             if (yaz_cond_wait(host->cond_ready, host->mutex, abstime))
591             {
592                 yaz_log(YLOG_LOG, "out of connections %s", client_get_id(cl));
593                 client_set_state(cl, Client_Error);
594                 yaz_mutex_leave(host->mutex);
595                 return 0;
596             }
597         }
598         if (co)
599         {
600             yaz_log(YLOG_LOG,  "%p Connection reuse. state: %d", co, co->state);
601             connection_release(co);
602             client_set_connection(cl, co);
603             co->client = cl;
604             /* ensure that connection is only assigned to this client
605                by marking the client non Idle */
606             client_set_state(cl, Client_Working);
607             yaz_mutex_leave(host->mutex);
608             co->operation_timeout = operation_timeout;
609             co->session_timeout = session_timeout;
610             /* tells ZOOM to reconnect if necessary. Disabled becuase
611                the ZOOM_connection_connect flushes the task queue */
612             ZOOM_connection_connect(co->link, 0, 0);
613         }
614         else
615         {
616             yaz_mutex_leave(host->mutex);
617             co = connection_create(cl, host, operation_timeout, session_timeout,
618                                    iochan_man);
619         }
620         assert(co->host);
621     }
622
623     if (co && co->link)
624         return 1;
625     else
626         return 0;
627 }
628
629 /*
630  * Local variables:
631  * c-basic-offset: 4
632  * c-file-style: "Stroustrup"
633  * indent-tabs-mode: nil
634  * End:
635  * vim: shiftwidth=4 tabstop=8 expandtab
636  */
637