aa23b0bdf4079e13f0e2448d0d2cd168e6874370
[debian/amanda] / xfer-src / filter-process.c
1 /*
2  * Amanda, The Advanced Maryland Automatic Network Disk Archiver
3  * Copyright (c) 2008, 2009, 2010 Zmanda, Inc.  All Rights Reserved.
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 as published
7  * by the Free Software Foundation.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
11  * or 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 along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
17  *
18  * Contact information: Zmanda Inc., 465 S. Mathilda Ave., Suite 300
19  * Sunnyvale, CA 94085, USA, or: http://www.zmanda.com
20  */
21
22 #include "amanda.h"
23 #include "amxfer.h"
24 #include "event.h"
25 #include "util.h"
26
27 /*
28  * Class declaration
29  *
30  * This declaration is entirely private; nothing but xfer_filter_process() references
31  * it directly.
32  */
33
34 GType xfer_filter_process_get_type(void);
35 #define XFER_FILTER_PROCESS_TYPE (xfer_filter_process_get_type())
36 #define XFER_FILTER_PROCESS(obj) G_TYPE_CHECK_INSTANCE_CAST((obj), xfer_filter_process_get_type(), XferFilterProcess)
37 #define XFER_FILTER_PROCESS_CONST(obj) G_TYPE_CHECK_INSTANCE_CAST((obj), xfer_filter_process_get_type(), XferFilterProcess const)
38 #define XFER_FILTER_PROCESS_CLASS(klass) G_TYPE_CHECK_CLASS_CAST((klass), xfer_filter_process_get_type(), XferFilterProcessClass)
39 #define IS_XFER_FILTER_PROCESS(obj) G_TYPE_CHECK_INSTANCE_TYPE((obj), xfer_filter_process_get_type ())
40 #define XFER_FILTER_PROCESS_GET_CLASS(obj) G_TYPE_INSTANCE_GET_CLASS((obj), xfer_filter_process_get_type(), XferFilterProcessClass)
41
42 static GObjectClass *parent_class = NULL;
43
44 /*
45  * Main object structure
46  */
47
48 typedef struct XferFilterProcess {
49     XferElement __parent__;
50
51     gchar **argv;
52     gboolean need_root;
53     int pipe_err[2];
54
55     pid_t child_pid;
56     GSource *child_watch;
57     gboolean child_killed;
58 } XferFilterProcess;
59
60 /*
61  * Class definition
62  */
63
64 typedef struct {
65     XferElementClass __parent__;
66     int (*get_err_fd)(XferFilterProcess *elt);
67
68 } XferFilterProcessClass;
69
70 /*
71  * Implementation
72  */
73
74 static void
75 child_watch_callback(
76     pid_t pid,
77     gint status,
78     gpointer data)
79 {
80     XferFilterProcess *self = XFER_FILTER_PROCESS(data);
81     XferElement *elt = (XferElement *)self;
82     XMsg *msg;
83     char *errmsg = NULL;
84
85     g_assert(pid == self->child_pid);
86     self->child_pid = -1; /* it's gone now.. */
87
88     if (WIFEXITED(status)) {
89         int exitcode = WEXITSTATUS(status);
90         g_debug("%s: process exited with status %d", xfer_element_repr(elt), exitcode);
91         if (exitcode != 0) {
92             errmsg = g_strdup_printf("%s exited with status %d",
93                 self->argv[0], exitcode);
94         }
95     } else if (WIFSIGNALED(status)) {
96         int signal = WTERMSIG(status);
97         if (signal != SIGKILL || !self->child_killed) {
98             errmsg = g_strdup_printf("%s died on signal %d", self->argv[0], signal);
99             g_debug("%s: %s", xfer_element_repr(elt), errmsg);
100         }
101     }
102
103     /* if this is an error exit, send an XMSG_ERROR and cancel */
104     if (errmsg) {
105         msg = xmsg_new(XFER_ELEMENT(self), XMSG_ERROR, 0);
106         msg->message = errmsg;
107         xfer_queue_message(XFER_ELEMENT(self)->xfer, msg);
108
109         xfer_cancel(elt->xfer);
110
111         /* this element is as good as cancelled already, so fall through to XMSG_DONE */
112     }
113
114     xfer_queue_message(XFER_ELEMENT(self)->xfer, xmsg_new(XFER_ELEMENT(self), XMSG_DONE, 0));
115 }
116
117 static int
118 get_err_fd_impl(
119     XferFilterProcess *xfp)
120 {
121     return xfp->pipe_err[0];
122 }
123
124 static gboolean
125 start_impl(
126     XferElement *elt)
127 {
128     XferFilterProcess *self = (XferFilterProcess *)elt;
129     char *cmd_str;
130     char **argv;
131     char *errmsg;
132     char **env;
133     int rfd, wfd;
134
135     /* first build up a log message of what we're going to do, properly shell quoted */
136     argv = self->argv;
137     cmd_str = g_shell_quote(*(argv++));
138     while (*argv) {
139         char *qarg = g_shell_quote(*(argv++));
140         cmd_str = newvstralloc(cmd_str, cmd_str, " ", qarg, NULL);
141         g_free(qarg);
142     }
143     g_debug("%s spawning: %s", xfer_element_repr(elt), cmd_str);
144
145     rfd = xfer_element_swap_output_fd(elt->upstream, -1);
146     wfd = xfer_element_swap_input_fd(elt->downstream, -1);
147
148     /* now fork off the child and connect the pipes */
149     switch (self->child_pid = fork()) {
150         case -1:
151             error("cannot fork: %s", strerror(errno));
152             /* NOTREACHED */
153
154         case 0: /* child */
155             /* first, copy our fd's out of the stdio range */
156             while (rfd <= STDERR_FILENO)
157                 rfd = dup(rfd);
158             while (wfd <= STDERR_FILENO)
159                 wfd = dup(wfd);
160
161             /* set up stdin, stdout, and stderr, overwriting anything already open
162              * on those fd's */
163             dup2(rfd, STDIN_FILENO);
164             dup2(wfd, STDOUT_FILENO);
165             dup2(self->pipe_err[1], STDERR_FILENO);
166
167             /* and close everything else */
168             safe_fd(-1, 0);
169             env = safe_env();
170
171             if (self->need_root && !become_root()) {
172                 errmsg = g_strdup_printf("could not become root: %s\n", strerror(errno));
173                 full_write(STDERR_FILENO, errmsg, strlen(errmsg));
174                 exit(1);
175             }
176
177             execve(self->argv[0], self->argv, env);
178             errmsg = g_strdup_printf("exec failed: %s\n", strerror(errno));
179             full_write(STDERR_FILENO, errmsg, strlen(errmsg));
180             exit(1);
181
182         default: /* parent */
183             break;
184     }
185     g_free(cmd_str);
186
187     /* close the pipe fd's */
188     close(rfd);
189     close(wfd);
190     close(self->pipe_err[1]);
191
192     /* watch for child death */
193     self->child_watch = new_child_watch_source(self->child_pid);
194     g_source_set_callback(self->child_watch,
195             (GSourceFunc)child_watch_callback, self, NULL);
196     g_source_attach(self->child_watch, NULL);
197     g_source_unref(self->child_watch);
198
199     return TRUE;
200 }
201
202 static gboolean
203 cancel_impl(
204     XferElement *elt,
205     gboolean expect_eof)
206 {
207     XferFilterProcess *self = (XferFilterProcess *)elt;
208
209     /* chain up first */
210     XFER_ELEMENT_CLASS(parent_class)->cancel(elt, expect_eof);
211
212     /* if the process is running as root, we can't do anything but wait until
213      * we get an upstream EOF, or downstream does something to trigger a
214      * SIGPIPE */
215     if (self->need_root)
216         return expect_eof;
217
218     /* avoid the risk of SIGPIPEs by not killing the process if it is already
219      * expecting an EOF */
220     if (expect_eof) {
221         return expect_eof;
222     }
223
224     /* and kill the process, if it's not already dead; this will likely send
225      * SIGPIPE to anything upstream. */
226     if (self->child_pid != -1) {
227         g_debug("%s: killing child process", xfer_element_repr(elt));
228         if (kill(self->child_pid, SIGKILL) < 0) {
229             /* log but ignore */
230             g_debug("while killing child process: %s", strerror(errno));
231             return FALSE; /* downstream should not expect EOF */
232         }
233
234         /* make sure we don't send an XMSG_ERROR about this */
235         self->child_killed = 1;
236     }
237
238     return TRUE; /* downstream should expect an EOF */
239 }
240
241 static void
242 instance_init(
243     XferElement *elt)
244 {
245     XferFilterProcess *self = (XferFilterProcess *)elt;
246
247     /* we can generate an EOF *unless* the process is running as root */
248     elt->can_generate_eof = !self->need_root;
249
250     self->argv = NULL;
251     self->child_pid = -1;
252     self->child_killed = FALSE;
253 }
254
255 static void
256 finalize_impl(
257     GObject * obj_self)
258 {
259     XferFilterProcess *self = XFER_FILTER_PROCESS(obj_self);
260
261     if (self->argv)
262         g_strfreev(self->argv);
263
264     /* chain up */
265     G_OBJECT_CLASS(parent_class)->finalize(obj_self);
266 }
267
268 static void
269 class_init(
270     XferFilterProcessClass * selfc)
271 {
272     XferElementClass *klass = XFER_ELEMENT_CLASS(selfc);
273     GObjectClass *goc = (GObjectClass*) klass;
274     static xfer_element_mech_pair_t mech_pairs[] = {
275         { XFER_MECH_READFD, XFER_MECH_WRITEFD, XFER_NROPS(1), XFER_NTHREADS(0) },
276         { XFER_MECH_NONE, XFER_MECH_NONE, XFER_NROPS(0), XFER_NTHREADS(0) },
277     };
278
279     klass->start = start_impl;
280     klass->cancel = cancel_impl;
281
282     klass->perl_class = "Amanda::Xfer::Filter::Process";
283     klass->mech_pairs = mech_pairs;
284     selfc->get_err_fd = get_err_fd_impl;
285
286     goc->finalize = finalize_impl;
287
288     parent_class = g_type_class_peek_parent(selfc);
289 }
290
291 GType
292 xfer_filter_process_get_type (void)
293 {
294     static GType type = 0;
295
296     if G_UNLIKELY(type == 0) {
297         static const GTypeInfo info = {
298             sizeof (XferFilterProcessClass),
299             (GBaseInitFunc) NULL,
300             (GBaseFinalizeFunc) NULL,
301             (GClassInitFunc) class_init,
302             (GClassFinalizeFunc) NULL,
303             NULL /* class_data */,
304             sizeof (XferFilterProcess),
305             0 /* n_preallocs */,
306             (GInstanceInitFunc) instance_init,
307             NULL
308         };
309
310         type = g_type_register_static (XFER_ELEMENT_TYPE, "XferFilterProcess", &info, 0);
311     }
312
313     return type;
314 }
315
316 /* create an element of this class; prototype is in xfer-element.h */
317 XferElement *
318 xfer_filter_process(
319     gchar **argv,
320     gboolean need_root)
321 {
322     XferFilterProcess *xfp = (XferFilterProcess *)g_object_new(XFER_FILTER_PROCESS_TYPE, NULL);
323     XferElement *elt = XFER_ELEMENT(xfp);
324
325     if (!argv || !*argv)
326         error("xfer_filter_process got a NULL or empty argv");
327
328     xfp->argv = argv;
329     xfp->need_root = need_root;
330     if (pipe(xfp->pipe_err) < 0) {
331         g_critical(_("Can't create pipe: %s"), strerror(errno));
332     }
333     return elt;
334 }
335
336 int get_err_fd(XferElement *elt);
337 int get_err_fd(
338     XferElement *elt)
339 {
340     XferFilterProcessClass *klass;
341     g_assert(IS_XFER_FILTER_PROCESS(elt));
342
343     klass = XFER_FILTER_PROCESS_GET_CLASS(elt);
344     if (klass->get_err_fd)
345         return klass->get_err_fd(XFER_FILTER_PROCESS(elt));
346     else
347         return 0;
348 }