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