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