struct database: rename member url to id
[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(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_Resolving,
97         Conn_Connecting,
98         Conn_Open,
99         Conn_Dead
100     } state;
101     int operation_timeout;
102     int session_timeout;
103     struct connection *next; // next for same host or next in free list
104 };
105
106 static int connection_connect(struct connection *con, iochan_man_t iochan_man);
107
108 static int connection_is_idle(struct connection *co)
109 {
110     ZOOM_connection link = co->link;
111     int event;
112
113     if (co->state != Conn_Open || !link)
114         return 0;
115
116     if (!ZOOM_connection_is_idle(link))
117         return 0;
118     event = ZOOM_connection_peek_event(link);
119     if (event == ZOOM_EVENT_NONE)
120         return 1;
121     else
122         return 0;
123 }
124
125 ZOOM_connection connection_get_link(struct connection *co)
126 {
127     return co->link;
128 }
129
130 static void remove_connection_from_host(struct connection *con)
131 {
132     struct connection **conp = &con->host->connections;
133     assert(con);
134     while (*conp)
135     {
136         if (*conp == con)
137         {
138             *conp = (*conp)->next;
139             break;
140         }
141         conp = &(*conp)->next;
142     }
143     yaz_cond_broadcast(con->host->cond_ready);
144 }
145
146 // Close connection and recycle structure
147 static void connection_destroy(struct connection *co)
148 {
149     if (co->link)
150     {
151         ZOOM_connection_destroy(co->link);
152         iochan_destroy(co->iochan);
153     }
154     yaz_log(YLOG_DEBUG, "%p Connection destroy %s", co, co->host->hostport);
155
156     if (co->client)
157     {
158         client_disconnect(co->client);
159     }
160
161     xfree(co->zproxy);
162     xfree(co);
163     connection_use(-1);
164 }
165
166 // Creates a new connection for client, associated with the host of 
167 // client's database
168 static struct connection *connection_create(struct client *cl,
169                                             struct host *host,
170                                             int operation_timeout,
171                                             int session_timeout,
172                                             iochan_man_t iochan_man)
173 {
174     struct connection *co;
175
176     co = xmalloc(sizeof(*co));
177     co->host = host;
178
179     co->client = cl;
180     co->zproxy = 0;
181     client_set_connection(cl, co);
182     co->link = 0;
183     co->state = Conn_Resolving;
184     co->operation_timeout = operation_timeout;
185     co->session_timeout = session_timeout;
186     
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_url(cl));
227                     client_set_diagnostic(cl, err);
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_url(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_url(cl));
264         }
265     }
266     if (got_records)
267     {
268         struct client *cl = co->client;
269         if (cl)
270         {
271             client_check_preferred_watch(cl);
272             client_got_records(cl);
273         }
274     }
275 }
276
277 void connection_continue(struct connection *co)
278 {
279     int r = ZOOM_connection_exec_task(co->link);
280     if (!r)
281         yaz_log(YLOG_WARN, "No task was executed for connection");
282     iochan_setflags(co->iochan, ZOOM_connection_get_mask(co->link));
283     iochan_setfd(co->iochan, ZOOM_connection_get_socket(co->link));
284 }
285
286 static void connection_handler(IOCHAN iochan, int event)
287 {
288     struct connection *co = iochan_getdata(iochan);
289     struct client *cl;
290     struct host *host = co->host;
291
292     yaz_mutex_enter(host->mutex);
293     cl = co->client;
294     if (!cl) 
295     {
296         /* no client associated with it.. We are probably getting
297            a closed connection from the target.. Or, perhaps, an unexpected
298            package.. We will just close the connection */
299         yaz_log(YLOG_LOG, "timeout connection %p event=%d", co, event);
300         remove_connection_from_host(co);
301         yaz_mutex_leave(host->mutex);
302         connection_destroy(co);
303     }
304     else if (event & EVENT_TIMEOUT)
305     {
306         if (co->state == Conn_Connecting)
307         {
308             yaz_log(YLOG_WARN, "%p connect timeout %s", co, client_get_url(cl));
309
310             client_set_state(cl, Client_Error);
311             remove_connection_from_host(co);
312             yaz_mutex_leave(host->mutex);
313             connection_destroy(co);
314         }
315         else
316         {
317             yaz_log(YLOG_LOG,  "%p Connection idle timeout %s", co, client_get_url(cl));
318             remove_connection_from_host(co);
319             yaz_mutex_leave(host->mutex);
320             connection_destroy(co);
321         }
322     }
323     else
324     {
325         yaz_mutex_leave(host->mutex);
326
327         client_lock(cl);
328         non_block_events(co);
329
330         ZOOM_connection_fire_event_socket(co->link, event);
331         
332         non_block_events(co);
333         client_unlock(cl);
334
335         if (co->link)
336         {
337             iochan_setflags(iochan, ZOOM_connection_get_mask(co->link));
338             iochan_setfd(iochan, ZOOM_connection_get_socket(co->link));
339         }
340     }
341 }
342
343
344 // Disassociate connection from client
345 static void connection_release(struct connection *co)
346 {
347     struct client *cl = co->client;
348
349     if (!cl)
350         return;
351     client_set_connection(cl, 0);
352     co->client = 0;
353 }
354
355 static struct host *connection_get_host(struct connection *con)
356 {
357     return con->host;
358 }
359
360 static int connection_connect(struct connection *con, iochan_man_t iochan_man)
361 {
362     ZOOM_connection link = 0;
363     struct host *host = connection_get_host(con);
364     ZOOM_options zoptions = ZOOM_options_create();
365     const char *auth;
366     const char *charset;
367     const char *sru;
368     const char *sru_version = 0;
369
370     struct session_database *sdb = client_get_database(con->client);
371     const char *zproxy = session_setting_oneval(sdb, PZ_ZPROXY);
372     const char *apdulog = session_setting_oneval(sdb, PZ_APDULOG);
373
374     assert(con);
375
376     ZOOM_options_set(zoptions, "async", "1");
377     ZOOM_options_set(zoptions, "implementationName", PACKAGE_NAME);
378     ZOOM_options_set(zoptions, "implementationVersion", VERSION);
379         
380     if ((charset = session_setting_oneval(sdb, PZ_NEGOTIATION_CHARSET)))
381         ZOOM_options_set(zoptions, "charset", charset);
382     
383     if (zproxy && *zproxy)
384     {
385         con->zproxy = xstrdup(zproxy);
386         ZOOM_options_set(zoptions, "proxy", zproxy);
387     }
388     if (apdulog && *apdulog)
389         ZOOM_options_set(zoptions, "apdulog", apdulog);
390
391     if ((auth = session_setting_oneval(sdb, PZ_AUTHENTICATION)))
392         ZOOM_options_set(zoptions, "user", auth);
393     if ((sru = session_setting_oneval(sdb, PZ_SRU)) && *sru)
394         ZOOM_options_set(zoptions, "sru", sru);
395     if ((sru_version = session_setting_oneval(sdb, PZ_SRU_VERSION)) 
396         && *sru_version)
397         ZOOM_options_set(zoptions, "sru_version", sru_version);
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     {
414         ZOOM_connection_connect(link, host->hostport, 0);
415     }
416     
417     con->link = link;
418     con->iochan = iochan_create(-1, connection_handler, 0, "connection_socket");
419     con->state = Conn_Connecting;
420     iochan_settimeout(con->iochan, con->operation_timeout);
421     iochan_setdata(con->iochan, con);
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 // Ensure that client has a connection associated
431 int client_prep_connection(struct client *cl,
432                            int operation_timeout, int session_timeout,
433                            iochan_man_t iochan_man,
434                            const struct timeval *abstime)
435 {
436     struct connection *co;
437     struct session_database *sdb = client_get_database(cl);
438     const char *zproxy = session_setting_oneval(sdb, PZ_ZPROXY);
439     const char *url = session_setting_oneval(sdb, PZ_URL);
440     struct host *host = 0;
441
442     if (zproxy && zproxy[0] == '\0')
443         zproxy = 0;
444
445     if (!url || !*url)
446         url = sdb->database->id;
447
448     host = find_host(client_get_session(cl)->service->server->database_hosts,
449                      url);
450
451     yaz_log(YLOG_DEBUG, "client_prep_connection: target=%s url=%s",
452             client_get_url(cl), url);
453
454     co = client_get_connection(cl);
455
456     if (co)
457     {
458         assert(co->host);
459         if (co->host == host)
460             ;  /* reusing connection. It's ours! */
461         else 
462         {
463             client_incref(cl);
464             connection_release(co);
465             co = 0;
466         }
467     }
468     if (!co)
469     {
470         int max_connections = 0;
471         int reuse_connections = 1;
472         const char *v = session_setting_oneval(client_get_database(cl),
473                                                PZ_MAX_CONNECTIONS);
474         if (v && *v)
475             max_connections = atoi(v);
476         
477         v = session_setting_oneval(client_get_database(cl),
478                 PZ_REUSE_CONNECTIONS);
479         if (v && *v)
480             reuse_connections = atoi(v);
481
482         // See if someone else has an idle connection
483         // We should look at timestamps here to select the longest-idle connection
484         yaz_mutex_enter(host->mutex);
485         while (1)
486         {
487             int num_connections = 0;
488             for (co = host->connections; co; co = co->next)
489                 num_connections++;
490             if (reuse_connections)
491             {
492                 for (co = host->connections; co; co = co->next)
493                 {
494                     if (connection_is_idle(co) &&
495                         (!co->client || client_get_state(co->client) == Client_Idle) &&
496                         !strcmp(ZOOM_connection_option_get(co->link, "user"),
497                                 session_setting_oneval(client_get_database(cl),
498                                                        PZ_AUTHENTICATION)))
499                     {
500                         if (zproxy == 0 && co->zproxy == 0)
501                             break;
502                         if (zproxy && co->zproxy && !strcmp(zproxy, co->zproxy))
503                             break;
504                     }
505                 }
506                 if (co)
507                 {
508                     yaz_log(YLOG_LOG, "num_connections = %d (reusing)", num_connections);
509                     break;
510                 }
511             }
512             if (max_connections <= 0 || num_connections < max_connections)
513             {
514                 yaz_log(YLOG_LOG, "num_connections = %d (new); max = %d",
515                         num_connections, max_connections);
516                 break;
517             }
518             yaz_log(YLOG_LOG, "num_connections = %d (waiting) max = %d",
519                     num_connections, max_connections);
520             if (yaz_cond_wait(host->cond_ready, host->mutex, abstime))
521             {
522                 yaz_log(YLOG_LOG, "out of connections %s", client_get_url(cl));
523                 client_set_state(cl, Client_Error);
524                 yaz_mutex_leave(host->mutex);
525                 return 0;
526             }
527         }
528         if (co)
529         {
530             yaz_log(YLOG_LOG,  "%p Connection reuse. state: %d", co, co->state);
531             connection_release(co);
532             client_set_connection(cl, co);
533             co->client = cl;
534             /* ensure that connection is only assigned to this client
535                by marking the client non Idle */
536             client_set_state(cl, Client_Working);
537             yaz_mutex_leave(host->mutex);
538             co->operation_timeout = operation_timeout;
539             co->session_timeout = session_timeout;
540             /* tells ZOOM to reconnect if necessary. Disabled becuase
541                the ZOOM_connection_connect flushes the task queue */
542             ZOOM_connection_connect(co->link, 0, 0);
543         }
544         else
545         {
546             yaz_mutex_leave(host->mutex);
547             co = connection_create(cl, host, operation_timeout, session_timeout,
548                                    iochan_man);
549         }
550         assert(co->host);
551     }
552
553     if (co && co->link)
554         return 1;
555     else
556         return 0;
557 }
558
559 /*
560  * Local variables:
561  * c-basic-offset: 4
562  * c-file-style: "Stroustrup"
563  * indent-tabs-mode: nil
564  * End:
565  * vim: shiftwidth=4 tabstop=8 expandtab
566  */
567