Imported Upstream version 2.6.0p2
[debian/amanda] / restore-src / amidxtaped.c
1 /*
2  * Amanda, The Advanced Maryland Automatic Network Disk Archiver
3  * Copyright (c) 1991-1998 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 /* $Id: amidxtaped.c,v 1.73 2006/07/25 19:06:46 martinea Exp $
27  *
28  * This daemon extracts a dump image off a tape for amrecover and
29  * returns it over the network. It basically, reads a number of
30  * arguments from stdin (it is invoked via inet), one per line,
31  * preceeded by the number of them, and forms them into an argv
32  * structure, then execs amrestore
33  */
34
35 #include "amanda.h"
36 #include "version.h"
37 #include "clock.h"
38 #include "restore.h"
39 #include "cmdline.h"
40
41 #include "changer.h"
42 #include "conffile.h"
43 #include "logfile.h"
44 #include "amfeatures.h"
45 #include "stream.h"
46 #include "amandad.h"
47
48 #define amidxtaped_debug(i,x) do {      \
49         if ((i) <= debug_amidxtaped) {  \
50             dbprintf(x);                \
51         }                               \
52 } while (0)
53
54 #define TIMEOUT 30
55
56 static char *pgm = "amidxtaped";        /* in case argv[0] is not set */
57
58 extern char *rst_conf_logfile;
59
60 static int get_lock = 0;
61 static int from_amandad;
62
63 static am_feature_t *our_features = NULL;
64 static am_feature_t *their_features = NULL;
65 static g_option_t *g_options = NULL;
66 static int ctlfdin, ctlfdout, datafdout;
67 static char *amandad_auth = NULL;
68 static FILE *cmdin, *cmdout;
69
70 static char *get_client_line(FILE *in);
71 static void check_security_buffer(char *);
72 static char *get_client_line_fd(int);
73
74 /* exit routine */
75 static pid_t parent_pid = -1;
76 static void cleanup(void);
77
78 int main(int argc, char **argv);
79
80 /* get a line from client - line terminated by \r\n */
81 static char *
82 get_client_line(FILE *in)
83 {
84     static char *line = NULL;
85     char *part = NULL;
86     size_t len;
87
88     amfree(line);
89     while(1) {
90         if((part = agets(in)) == NULL) {
91             if(errno != 0) {
92                 dbprintf(_("read error: %s\n"), strerror(errno));
93             } else {
94                 dbprintf(_("EOF reached\n"));
95             }
96             if(line) {
97                 dbprintf(_("s: unprocessed input:\n"));
98                 dbprintf("-----\n");
99                 dbprintf("%s\n", line);
100                 dbprintf("-----\n");
101             }
102             amfree(line);
103             amfree(part);
104             dbclose();
105             exit(1);
106             /*NOTREACHED*/
107         }
108         if(line) {
109             strappend(line, part);
110             amfree(part);
111         } else {
112             line = part;
113             part = NULL;
114         }
115         if((len = strlen(line)) > 0 && line[len-1] == '\r') {
116             line[len-1] = '\0';         /* zap the '\r' */
117             break;
118         }
119         /*
120          * Hmmm.  We got a "line" from agets(), which means it saw
121          * a '\n' (or EOF, etc), but there was not a '\r' before it.
122          * Put a '\n' back in the buffer and loop for more.
123          */
124         strappend(line, "\n");
125     }
126     dbprintf("> %s\n", line);
127     return line;
128 }
129
130 /* get a line from client - line terminated by \r\n */
131 static char *
132 get_client_line_fd(
133     int         fd)
134 {
135     static char *line = NULL;
136     static size_t line_size = 0;
137     char *s = line;
138     size_t len = 0;
139     char c;
140     ssize_t nb;
141
142     if(line == NULL) { /* first time only, allocate initial buffer */
143         s = line = alloc(128);
144         line_size = 128;
145     }
146     while(1) {
147         nb = read(fd, &c, 1);
148         if (nb <= 0) {
149             /* EOF or error */
150             if ((nb <= 0) && ((errno == EINTR) || (errno == EAGAIN))) {
151                 /* Keep looping if failure is temporary */
152                 continue;
153             }
154             dbprintf(_("%s: Control pipe read error - %s\n"),
155                       pgm, strerror(errno));
156             break;
157         }
158
159         if(len >= line_size-1) { /* increase buffer size */
160             line_size *= 2;
161             line = realloc(line, line_size);
162             if (line == NULL) {
163                 error(_("Memory reallocation failure"));
164                 /*NOTREACHED*/
165             }
166             s = &line[len];
167         }
168         *s = c;
169         if(c == '\n') {
170             if(len > 0 && *(s-1) == '\r') { /* remove '\r' */
171                 s--;
172                 len--;
173             }
174             *s = '\0';
175             return line;
176         }
177         s++;
178         len++;
179     }
180     line[len] = '\0';
181     return line;
182 }
183
184
185 void
186 check_security_buffer(
187     char *      buffer)
188 {
189     socklen_t_equiv i;
190     struct sockaddr_in addr;
191     char *s, *fp, ch;
192     char *errstr = NULL;
193
194     dbprintf(_("check_security_buffer(buffer='%s')\n"), buffer);
195
196     i = SIZEOF(addr);
197     if (getpeername(0, (struct sockaddr *)&addr, &i) == -1) {
198         error(_("getpeername: %s"), strerror(errno));
199         /*NOTREACHED*/
200     }
201     if ((addr.sin_family != (sa_family_t)AF_INET)
202                 || (ntohs(addr.sin_port) == 20)) {
203         error(_("connection rejected from %s family %d port %d"),
204              inet_ntoa(addr.sin_addr), addr.sin_family, htons(addr.sin_port));
205         /*NOTREACHED*/
206     }
207
208     /* do the security thing */
209     s = buffer;
210     ch = *s++;
211
212     skip_whitespace(s, ch);
213     if (ch == '\0') {
214         error(_("cannot parse SECURITY line"));
215         /*NOTREACHED*/
216     }
217     fp = s-1;
218     skip_non_whitespace(s, ch);
219     s[-1] = '\0';
220     if (strcmp(fp, "SECURITY") != 0) {
221         error(_("cannot parse SECURITY line"));
222         /*NOTREACHED*/
223     }
224     skip_whitespace(s, ch);
225     if (!check_security((sockaddr_union *)&addr, s-1, 0, &errstr)) {
226         error(_("security check failed: %s"), errstr);
227         /*NOTREACHED*/
228     }
229 }
230
231 int
232 main(
233     int         argc,
234     char **     argv)
235 {
236     char *buf = NULL;
237     int data_sock = -1;
238     in_port_t data_port = (in_port_t)-1;
239     socklen_t_equiv socklen;
240     struct sockaddr_in addr;
241     GSList *dumpspecs;
242     tapelist_t *tapes = NULL;
243     char *their_feature_string = NULL;
244     rst_flags_t *rst_flags;
245     int use_changer = 0;
246     int re_end;
247     char *re_config = NULL;
248     char *conf_tapetype;
249     tapetype_t *tape;
250     char *line;
251     char *tapedev;
252     dumpspec_t *ds;
253
254     /*
255      * Configure program for internationalization:
256      *   1) Only set the message locale for now.
257      *   2) Set textdomain for all amanda related programs to "amanda"
258      *      We don't want to be forced to support dozens of message catalogs.
259      */  
260     setlocale(LC_MESSAGES, "C");
261     textdomain("amanda"); 
262
263     safe_fd(DATA_FD_OFFSET, 4);
264     safe_cd();
265
266     /* Don't die when child closes pipe */
267     signal(SIGPIPE, SIG_IGN);
268
269     rst_flags = new_rst_flags();
270     rst_flags->mask_splits = 1; /* for older clients */
271     rst_flags->amidxtaped = 1;
272     our_features = am_init_feature_set();
273     their_features = am_set_default_feature_set();
274
275     /*
276      * When called via inetd, it is not uncommon to forget to put the
277      * argv[0] value on the config line.  On some systems (e.g. Solaris)
278      * this causes argv and/or argv[0] to be NULL, so we have to be
279      * careful getting our name.
280      */
281     if (argc >= 1 && argv != NULL && argv[0] != NULL) {
282         if((pgm = strrchr(argv[0], '/')) != NULL) {
283             pgm++;
284         } else {
285             pgm = argv[0];
286         }
287     }
288
289     set_pname(pgm);
290
291     if(argv && argv[1] && strcmp(argv[1], "amandad") == 0) {
292         from_amandad = 1;
293         if(argv[2])
294             amandad_auth = argv[2];
295     }
296     else {
297         from_amandad = 0;
298         safe_fd(-1, 0);
299     }
300
301     /* initialize */
302     /* close stderr first so that debug file becomes it - amrestore
303        chats to stderr, which we don't want going to client */
304     /* if no debug file, ship to bit bucket */
305     (void)close(STDERR_FILENO);
306     dbopen(DBG_SUBDIR_SERVER);
307     startclock();
308     dbprintf(_("%s: version %s\n"), pgm, version());
309     debug_dup_stderr_to_debug();
310
311     if (! (argc >= 1 && argv != NULL && argv[0] != NULL)) {
312         dbprintf(_("WARNING: argv[0] not defined: check inetd.conf\n"));
313     }
314
315     if(from_amandad == 0) {
316         socklen = SIZEOF(addr);
317         if (getpeername(0, (struct sockaddr *)&addr, &socklen) == -1) {
318             error(_("getpeername: %s"), strerror(errno));
319             /*NOTREACHED*/
320         }
321         if ((addr.sin_family != (sa_family_t)AF_INET)
322                 || (ntohs(addr.sin_port) == 20)) {
323             error(_("connection rejected from %s family %d port %d"),
324                   inet_ntoa(addr.sin_addr), addr.sin_family,
325                   htons(addr.sin_port));
326             /*NOTREACHED*/
327         }
328
329         /* do the security thing */
330         amfree(buf);
331         fflush(stdout);
332         cmdout = stdout;
333         cmdin  = stdin;
334         buf = stralloc(get_client_line(cmdin));
335         check_security_buffer(buf);
336     }
337     else {
338         ctlfdout  = DATA_FD_OFFSET + 0;
339         ctlfdin   = DATA_FD_OFFSET + 1;
340         datafdout = DATA_FD_OFFSET + 2;
341         close(DATA_FD_OFFSET +3);
342
343         /* read the REQ packet */
344         for(; (line = agets(stdin)) != NULL; free(line)) {
345             if(strncmp_const(line, "OPTIONS ") == 0) {
346                 g_options = parse_g_options(line+8, 1);
347                 if(!g_options->hostname) {
348                     g_options->hostname = alloc(MAX_HOSTNAME_LENGTH+1);
349                     gethostname(g_options->hostname, MAX_HOSTNAME_LENGTH);
350                     g_options->hostname[MAX_HOSTNAME_LENGTH] = '\0';
351                 }
352             }
353         }
354         amfree(line);
355
356         if(amandad_auth && g_options->auth) {
357             if(strcasecmp(amandad_auth, g_options->auth) != 0) {
358                 g_printf(_("ERROR recover program ask for auth=%s while amidxtaped is configured for '%s'\n"),
359                        g_options->auth, amandad_auth);
360                 error(_("ERROR recover program ask for auth=%s while amidxtaped is configured for '%s'"),
361                       g_options->auth, amandad_auth);
362                 /*NOTREACHED*/
363             }
364         }
365         /* send the REP packet */
366         g_printf("CONNECT CTL %d DATA %d\n", DATA_FD_OFFSET, DATA_FD_OFFSET+1);
367         g_printf("\n");
368         fflush(stdout);
369         fclose(stdin);
370         fclose(stdout);
371         cmdout = fdopen(ctlfdout, "a");
372         if (!cmdout) {
373             error(_("amidxtaped: Can't fdopen(ctlfdout): %s"), strerror(errno));
374             /*NOTREACHED*/
375         }
376         cmdin = fdopen(ctlfdin, "r");
377         if (!cmdin) {
378             error(_("amidxtaped: Can't fdopen(ctlfdin): %s"), strerror(errno));
379             /*NOTREACHED*/
380         }
381     }
382
383     ds = dumpspec_new(NULL, NULL, NULL, NULL);
384     for (re_end = 0; re_end == 0; ) {
385         char *s, ch;
386         amfree(buf);
387         buf = stralloc(get_client_line(cmdin));
388         s = buf;
389         if(strncmp_const_skip(buf, "LABEL=", s, ch) == 0) {
390             tapes = unmarshal_tapelist_str(s);
391         }
392         else if(strncmp_const_skip(buf, "FSF=", s, ch) == 0) {
393             rst_flags->fsf = OFF_T_ATOI(s);
394         }
395         else if(strncmp_const_skip(buf, "HEADER", s, ch) == 0) {
396             rst_flags->headers = 1;
397         }
398         else if(strncmp_const_skip(buf, "FEATURES=", s, ch) == 0) {
399             char *our_feature_string = NULL;
400             their_feature_string = stralloc(s);
401             am_release_feature_set(their_features);
402             their_features = am_string_to_feature(their_feature_string);
403             amfree(their_feature_string);
404             our_feature_string = am_feature_to_string(our_features);
405             if(from_amandad == 1) 
406                 g_fprintf(cmdout,"FEATURES=%s\r\n", our_feature_string);
407             else
408                 g_fprintf(cmdout,"%s", our_feature_string);
409             fflush(cmdout);
410             amfree(our_feature_string);
411         }
412         else if(strncmp_const_skip(buf, "DEVICE=", s, ch) == 0) {
413             rst_flags->alt_tapedev= stralloc(s);
414         }
415         else if(strncmp_const_skip(buf, "HOST=", s, ch) == 0) {
416             ds->host = stralloc(s);
417         }
418         else if(strncmp_const_skip(buf, "DISK=", s, ch) == 0) {
419             ds->disk = stralloc(s);
420         }
421         else if(strncmp_const_skip(buf, "DATESTAMP=", s, ch) == 0) {
422             ds->datestamp = stralloc(s);
423         }
424         else if(strncmp_const(buf, "END") == 0) {
425             re_end = 1;
426         }
427         else if(strncmp_const_skip(buf, "CONFIG=", s, ch) == 0) {
428             re_config = stralloc(s);
429             if(strlen(re_config) == 0)
430                 amfree(re_config);
431         }
432         else if(buf[0] != '\0' && buf[0] >= '0' && buf[0] <= '9') {
433             re_end = 1;
434         }
435     }
436     amfree(buf);
437
438     if(re_config) {
439         config_init(CONFIG_INIT_EXPLICIT_NAME | CONFIG_INIT_FATAL, re_config);
440         dbrename(re_config, DBG_SUBDIR_SERVER);
441     } else {
442         config_init(0, NULL);
443     }
444
445     check_running_as(RUNNING_AS_DUMPUSER_PREFERRED);
446
447     if(tapes &&
448        (!rst_flags->alt_tapedev  ||
449         (re_config && ( strcmp(rst_flags->alt_tapedev,
450                                getconf_str(CNF_AMRECOVER_CHANGER)) == 0 ||
451                         strcmp(rst_flags->alt_tapedev,
452                                getconf_str(CNF_TPCHANGER)) == 0 ) ) ) ) {
453         /* We need certain options, if restoring from more than one tape */
454         if(tapes->next && !am_has_feature(their_features, fe_recover_splits)) {
455             error(_("Client must support split dumps to restore requested data."));
456             /*NOTREACHED*/
457         }
458         dbprintf(_("Restoring from changer, checking labels\n"));
459         rst_flags->check_labels = 1;
460         use_changer = 1;
461     }
462
463     /* build the dumpspec list from our single dumpspec */
464     dumpspecs = g_slist_append(NULL, (gpointer)ds);
465     ds = NULL;
466
467     if(!tapes && rst_flags->alt_tapedev){
468         sleep(10);
469         dbprintf(_("Looks like we're restoring from a holding file...\n"));
470         tapes = unmarshal_tapelist_str(rst_flags->alt_tapedev);
471         tapes->isafile = 1;
472         amfree(rst_flags->alt_tapedev);
473         rst_flags->alt_tapedev = NULL;
474         use_changer = FALSE;
475     } 
476
477     tapedev = getconf_str(CNF_TAPEDEV);
478     /* If we'll be stepping on the tape server's devices, lock them. */
479     if(re_config &&
480        (use_changer || (rst_flags->alt_tapedev && tapedev &&
481                         strcmp(rst_flags->alt_tapedev, tapedev) == 0) ) ) {
482         dbprintf(_("Locking devices\n"));
483         parent_pid = getpid();
484         atexit(cleanup);
485         get_lock = lock_logfile();
486     }
487
488     /* Init the tape changer */
489     if(tapes && use_changer && changer_init() == 0) {
490         dbprintf(_("No changer available\n"));
491     }
492
493     /* Read the default block size from the tape type */
494     if(re_config && (conf_tapetype = getconf_str(CNF_TAPETYPE)) != NULL) {
495         tape = lookup_tapetype(conf_tapetype);
496         rst_flags->blocksize = tapetype_get_blocksize(tape) * 1024;
497     }
498
499     if(rst_flags->fsf && re_config &&
500        getconf_boolean(CNF_AMRECOVER_DO_FSF) == 0) {
501         rst_flags->fsf = (off_t)0;
502     }
503
504     if (!use_changer && re_config &&
505         getconf_boolean(CNF_AMRECOVER_CHECK_LABEL) == 0) {
506         rst_flags->check_labels = 0;
507     }
508
509     /* establish a distinct data connection for dumpfile data */
510     if(am_has_feature(their_features, fe_recover_splits)) {
511         if(from_amandad == 1) {
512             rst_flags->pipe_to_fd = datafdout;
513         }
514         else {
515             int data_fd;
516             char *buf;
517
518             dbprintf(_("Client understands split dumpfiles\n"));
519
520             if((data_sock = stream_server(AF_INET, &data_port, STREAM_BUFSIZE, 
521                  STREAM_BUFSIZE, 0)) < 0){
522                 error(_("could not create data socket: %s"), strerror(errno));
523                 /*NOTREACHED*/
524             }
525             dbprintf(_("Local port %d set aside for data\n"), data_port);
526
527             /* tell client where to connect */
528             g_printf(_("CONNECT %hu\n"), (unsigned short)data_port);
529             fflush(stdout);
530
531             if((data_fd = stream_accept(data_sock, TIMEOUT, STREAM_BUFSIZE, 
532                  STREAM_BUFSIZE)) < 0){
533                 error(_("stream_accept failed for client data connection: %s\n"),
534                       strerror(errno));
535                 /*NOTREACHED*/
536             }
537
538             buf = get_client_line_fd(data_fd);
539
540             check_security_buffer(buf);
541             rst_flags->pipe_to_fd = data_fd;
542         }
543     }
544     else {
545         rst_flags->pipe_to_fd = fileno(stdout);
546         cmdout = stderr;
547     }
548     dbprintf(_("Sending output to file descriptor %d\n"), rst_flags->pipe_to_fd);
549
550
551     tapedev = getconf_str(CNF_TAPEDEV);
552     if(get_lock == 0 &&
553        re_config && 
554        (use_changer || (rst_flags->alt_tapedev && tapedev &&
555                         strcmp(rst_flags->alt_tapedev, tapedev) == 0) ) ) {
556         send_message(cmdout, rst_flags, their_features,
557                      _("%s exists: amdump or amflush is already running, "
558                      "or you must run amcleanup"), 
559                      rst_conf_logfile);
560         error(_("%s exists: amdump or amflush is already running, "
561               "or you must run amcleanup"),
562               rst_conf_logfile);
563     }
564
565     /* make sure our restore flags aren't crazy */
566     if (check_rst_flags(rst_flags) == -1) {
567         if (rst_flags->pipe_to_fd != -1)
568             aclose(rst_flags->pipe_to_fd);
569         send_message(cmdout, rst_flags, their_features,
570                      _("restore flags are crazy"));
571         exit(1);
572     }
573
574     /* actual restoration */
575     search_tapes(cmdout, cmdin, use_changer, tapes, dumpspecs, rst_flags,
576                  their_features);
577     dbprintf(_("Restoration finished\n"));
578
579     /* cleanup */
580     if(rst_flags->pipe_to_fd != -1) aclose(rst_flags->pipe_to_fd);
581     free_tapelist(tapes);
582
583     am_release_feature_set(their_features);
584
585     amfree(rst_flags->alt_tapedev);
586     amfree(rst_flags);
587     dumpspec_list_free(dumpspecs);
588     amfree(re_config);
589     dbclose();
590     return 0;
591 }
592
593 static void
594 cleanup(void)
595 {
596     if(parent_pid == getpid()) {
597         if(get_lock) unlink(rst_conf_logfile);
598     }
599 }