3ef5cf6b94cde4708fbb0b4d25cd70fa885c7117
[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 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         Conn_Dead
83     } state;
84     int operation_timeout;
85     int session_timeout;
86     struct connection *next; // next for same host or next in free list
87 };
88
89 static int connection_connect(struct connection *con, iochan_man_t iochan_man);
90
91 static int connection_is_idle(struct connection *co)
92 {
93     ZOOM_connection link = co->link;
94     int event;
95
96     if (co->state != Conn_Open || !link)
97         return 0;
98
99     if (!ZOOM_connection_is_idle(link))
100         return 0;
101     event = ZOOM_connection_peek_event(link);
102     if (event == ZOOM_EVENT_NONE)
103         return 1;
104     else
105         return 0;
106 }
107
108 ZOOM_connection connection_get_link(struct connection *co)
109 {
110     return co->link;
111 }
112
113 static void remove_connection_from_host(struct connection *con)
114 {
115     struct connection **conp = &con->host->connections;
116     assert(con);
117     while (*conp)
118     {
119         if (*conp == con)
120         {
121             *conp = (*conp)->next;
122             break;
123         }
124         conp = &(*conp)->next;
125     }
126     yaz_cond_broadcast(con->host->cond_ready);
127 }
128
129 // Close connection and recycle structure
130 static void connection_destroy(struct connection *co)
131 {
132     if (co->link)
133     {
134         ZOOM_connection_destroy(co->link);
135         iochan_destroy(co->iochan);
136     }
137     yaz_log(YLOG_DEBUG, "%p Connection destroy %s", co, co->host->hostport);
138
139     if (co->client)
140     {
141         client_disconnect(co->client);
142     }
143
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 1
198         yaz_log(YLOG_DEBUG, "%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         remove_connection_from_host(co);
284         yaz_mutex_leave(host->mutex);
285         connection_destroy(co);
286     }
287     else if (event & EVENT_TIMEOUT)
288     {
289         if (co->state == Conn_Connecting)
290         {
291             yaz_log(YLOG_WARN, "%p connect timeout %s", co, client_get_url(cl));
292
293             client_set_state(cl, Client_Error);
294             remove_connection_from_host(co);
295             yaz_mutex_leave(host->mutex);
296             connection_destroy(co);
297         }
298         else
299         {
300             yaz_log(YLOG_LOG,  "%p Connection idle timeout %s", co, client_get_url(cl));
301             remove_connection_from_host(co);
302             yaz_mutex_leave(host->mutex);
303             connection_destroy(co);
304         }
305     }
306     else
307     {
308         yaz_mutex_leave(host->mutex);
309
310         client_lock(cl);
311         non_block_events(co);
312
313         ZOOM_connection_fire_event_socket(co->link, event);
314         
315         non_block_events(co);
316         client_unlock(cl);
317
318         if (co->link)
319         {
320             iochan_setflags(iochan, ZOOM_connection_get_mask(co->link));
321             iochan_setfd(iochan, ZOOM_connection_get_socket(co->link));
322         }
323     }
324 }
325
326
327 // Disassociate connection from client
328 static void connection_release(struct connection *co)
329 {
330     struct client *cl = co->client;
331
332     if (!cl)
333         return;
334     client_set_connection(cl, 0);
335     co->client = 0;
336 }
337
338 void connect_resolver_host(struct host *host, iochan_man_t iochan_man)
339 {
340     struct connection *con;
341
342 start:
343     yaz_mutex_enter(host->mutex);
344     con = host->connections;
345     while (con)
346     {
347         if (con->state == Conn_Resolving)
348         {
349             if (!host->ipport) /* unresolved */
350             {
351                 remove_connection_from_host(con);
352                 yaz_mutex_leave(host->mutex);
353                 connection_destroy(con);
354                 goto start;
355                 /* start all over .. at some point it will be NULL */
356             }
357             else if (!con->client)
358             {
359                 remove_connection_from_host(con);
360                 yaz_mutex_leave(host->mutex);
361                 connection_destroy(con);
362                 /* start all over .. at some point it will be NULL */
363                 goto start;
364             }
365             else
366             {
367                 yaz_mutex_leave(host->mutex);
368                 connection_connect(con, iochan_man);
369                 client_start_search(con->client);
370                 goto start;
371             }
372         }
373         else
374         {
375             yaz_log(YLOG_LOG, "connect_resolver_host: state=%d", con->state);
376             con = con->next;
377         }
378     }
379     yaz_mutex_leave(host->mutex);
380 }
381
382 static struct host *connection_get_host(struct connection *con)
383 {
384     return con->host;
385 }
386
387 static int connection_connect(struct connection *con, iochan_man_t iochan_man)
388 {
389     ZOOM_connection link = 0;
390     struct host *host = connection_get_host(con);
391     ZOOM_options zoptions = ZOOM_options_create();
392     const char *auth;
393     const char *charset;
394     const char *sru;
395     const char *sru_version = 0;
396     const char *extra_args  = 0;
397
398     struct session_database *sdb = client_get_database(con->client);
399     const char *zproxy = session_setting_oneval(sdb, PZ_ZPROXY);
400     const char *apdulog = session_setting_oneval(sdb, PZ_APDULOG);
401
402     assert(host->ipport);
403     assert(con);
404
405     ZOOM_options_set(zoptions, "async", "1");
406     ZOOM_options_set(zoptions, "implementationName", PACKAGE_NAME);
407     ZOOM_options_set(zoptions, "implementationVersion", VERSION);
408         
409     if ((charset = session_setting_oneval(sdb, PZ_NEGOTIATION_CHARSET)))
410         ZOOM_options_set(zoptions, "charset", charset);
411     
412     if (zproxy && *zproxy)
413     {
414         con->zproxy = xstrdup(zproxy);
415         ZOOM_options_set(zoptions, "proxy", zproxy);
416     }
417     if (apdulog && *apdulog)
418         ZOOM_options_set(zoptions, "apdulog", apdulog);
419
420     if ((auth = session_setting_oneval(sdb, PZ_AUTHENTICATION)))
421         ZOOM_options_set(zoptions, "user", auth);
422     if ((sru = session_setting_oneval(sdb, PZ_SRU)) && *sru)
423         ZOOM_options_set(zoptions, "sru", sru);
424     if ((sru_version = session_setting_oneval(sdb, PZ_SRU_VERSION)) 
425         && *sru_version)
426         ZOOM_options_set(zoptions, "sru_version", sru_version);
427     if ((extra_args = session_setting_oneval(sdb, PZ_EXTRA_ARGS)) && *extra_args)
428         ZOOM_options_set(zoptions, "extraArgs", extra_args);
429
430     if (!(link = ZOOM_connection_create(zoptions)))
431     {
432         yaz_log(YLOG_FATAL|YLOG_ERRNO, "Failed to create ZOOM Connection");
433         ZOOM_options_destroy(zoptions);
434         return -1;
435     }
436
437     if (sru && *sru)
438     {
439         char http_hostport[512];
440         strcpy(http_hostport, "http://");
441         strcat(http_hostport, host->hostport);
442         ZOOM_connection_connect(link, http_hostport, 0);
443     }
444     else if (zproxy && *zproxy)
445         ZOOM_connection_connect(link, host->hostport, 0);        
446     else
447         ZOOM_connection_connect(link, host->ipport, 0);
448     
449     con->link = link;
450     con->iochan = iochan_create(-1, connection_handler, 0, "connection_socket");
451     con->state = Conn_Connecting;
452     iochan_settimeout(con->iochan, con->operation_timeout);
453     iochan_setdata(con->iochan, con);
454     iochan_add(iochan_man, con->iochan);
455
456     /* this fragment is bad DRY: from client_prep_connection */
457     client_set_state(con->client, Client_Connecting);
458     ZOOM_options_destroy(zoptions);
459     return 0;
460 }
461
462 // Ensure that client has a connection associated
463 int client_prep_connection(struct client *cl,
464                            int operation_timeout, int session_timeout,
465                            iochan_man_t iochan_man,
466                            const struct timeval *abstime)
467 {
468     struct connection *co;
469     struct host *host = client_get_host(cl);
470     struct session_database *sdb = client_get_database(cl);
471     const char *zproxy = session_setting_oneval(sdb, PZ_ZPROXY);
472
473     if (zproxy && zproxy[0] == '\0')
474         zproxy = 0;
475
476     if (!host)
477         return 0;
478
479     co = client_get_connection(cl);
480
481     yaz_log(YLOG_DEBUG, "Client prep %s", client_get_url(cl));
482
483     if (!co)
484     {
485         int max_connections = 0;
486         int reuse_connections = 1;
487         const char *v = session_setting_oneval(client_get_database(cl),
488                                                PZ_MAX_CONNECTIONS);
489         if (v && *v)
490             max_connections = atoi(v);
491
492         v = session_setting_oneval(client_get_database(cl),
493                 PZ_REUSE_CONNECTIONS);
494         if (v && *v)
495             reuse_connections = atoi(v);
496
497         // See if someone else has an idle connection
498         // We should look at timestamps here to select the longest-idle connection
499         yaz_mutex_enter(host->mutex);
500         while (1)
501         {
502             int num_connections = 0;
503             for (co = host->connections; co; co = co->next)
504                 num_connections++;
505             if (reuse_connections) {
506                 for (co = host->connections; co; co = co->next)
507                 {
508                     if (connection_is_idle(co) &&
509                         (!co->client || client_get_state(co->client) == Client_Idle) &&
510                         !strcmp(ZOOM_connection_option_get(co->link, "user"),
511                                 session_setting_oneval(client_get_database(cl),
512                                                        PZ_AUTHENTICATION)))
513                     {
514                         if (zproxy == 0 && co->zproxy == 0)
515                             break;
516                         if (zproxy && co->zproxy && !strcmp(zproxy, co->zproxy))
517                             break;
518                     }
519                 }
520                 if (co)
521                 {
522                     yaz_log(YLOG_LOG, "num_connections = %d (reusing)", num_connections);
523                     break;
524                 }
525             }
526             if (max_connections <= 0 || num_connections < max_connections)
527             {
528                 yaz_log(YLOG_LOG, "num_connections = %d (new); max = %d",
529                         num_connections, max_connections);
530                 break;
531             }
532             yaz_log(YLOG_LOG, "num_connections = %d (waiting) max = %d",
533                     num_connections, max_connections);
534             if (yaz_cond_wait(host->cond_ready, host->mutex, abstime))
535             {
536                 yaz_log(YLOG_LOG, "out of connections %s", client_get_url(cl));
537                 client_set_state(cl, Client_Error);
538                 yaz_mutex_leave(host->mutex);
539                 return 0;
540             }
541         }
542         if (co)
543         {
544             yaz_log(YLOG_LOG,  "%p Connection reuse. state: %d", co, co->state);
545             connection_release(co);
546             client_set_connection(cl, co);
547             co->client = cl;
548             /* ensure that connection is only assigned to this client
549                by marking the client non Idle */
550             client_set_state(cl, Client_Working);
551             yaz_mutex_leave(host->mutex);
552             co->operation_timeout = operation_timeout;
553             co->session_timeout = session_timeout;
554             /* tells ZOOM to reconnect if necessary. Disabled becuase
555                the ZOOM_connection_connect flushes the task queue */
556             ZOOM_connection_connect(co->link, 0, 0);
557         }
558         else
559         {
560             yaz_mutex_leave(host->mutex);
561             co = connection_create(cl, operation_timeout, session_timeout,
562                                    iochan_man);
563         }
564     }
565
566     if (co && co->link)
567         return 1;
568     else
569         return 0;
570 }
571
572 /*
573  * Local variables:
574  * c-basic-offset: 4
575  * c-file-style: "Stroustrup"
576  * indent-tabs-mode: nil
577  * End:
578  * vim: shiftwidth=4 tabstop=8 expandtab
579  */
580