3cad500f71b56e16d881f7998eeac56a24993f7f
[debian/amanda] / common-src / protocol.c
1 /*
2  * Amanda, The Advanced Maryland Automatic Network Disk Archiver
3  * Copyright (c) 1991-1999 University of Maryland at College Park
4  * All Rights Reserved.
5  *
6  * Permission to use, copy, modify, distribute, and sell this software and its
7  * documentation for any purpose is hereby granted without fee, provided that
8  * the above copyright notice appear in all copies and that both that
9  * copyright notice and this permission notice appear in supporting
10  * documentation, and that the name of U.M. not be used in advertising or
11  * publicity pertaining to distribution of the software without specific,
12  * written prior permission.  U.M. makes no representations about the
13  * suitability of this software for any purpose.  It is provided "as is"
14  * without express or implied warranty.
15  *
16  * U.M. DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL U.M.
18  * BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
19  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
20  * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
21  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
22  *
23  * Authors: the Amanda Development Team.  Its members are listed in a
24  * file named AUTHORS, in the root directory of this distribution.
25  */
26 /*
27  * $Id: protocol.c,v 1.45 2006/05/25 17:07:31 martinea Exp $
28  *
29  * implements amanda protocol
30  */
31 #include "amanda.h"
32 #include "conffile.h"
33 #include "event.h"
34 #include "packet.h"
35 #include "security.h"
36 #include "protocol.h"
37
38 #define proto_debug(i, ...) do {        \
39        if ((i) <= debug_protocol) {     \
40            dbprintf(__VA_ARGS__);       \
41        }                                \
42 } while (0)
43
44 /*
45  * Valid actions that can be passed to the state machine
46  */
47 typedef enum {
48         PA_START,
49         PA_TIMEOUT,
50         PA_ERROR,
51         PA_RCVDATA,
52         PA_CONTPEND,
53         PA_PENDING,
54         PA_CONTINUE,
55         PA_FINISH,
56         PA_ABORT
57 } p_action_t;
58
59 /*
60  * The current state type.  States are represented as function
61  * vectors.
62  */
63 struct proto;
64 typedef p_action_t (*pstate_t)(struct proto *, p_action_t, pkt_t *);
65
66 /*
67  * This is a request structure that is wrapped around a packet while it
68  * is being passed through amanda.  It holds the timeouts, state, and handles
69  * for each request.
70  */
71 typedef struct proto {
72     pstate_t state;                     /* current state of the request */
73     char *hostname;                     /* remote host */
74     const security_driver_t *security_driver;   /* for connect retries */
75     security_handle_t *security_handle; /* network stream for this req */
76     time_t timeout;                     /* seconds for this timeout */
77     time_t repwait;                     /* seconds to wait for reply */
78     time_t origtime;                    /* orig start time of this request */
79     time_t curtime;                     /* time when this attempt started */
80     int connecttries;                   /* times we'll retry a connect */
81     int resettries;                     /* times we'll resend a REQ */
82     int reqtries;                       /* times we'll wait for an a ACK */
83     pkt_t req;                          /* the actual wire request */
84     protocol_sendreq_callback continuation; /* call when req dies/finishes */
85     void *datap;                        /* opaque cookie passed to above */
86     char *(*conf_fn)(char *, void *);   /* configuration function */
87 } proto_t;
88
89 #define CONNECT_WAIT    5       /* secs between connect attempts */
90 #define ACK_WAIT        10      /* time (secs) to wait for ACK - keep short */
91 #define RESET_TRIES     2       /* num restarts (reboot/crash) */
92 #define CURTIME (time(0) - proto_init_time) /* time relative to start */
93
94 /* if no reply in an hour, just forget it */
95 #define DROP_DEAD_TIME(t)       (CURTIME - (t) > (60 * 60))
96
97 /* get the size of an array */
98 #define ASIZE(arr)      (int)(sizeof(arr) / sizeof((arr)[0]))
99
100 /*
101  * Initialization time
102  */
103 static time_t proto_init_time;
104
105 /* local functions */
106
107 static const char *action2str(p_action_t);
108 static const char *pstate2str(pstate_t);
109
110 static void connect_callback(void *, security_handle_t *, security_status_t);
111 static void connect_wait_callback(void *);
112 static void recvpkt_callback(void *, pkt_t *, security_status_t);
113
114 static p_action_t s_sendreq(proto_t *, p_action_t, pkt_t *);
115 static p_action_t s_ackwait(proto_t *, p_action_t, pkt_t *);
116 static p_action_t s_repwait(proto_t *, p_action_t, pkt_t *);
117 static void state_machine(proto_t *, p_action_t, pkt_t *);
118
119 /*
120  * -------------------
121  * Interface functions
122  */
123
124 /*
125  * Initialize globals.
126  */
127 void
128 protocol_init(void)
129 {
130
131     proto_init_time = time(NULL);
132 }
133
134 /*
135  * Generate a request packet, and submit it to the state machine
136  * for transmission.
137  */
138 void
139 protocol_sendreq(
140     const char *                hostname,
141     const security_driver_t *   security_driver,
142     char *                      (*conf_fn)(char *, void *),
143     const char *                req,
144     time_t                      repwait,
145     protocol_sendreq_callback   continuation,
146     void *                      datap)
147 {
148     proto_t *p;
149
150     p = alloc(SIZEOF(proto_t));
151     p->state = s_sendreq;
152     p->hostname = stralloc(hostname);
153     p->security_driver = security_driver;
154     /* p->security_handle set in connect_callback */
155     p->repwait = repwait;
156     p->origtime = CURTIME;
157     /* p->curtime set in the sendreq state */
158     p->connecttries = getconf_int(CNF_CONNECT_TRIES);
159     p->resettries = RESET_TRIES;
160     p->reqtries = getconf_int(CNF_REQ_TRIES);
161     p->conf_fn = conf_fn;
162     pkt_init(&p->req, P_REQ, "%s", req);
163
164     /*
165      * These are here for the caller
166      * We call the continuation function after processing is complete.
167      * We pass the datap on through untouched.  It is here so the caller
168      * has a way to keep state with each request.
169      */
170     p->continuation = continuation;
171     p->datap = datap;
172
173     proto_debug(1, _("protocol: security_connect: host %s -> p %p\n"), 
174                     hostname, p);
175
176     security_connect(p->security_driver, p->hostname, conf_fn, connect_callback,
177                          p, p->datap);
178 }
179
180 /*
181  * This is a callback for security_connect.  After the security layer
182  * has initiated a connection to the given host, this will be called
183  * with a security_handle_t.
184  *
185  * On error, the security_status_t arg will reflect errors which can
186  * be had via security_geterror on the handle.
187  */
188 static void
189 connect_callback(
190     void *              cookie,
191     security_handle_t * security_handle,
192     security_status_t   status)
193 {
194     proto_t *p = cookie;
195
196     assert(p != NULL);
197     p->security_handle = security_handle;
198
199     proto_debug(1, _("protocol: connect_callback: p %p\n"), p);
200
201     switch (status) {
202     case S_OK:
203         state_machine(p, PA_START, NULL);
204         break;
205
206     case S_TIMEOUT:
207         security_seterror(p->security_handle, _("timeout during connect"));
208         /* FALLTHROUGH */
209
210     case S_ERROR:
211         /*
212          * For timeouts or errors, retry a few times, waiting CONNECT_WAIT
213          * seconds between each attempt.  If they all fail, just return
214          * an error back to the caller.
215          */
216         if (--p->connecttries == 0) {
217             state_machine(p, PA_ABORT, NULL);
218         } else {
219             proto_debug(1, _("protocol: connect_callback: p %p: retrying %s\n"),
220                             p, p->hostname);
221             security_close(p->security_handle);
222             /* XXX overload p->security handle to hold the event handle */
223             p->security_handle =
224                 (security_handle_t *)event_register(CONNECT_WAIT, EV_TIME,
225                 connect_wait_callback, p);
226         }
227         break;
228
229     default:
230         assert(0);
231         break;
232     }
233 }
234
235 /*
236  * This gets called when a host has been put on a wait queue because
237  * initial connection attempts failed.
238  */
239 static void
240 connect_wait_callback(
241     void *      cookie)
242 {
243     proto_t *p = cookie;
244
245     event_release((event_handle_t *)p->security_handle);
246     security_connect(p->security_driver, p->hostname, p->conf_fn,
247         connect_callback, p, p->datap);
248 }
249
250
251 /*
252  * Does a one pass protocol sweep.  Handles any incoming packets that 
253  * are waiting to be processed, and then deals with any pending
254  * requests that have timed out.
255  *
256  * Callers should periodically call this after they have submitted
257  * requests if they plan on doing a lot of work.
258  */
259 void
260 protocol_check(void)
261 {
262
263     /* arg == 1 means don't block */
264     event_loop(1);
265 }
266
267
268 /*
269  * Does an infinite pass protocol sweep.  This doesn't return until all
270  * requests have been satisfied or have timed out.
271  *
272  * Callers should call this after they have finished submitting requests
273  * and are just waiting for all of the answers to come back.
274  */
275 void
276 protocol_run(void)
277 {
278
279     /* arg == 0 means block forever until no more events are left */
280     event_loop(0);
281 }
282
283
284 /*
285  * ------------------
286  * Internal functions
287  */
288
289 /*
290  * The guts of the protocol.  This handles the many paths a request can
291  * make, including retrying the request and acknowledgements, and dealing
292  * with timeouts and successfull replies.
293  */
294 static void
295 state_machine(
296     proto_t *   p,
297     p_action_t  action,
298     pkt_t *     pkt)
299 {
300     pstate_t curstate;
301     p_action_t retaction;
302
303     proto_debug(1, _("protocol: state_machine: initial: p %p action %s pkt %p\n"),
304                     p, action2str(action), (void *)NULL);
305
306     assert(p != NULL);
307     assert(action == PA_RCVDATA || pkt == NULL);
308     assert(p->state != NULL);
309
310     for (;;) {
311         proto_debug(1, _("protocol: state_machine: p %p state %s action %s\n"),
312                         p, pstate2str(p->state), action2str(action));
313         if (pkt != NULL) {
314             proto_debug(1, _("protocol: pkt: %s (t %d) orig REQ (t %d cur %d)\n"),
315                             pkt_type2str(pkt->type), (int)CURTIME,
316                             (int)p->origtime, (int)p->curtime);
317             proto_debug(1, _("protocol: pkt contents:\n-----\n%s-----\n"),
318                             pkt->body);
319         }
320
321         /*
322          * p->state is a function pointer to the current state a request
323          * is in.
324          *
325          * We keep track of the last state we were in so we can make
326          * sure states which return PA_CONTINUE really have transitioned
327          * the request to a new state.
328          */
329         curstate = p->state;
330
331         if (action == PA_ABORT)
332             /*
333              * If the passed action indicates a terminal error, then we
334              * need to move to abort right away.
335              */
336             retaction = PA_ABORT;
337         else
338             /*
339              * Else we run the state and perform the action it
340              * requests.
341              */
342             retaction = (*curstate)(p, action, pkt);
343
344         proto_debug(1, _("protocol: state_machine: p %p state %s returned %s\n"),
345                         p, pstate2str(p->state), action2str(retaction));
346
347         /*
348          * The state function is expected to return one of the following
349          * p_action_t's.
350          */
351         switch (retaction) {
352
353         /*
354          * Request is still waiting for more data off of the network.
355          * Setup to receive another pkt, and wait for the recv event
356          * to occur.
357          */
358         case PA_CONTPEND:
359             (*p->continuation)(p->datap, pkt, p->security_handle);
360             /* FALLTHROUGH */
361
362         case PA_PENDING:
363             proto_debug(1, _("protocol: state_machine: p %p state %s: timeout %d\n"),
364                             p, pstate2str(p->state), (int)p->timeout);
365             /*
366              * Get the security layer to register a receive event for this
367              * security handle on our behalf.  Have it timeout in p->timeout
368              * seconds.
369              */
370             security_recvpkt(p->security_handle, recvpkt_callback, p,
371                 (int)p->timeout);
372
373             return;
374
375         /*
376          * Request has moved to another state.  Loop and run it again.
377          */
378         case PA_CONTINUE:
379             assert(p->state != curstate);
380             proto_debug(1, _("protocol: state_machine: p %p: moved from %s to %s\n"),
381                             p, pstate2str(curstate),
382                             pstate2str(p->state));
383             continue;
384
385         /*
386          * Request has failed in some way locally.  The security_handle will
387          * contain an appropriate error message via security_geterror().  Set
388          * pkt to NULL to indicate failure to the callback, and then
389          * fall through to the common finish code.
390          *
391          * Note that remote failures finish via PA_FINISH, because they did
392          * complete successfully locally.
393          */
394         case PA_ABORT:
395             pkt = NULL;
396             /* FALLTHROUGH */
397
398         /*
399          * Request has completed successfully.
400          * Free up resources the request has used, call the continuation
401          * function specified by the caller and quit.
402          */
403         case PA_FINISH:
404             (*p->continuation)(p->datap, pkt, p->security_handle);
405             security_close(p->security_handle);
406             amfree(p->hostname);
407             amfree(p->req.body);
408             amfree(p);
409             return;
410
411         default:
412             assert(0);
413             break;      /* in case asserts are turned off */
414         }
415         /*NOTREACHED*/
416     }
417     /*NOTREACHED*/
418 }
419
420 /*
421  * The request send state.  Here, the packet is actually transmitted
422  * across the network.  After setting up timeouts, the request
423  * moves to the acknowledgement wait state.  We return from the state
424  * machine at this point, and let the request be received from the network.
425  */
426 static p_action_t
427 s_sendreq(
428     proto_t *   p,
429     p_action_t  action,
430     pkt_t *     pkt)
431 {
432
433     assert(p != NULL);
434     (void)action;       /* Quiet unused parameter warning */
435     (void)pkt;          /* Quiet unused parameter warning */
436
437     if (security_sendpkt(p->security_handle, &p->req) < 0) {
438         /* XXX should retry */
439         security_seterror(p->security_handle, _("error sending REQ: %s"),
440             security_geterror(p->security_handle));
441         return (PA_ABORT);
442     }
443
444     /*
445      * Remember when this request was first sent
446      */
447     p->curtime = CURTIME;
448
449     /*
450      * Move to the ackwait state
451      */
452     p->state = s_ackwait;
453     p->timeout = ACK_WAIT;
454     return (PA_PENDING);
455 }
456
457 /*
458  * The acknowledge wait state.  We can enter here two ways:
459  *
460  *  - the caller has received a packet, located the request for
461  *    that packet, and called us with an action of PA_RCVDATA.
462  *    
463  *  - the caller has determined that a request has timed out,
464  *    and has called us with PA_TIMEOUT.
465  *
466  * Here we process the acknowledgment, which usually means that
467  * the client has agreed to our request and is working on it.
468  * It will later send a reply when finished.
469  */
470 static p_action_t
471 s_ackwait(
472     proto_t *   p,
473     p_action_t  action,
474     pkt_t *     pkt)
475 {
476
477     assert(p != NULL);
478
479     /*
480      * The timeout case.  If our retry count has gone to zero
481      * fail this request.  Otherwise, move to the send state
482      * to retry the request.
483      */
484     if (action == PA_TIMEOUT) {
485         assert(pkt == NULL);
486
487         if (--p->reqtries == 0) {
488             security_seterror(p->security_handle, _("timeout waiting for ACK"));
489             return (PA_ABORT);
490         }
491
492         p->state = s_sendreq;
493         return (PA_CONTINUE);
494     }
495
496     assert(action == PA_RCVDATA);
497     assert(pkt != NULL);
498
499     /*
500      * The packet-received state.  Determine what kind of
501      * packet we received, and act based on the reply type.
502      */
503     switch (pkt->type) {
504
505     /*
506      * Received an ACK.  Everything's good.  The client is
507      * now working on the request.  We queue up again and
508      * wait for the reply.
509      */
510     case P_ACK:
511         p->state = s_repwait;
512         p->timeout = p->repwait;
513         return (PA_PENDING);
514
515     /*
516      * Received a NAK.  The request failed, so free up the
517      * resources associated with it and return.
518      *
519      * This should NOT return PA_ABORT because it is not a local failure.
520      */
521     case P_NAK:
522         return (PA_FINISH);
523
524     /*
525      * The client skipped the ACK, and replied right away.
526      * Move to the reply state to handle it.
527      */
528     case P_REP:
529     case P_PREP:
530         p->state = s_repwait;
531         return (PA_CONTINUE);
532
533     /*
534      * Unexpected packet.  Requeue this request and hope
535      * we get what we want later.
536      */
537     default:
538         return (PA_PENDING);
539     }
540 }
541
542 /*
543  * The reply wait state.  We enter here much like we do with s_ackwait.
544  */
545 static p_action_t
546 s_repwait(
547     proto_t *   p,
548     p_action_t  action,
549     pkt_t *     pkt)
550 {
551     pkt_t ack;
552
553     /*
554      * Timeout waiting for a reply.
555      */
556     if (action == PA_TIMEOUT) {
557         assert(pkt == NULL);
558
559         /*
560          * If we've blown our timeout limit, free up this packet and
561          * return.
562          */
563         if (p->resettries == 0 || DROP_DEAD_TIME(p->origtime)) {
564             security_seterror(p->security_handle, _("timeout waiting for REP"));
565             return (PA_ABORT);
566         }
567
568         /*
569          * We still have some tries left.  Resend the request.
570          */
571         p->resettries--;
572         p->state = s_sendreq;
573         p->reqtries = getconf_int(CNF_REQ_TRIES);
574         return (PA_CONTINUE);
575     }
576
577     assert(action == PA_RCVDATA);
578
579     /* Finish if we get a NAK */
580     if (pkt->type == P_NAK)
581         return (PA_FINISH);
582
583     /*
584      * We've received some data.  If we didn't get a reply,
585      * requeue the packet and retry.  Otherwise, acknowledge
586      * the reply, cleanup this packet, and return.
587      */
588     if (pkt->type != P_REP && pkt->type != P_PREP)
589         return (PA_PENDING);
590
591     if(pkt->type == P_REP) {
592         pkt_init_empty(&ack, P_ACK);
593         if (security_sendpkt(p->security_handle, &ack) < 0) {
594             /* XXX should retry */
595             amfree(ack.body);
596             security_seterror(p->security_handle, _("error sending ACK: %s"),
597                 security_geterror(p->security_handle));
598             return (PA_ABORT);
599         }
600         amfree(ack.body);
601         return (PA_FINISH);
602     }
603     else if(pkt->type == P_PREP) {
604         p->timeout = p->repwait - CURTIME + p->curtime + 1;
605         return (PA_CONTPEND);
606     }
607
608     /* should never go here, shut up compiler warning */
609     return (PA_FINISH);
610 }
611
612 /*
613  * event callback that receives a packet
614  */
615 static void
616 recvpkt_callback(
617     void *              cookie,
618     pkt_t *             pkt,
619     security_status_t   status)
620 {
621     proto_t *p = cookie;
622
623     assert(p != NULL);
624
625     switch (status) {
626     case S_OK:
627         state_machine(p, PA_RCVDATA, pkt);
628         break;
629     case S_TIMEOUT:
630         state_machine(p, PA_TIMEOUT, NULL);
631         break;
632     case S_ERROR:
633         state_machine(p, PA_ABORT, NULL);
634         break;
635     default:
636         assert(0);
637         break;
638     }
639 }
640
641 /*
642  * --------------
643  * Misc functions
644  */
645
646 /*
647  * Convert a pstate_t into a printable form.
648  */
649 static const char *
650 pstate2str(
651     pstate_t    pstate)
652 {
653     static const struct {
654         pstate_t type;
655         const char name[12];
656     } pstates[] = {
657 #define X(s)    { s, stringize(s) }
658         X(s_sendreq),
659         X(s_ackwait),
660         X(s_repwait),
661 #undef X
662     };
663     int i;
664
665     for (i = 0; i < ASIZE(pstates); i++)
666         if (pstate == pstates[i].type)
667             return (pstates[i].name);
668     return (_("BOGUS PSTATE"));
669 }
670
671 /*
672  * Convert an p_action_t into a printable form
673  */
674 static const char *
675 action2str(
676     p_action_t  action)
677 {
678     static const struct {
679         p_action_t type;
680         const char name[12];
681     } actions[] = {
682 #define X(s)    { s, stringize(s) }
683         X(PA_START),
684         X(PA_TIMEOUT),
685         X(PA_ERROR),
686         X(PA_RCVDATA),
687         X(PA_CONTPEND),
688         X(PA_PENDING),
689         X(PA_CONTINUE),
690         X(PA_FINISH),
691         X(PA_ABORT),
692 #undef X
693     };
694     int i;
695
696     for (i = 0; i < ASIZE(actions); i++)
697         if (action == actions[i].type)
698             return (actions[i].name);
699     return (_("BOGUS ACTION"));
700 }