9af2f3ae78b5f2200ebed57c8e00de4be137f1a9
[captive.git] / src / libcaptive / sandbox / split.c
1 /* $Id$
2  * Connection of captive-vfs interface through CORBA/ORBit
3  * Copyright (C) 2002 Jan Kratochvil <project-captive@jankratochvil.net>
4  * 
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; exactly version 2 of June 1991 is required
8  * 
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17  */
18
19
20 #include "config.h"
21
22 #include "split.h"      /* self */
23 #include "sandbox.h"
24 #include "server-GLogFunc.h"
25 #include "captive/macros.h"
26 #include <glib/gmacros.h>
27 #include <stdlib.h>
28 #include "captive/rtl-file.h"
29 #include <unistd.h>
30 #include <fcntl.h>
31 #include "server-Directory.h"
32 #include "server-Vfs.h"
33 #include "../client/vfs.h"
34 #include "parent-Vfs.h"
35 #include <dirent.h>
36 #include "server-CaptiveIOChannel.h"
37 #include <errno.h>
38 #include "../client/giochannel-blind.h" /* for captive_giochannel_blind_new() */
39 #include <signal.h>
40
41 #ifdef HAVE_ORBIT_LINK
42 void link_set_tmpdir(const char *dir);
43 #else
44 #include <linc/linc.h>  /* for linc_main_get_loop() */
45 #endif
46
47
48 /* CONFIG: */
49
50 #define HEARTBEAT_SOURCE_CHECK_EVENTS (G_IO_IN|G_IO_PRI)
51 #define HEARTBEAT_SOURCE_CHECK_REVENTS (HEARTBEAT_SOURCE_CHECK_EVENTS|G_IO_ERR|G_IO_HUP|G_IO_NVAL)
52
53
54 gboolean validate_CORBA_Environment(CORBA_Environment *evp)
55 {
56         if (evp->_major==CORBA_NO_EXCEPTION)
57                 return TRUE;
58
59         g_error(_("CORBA Exception occured: id=\"%s\", value=%p"),
60                         CORBA_exception_id(evp),CORBA_exception_value(evp));
61         CORBA_exception_free(evp);
62         return FALSE;
63 }
64
65 CORBA_Environment captive_corba_ev;
66 CORBA_ORB captive_corba_orb;
67 PortableServer_POA captive_corba_poa;
68
69 static void corba_shutdown_atexit(void);
70
71 static gboolean corba_init(const char *pname,CORBA_Environment *evp,CORBA_ORB *orbp,PortableServer_POA *poap)
72 {
73 static gboolean done=FALSE;
74 int orb_argc=1;
75 gchar *orb_argv[]={
76                 (gchar *)captive_strdup_alloca(pname),
77                 NULL};
78
79         g_return_val_if_fail(evp!=NULL,FALSE);
80         g_return_val_if_fail(orbp!=NULL,FALSE);
81         g_return_val_if_fail(poap!=NULL,FALSE);
82
83         if (done)
84                 return TRUE;    /* FIXME: '*poap' is left invalid! */
85
86         /* Init 'ev' */
87         CORBA_exception_init(evp);
88
89         /* Init 'orb' */
90         *orbp=CORBA_ORB_init(&orb_argc,orb_argv,"orbit-local-orb",evp);
91         g_return_val_if_fail(*orbp!=CORBA_OBJECT_NIL,FALSE);
92         g_return_val_if_fail(validate_CORBA_Environment(evp),FALSE);
93
94         /* Init 'poa' */
95         *poap=(PortableServer_POA)CORBA_ORB_resolve_initial_references(*orbp,"RootPOA",evp);
96         g_return_val_if_fail(validate_CORBA_Environment(evp),FALSE);
97         {
98 PortableServer_POAManager poa_mgr;
99                 poa_mgr=PortableServer_POA__get_the_POAManager(*poap,evp);
100                 g_return_val_if_fail(validate_CORBA_Environment(evp),FALSE);
101                 PortableServer_POAManager_activate(poa_mgr,evp);
102                 g_return_val_if_fail(validate_CORBA_Environment(evp),FALSE);
103                 CORBA_Object_release((CORBA_Object)poa_mgr,evp);
104                 g_return_val_if_fail(validate_CORBA_Environment(evp),FALSE);
105                 }
106
107         g_atexit(corba_shutdown_atexit);
108
109         done=TRUE;
110         return TRUE;
111 }
112
113
114 static CORBA_ORB heartbeat_source_callback_orb=CORBA_OBJECT_NIL;
115
116 gboolean corba_shutdown(CORBA_Environment *evp,CORBA_ORB *orbp,PortableServer_POA *poap)
117 {
118 PortableServer_POA poa;
119 CORBA_ORB orb;
120
121         g_return_val_if_fail(evp!=NULL,FALSE);
122         g_return_val_if_fail(orbp!=NULL,FALSE);
123         g_return_val_if_fail(poap!=NULL,FALSE);
124
125         /* Shutdown 'poa' */
126         poa=*poap;
127         *poap=CORBA_OBJECT_NIL;
128         CORBA_Object_release((CORBA_Object)poa,evp);
129         g_return_val_if_fail(validate_CORBA_Environment(evp),FALSE);
130
131         /* Shutdown 'orb' */
132         orb=*orbp;
133         *orbp=CORBA_OBJECT_NIL;
134         heartbeat_source_callback_orb=CORBA_OBJECT_NIL;
135         CORBA_ORB_destroy(orb,evp);
136         /* Do not: g_return_val_if_fail(validate_CORBA_Environment(evp),FALSE);
137          * here as CORBA_ORB_destroy() sometimes reports:
138          *      WARNING **: ORB: a total of X refs to X ORB objects were leaked
139          */
140         CORBA_exception_free(evp);
141
142         /* Shutdown 'ev' */
143         CORBA_exception_free(evp);
144
145         return TRUE;
146 }
147
148 static void sandbox_parent_own_orbit_dir_cleanup_atexit(void);
149
150 static void corba_shutdown_atexit(void)
151 {
152 gboolean errbool;
153
154         errbool=corba_shutdown(&captive_corba_ev,&captive_corba_orb,&captive_corba_poa);
155         g_assert(errbool==TRUE);
156
157         /* Delete the CORBA ORB socket directory only after full CORBA ORB shutdown. */
158         sandbox_parent_own_orbit_dir_cleanup_atexit();
159 }
160
161
162 static GSource *captive_corba_sandbox_child_heartbeat_gsource;
163
164 #if 0   /* Currently unused - see server-Vfs.c:impl_Captive_Vfs_shutdown() */
165 void sandbox_child_prepare_shutdown(void)
166 {
167         /* Prevent during shutdown: Captive-WARNING **: CORBA Exception occured: id="IDL:omg.org/CORBA/COMM_FAILURE:1.0" */
168         if (captive_corba_sandbox_child_heartbeat_gsource) {
169                 g_source_destroy(captive_corba_sandbox_child_heartbeat_gsource);
170                 g_source_unref(captive_corba_sandbox_child_heartbeat_gsource);
171                 captive_corba_sandbox_child_heartbeat_gsource=NULL;
172                 }
173 }
174 #endif
175
176 GMainLoop *captive_corba_get_loop(void)
177 {
178 #ifdef HAVE_ORBIT_LINK
179 static GMainLoop *link_loop;
180
181         if (!link_loop)
182                 link_loop=g_main_loop_new(g_main_context_default(),TRUE);
183         return link_loop;
184 #else
185         return linc_main_get_loop();
186 #endif
187 }
188
189 GMainContext *captive_corba_get_context(void)
190 {
191         return g_main_loop_get_context(captive_corba_get_loop());
192 }
193
194 void sandbox_child_shutdown(void)
195 {
196         /* Do not fail by passing logging messages to the master. */
197         impl_Captive_Vfs_init_g_log_func_disable();
198
199         g_main_loop_quit(captive_corba_get_loop());
200 }
201
202
203 static gboolean heartbeat_source_callback(gpointer data /* unused */)
204 {
205         g_return_val_if_fail(heartbeat_source_callback_orb!=CORBA_OBJECT_NIL,FALSE);    /* the source should be removed */
206
207         sandbox_child_shutdown();
208
209         return FALSE;   /* the source should be removed */
210 }
211
212
213 static gboolean heartbeat_source_prepare(GSource *source,gint *timeout)
214 {
215         *timeout=-1;
216
217         return FALSE;
218 }
219
220 static GPollFD heartbeat_source_check_gpollfd;
221
222 static gboolean heartbeat_source_check(GSource *source)
223 {
224         return !!(heartbeat_source_check_gpollfd.revents & HEARTBEAT_SOURCE_CHECK_REVENTS);
225 }
226
227 static gboolean heartbeat_source_dispatch(GSource *source,GSourceFunc callback,gpointer user_data)
228 {
229         g_assert(callback!=NULL);
230         return (*callback)(user_data);
231 }
232
233 static GSourceFuncs heartbeat_source_watch_funcs={
234                 heartbeat_source_prepare,
235                 heartbeat_source_check,
236                 heartbeat_source_dispatch,
237                 NULL,   /* finalize */
238                 };
239
240 void captive_corba_sandbox_child(const gchar *chrooted_orbit_dir)
241 {
242 Captive_Vfs Vfs_object;
243 impl_POA_Captive_Vfs *Vfs_servant;
244 gboolean errbool;
245 guint errguint;
246 int errint;
247
248         /* attach heartbeat_source_callback() to watch for any abnormalities
249          * on our open pipe 'parentheart_fds' and terminate the child if parent dies.
250          */
251         captive_corba_sandbox_child_heartbeat_gsource=g_source_new(&heartbeat_source_watch_funcs,sizeof(GSource));
252         g_return_if_fail(captive_corba_sandbox_child_heartbeat_gsource!=NULL);
253         g_source_set_callback(
254                         captive_corba_sandbox_child_heartbeat_gsource,  /* source */
255                         heartbeat_source_callback,      /* func */
256                         NULL,   /* data */
257                         NULL);  /* notify */
258         heartbeat_source_check_gpollfd.fd=0 /* STDIN */;        /* parentheart_fd_read */
259         heartbeat_source_check_gpollfd.events=HEARTBEAT_SOURCE_CHECK_EVENTS;
260         heartbeat_source_check_gpollfd.revents=0;
261         g_source_add_poll(captive_corba_sandbox_child_heartbeat_gsource,&heartbeat_source_check_gpollfd);
262
263         errbool=corba_init("captive-sandbox-child",&captive_corba_ev,&captive_corba_orb,&captive_corba_poa);
264         g_return_if_fail(errbool==TRUE);
265
266         heartbeat_source_callback_orb=captive_corba_orb;
267
268         /* captive_corba_get_context() makes sense only after corba_init() -> CORBA_ORB_init() */
269         errguint=g_source_attach(
270                         captive_corba_sandbox_child_heartbeat_gsource,  /* source */
271                         captive_corba_get_context());   /* context; NULL means 'default context' */
272         g_assert(errguint!=0);
273
274         /* Init 'Vfs_object' */
275         Vfs_object=impl_Captive_Vfs__create(captive_corba_poa,&captive_corba_ev);
276         g_assert(validate_CORBA_Environment(&captive_corba_ev));
277
278         /* Pass IOR to our parent.
279          * It will also create the socket needed for 'chrooted_orbit_dir' below
280          * by CORBA_ORB_object_to_string()->ORBit_marshal_object()->IOP_generate_profiles()->ORBit_ORB_start_servers...
281          */
282         {
283 char *Vfs_IOR;
284                 Vfs_IOR=CORBA_ORB_object_to_string(captive_corba_orb,Vfs_object,&captive_corba_ev);
285                 g_assert(validate_CORBA_Environment(&captive_corba_ev));
286                 g_assert(Vfs_IOR!=NULL);
287                 errint=printf("ior=%s\n",Vfs_IOR);
288                 g_assert(errint>=0);
289                 CORBA_free(Vfs_IOR);
290                 }
291
292         /* Default mode is 0700, permit parent non-"captive" users to access our IOR socket. */
293         if (chrooted_orbit_dir) {
294 DIR *dir;
295 struct dirent *dirent;
296 const gchar *socketname=NULL,*socketpathname;
297
298                 errint=chmod(chrooted_orbit_dir,0755);
299                 g_assert(errint==0);
300
301                 dir=opendir(chrooted_orbit_dir);
302                 g_assert(dir!=NULL);
303                 while (errno=0,(dirent=readdir(dir))) {
304                         if (!strcmp(dirent->d_name,".") || !strcmp(dirent->d_name,".."))
305                                 continue;
306                         g_assert(socketname==NULL);
307                         socketname=captive_strdup_alloca(dirent->d_name);
308                         }
309                 g_assert(errno==0);
310                 errint=closedir(dir);
311                 g_assert(errint==0);
312                 g_assert(socketname!=NULL);
313
314                 socketpathname=captive_printf_alloca("%s/%s",chrooted_orbit_dir,socketname);
315                 errint=chmod(socketpathname,0666);
316                 g_assert(errint==0);
317
318                 printf("socketname=%s\n",socketname);
319                 }
320
321         /* Close the output to flush it to our spawning parent. */
322         errint=fflush(stdout);
323         g_assert(errint==0);
324         errint=fclose(stdout);
325         g_assert(errint==0);
326
327         /* CORBA_ORB_run() -> linc_main_loop_run() -> g_main_loop_run()
328          * and therefore we should be safe with glib events handling.
329          */
330 #ifdef HAVE_ORBIT_LINK
331         g_main_loop_run(captive_corba_get_loop());
332 #else
333         CORBA_ORB_run(captive_corba_orb,&captive_corba_ev);
334         g_assert(validate_CORBA_Environment(&captive_corba_ev));
335 #endif
336
337         /* Shutdown 'Vfs' servant */
338         Vfs_servant=PortableServer_POA_reference_to_servant(captive_corba_poa,Vfs_object,&captive_corba_ev);
339         g_assert(validate_CORBA_Environment(&captive_corba_ev));
340         CORBA_Object_release(Vfs_object,&captive_corba_ev);
341         g_assert(validate_CORBA_Environment(&captive_corba_ev));
342         impl_Captive_Vfs__destroy(Vfs_servant,&captive_corba_ev);
343         g_assert(validate_CORBA_Environment(&captive_corba_ev));
344
345         errbool=corba_shutdown(&captive_corba_ev,&captive_corba_orb,&captive_corba_poa);
346         g_assert(errbool==TRUE);
347
348         _exit(EXIT_SUCCESS);
349 }
350
351
352 static void options_module_captive_to_options_module_corba
353                 (Captive_CaptiveOptionsModule *dest_options_module_corba,const struct captive_options_module *src_options_module_captive)
354 {
355         g_return_if_fail(dest_options_module_corba!=NULL);
356         g_return_if_fail(src_options_module_captive!=NULL);
357
358         g_return_if_fail(src_options_module_captive->type==CAPTIVE_OPTIONS_MODULE_TYPE_PE32);
359
360         dest_options_module_corba->pathname_utf8=CORBA_string_dup(src_options_module_captive->pathname_utf8);
361         dest_options_module_corba->data._maximum=src_options_module_captive->u.pe32.length;
362         dest_options_module_corba->data._length =src_options_module_captive->u.pe32.length;
363         dest_options_module_corba->data._buffer=Captive_Bytes_allocbuf(dest_options_module_corba->data._maximum);
364         memcpy(dest_options_module_corba->data._buffer,src_options_module_captive->u.pe32.base,
365                         src_options_module_captive->u.pe32.length);
366         dest_options_module_corba->data._release=TRUE;
367 }
368
369 static void unlink_nonrecursive(const gchar *dirname)
370 {
371 DIR *dir;
372 struct dirent *dirent;
373 int errint;
374
375         dir=opendir(dirname);
376         g_assert(dir!=NULL);
377
378         while (errno=0,(dirent=readdir(dir))) {
379 gchar *pathname;
380
381                 if (!strcmp(dirent->d_name,".") || !strcmp(dirent->d_name,".."))
382                         continue;
383                 pathname=g_strdup_printf("%s/%s",dirname,dirent->d_name);
384                 errint=unlink(pathname);
385                 g_assert(errint==0);
386                 g_free(pathname);
387                 }
388         g_assert(errno==0);
389         errint=closedir(dir);
390         g_assert(errint==0);
391         errint=rmdir(dirname);
392         g_assert(errint==0);
393 }
394
395 static const gchar *sandbox_parent_own_orbit_dir;
396 static const gchar *sandbox_parent_own_orbit_socket;
397
398 static void sandbox_parent_own_orbit_dir_cleanup_atexit(void)
399 {
400 static gboolean done=FALSE;
401
402         g_log(G_LOG_DOMAIN,G_LOG_LEVEL_DEBUG,"%s; done=%d",G_STRLOC,(int)done);
403
404         if (done)
405                 return;
406         done=TRUE;
407
408         if (sandbox_parent_own_orbit_dir)
409                 unlink_nonrecursive(sandbox_parent_own_orbit_dir);
410 }
411
412 static struct sandbox_parent_own_orbit_dir_cleanup_signal {
413         int signum;
414         /* FIXME: Why we cannot use 'sighandler_t'? */ void (*sighandler_orig)(int signum);
415         } sandbox_parent_own_orbit_dir_cleanup_signals[]={
416                 { SIGINT  },
417                 { SIGQUIT },
418                 { SIGTERM },
419                 { SIGHUP  },
420                 { SIGABRT },
421                 { SIGFPE  },
422                 };
423
424 static void sandbox_parent_own_orbit_dir_cleanup_sighandler(int signum)
425 {
426 struct sandbox_parent_own_orbit_dir_cleanup_signal *sigstructp;
427
428         for (
429                         sigstructp=sandbox_parent_own_orbit_dir_cleanup_signals;
430                         sigstructp<sandbox_parent_own_orbit_dir_cleanup_signals+G_N_ELEMENTS(sandbox_parent_own_orbit_dir_cleanup_signals);
431                         sigstructp++) {
432                 if (sigstructp->signum==signum)
433                         break;
434                 }
435         g_assert(sigstructp<sandbox_parent_own_orbit_dir_cleanup_signals+G_N_ELEMENTS(sandbox_parent_own_orbit_dir_cleanup_signals));
436         signal(signum,sigstructp->sighandler_orig);
437
438         /* Prevent recursive fatal logging before signal restore: */
439         /* Do not: g_log(G_LOG_DOMAIN,G_LOG_LEVEL_DEBUG,"%s: signum=%d,sighandler_orig=%p",G_STRLOC,signum,sigstructp->sighandler_orig);
440          * as it is dangerous to g_log() from sighandler.
441          */
442
443         sandbox_parent_own_orbit_dir_cleanup_atexit();
444
445         /* Do not: g_log(G_LOG_DOMAIN,G_LOG_LEVEL_DEBUG,"%s: re-raising...",G_STRLOC);
446          * as it is dangerous to g_log() from sighandler.
447          */
448         raise(signum);
449 }
450
451 static void sandbox_parent_own_orbit_dir_cleanup_init(void)
452 {
453 struct sandbox_parent_own_orbit_dir_cleanup_signal *sigstructp;
454
455         for (
456                         sigstructp=sandbox_parent_own_orbit_dir_cleanup_signals;
457                         sigstructp<sandbox_parent_own_orbit_dir_cleanup_signals+G_N_ELEMENTS(sandbox_parent_own_orbit_dir_cleanup_signals);
458                         sigstructp++) {
459                 sigstructp->sighandler_orig=signal(sigstructp->signum,sandbox_parent_own_orbit_dir_cleanup_sighandler);
460                 if (sigstructp->sighandler_orig==SIG_IGN)
461                         sigstructp->sighandler_orig=SIG_DFL;
462                 }
463 }
464
465 static gchar *sandbox_parent_read_ior
466                 (int Vfs_IOR_fd_read,gchar **child_chroot_pid_hashkey_dirp,CaptiveVfsParentObject *captive_vfs_parent_object)
467 {
468 gchar *data;
469 gsize data_size;
470 GHashTable *hash;
471 gchar *ior,*child_chroot_pid_hashkey_dir;
472 int errint;
473 gchar *s,*sd,*se;
474 gboolean errbool;
475
476         /* Initialize /tmp/orbit-$username directory for linking IOR socket. */
477         errbool=corba_init("captive-sandbox-parent",&captive_corba_ev,&captive_corba_orb,&captive_corba_poa);
478         g_assert(errbool==TRUE);
479
480         /* FIXME: Security: Duplicate giop_tmpdir_init() here. */
481         if (!sandbox_parent_own_orbit_dir) {
482                 /* FIXME: Make 'CAPTIVE_SANDBOX_CHROOT' configurable. */
483                 sandbox_parent_own_orbit_dir=g_strdup_printf("%s/tmp/captive-orbit-%d",CAPTIVE_SANDBOX_CHROOT,getpid());
484                 if (mkdir(sandbox_parent_own_orbit_dir,0700)) {
485                         g_assert(errno==EEXIST);
486                         sandbox_parent_own_orbit_dir_cleanup_init();
487                         unlink_nonrecursive(sandbox_parent_own_orbit_dir);
488                         if (mkdir(sandbox_parent_own_orbit_dir,0700))
489                                 g_assert_not_reached();
490                         }
491                 sandbox_parent_own_orbit_dir_cleanup_init();
492 #ifdef HAVE_ORBIT_LINK
493                 link_set_tmpdir(sandbox_parent_own_orbit_dir);
494 #else
495                 linc_set_tmpdir(sandbox_parent_own_orbit_dir);
496 #endif
497                 }
498
499         data=captive_rtl_file_read(Vfs_IOR_fd_read,&data_size); /* data_fd_read */
500         errint=close(Vfs_IOR_fd_read);
501         g_assert(errint==0);
502         g_assert(data!=NULL);
503         g_assert(data_size>=1);
504         g_assert(data[data_size-1]=='\n');
505
506         hash=g_hash_table_new(g_str_hash,g_str_equal);
507
508         for (s=data;s<data+data_size;s=se+1) {
509                 se=strchr(s,'\n');
510                 g_assert(se!=NULL);
511                 *se=0;
512                 sd=strchr(s,'=');
513                 g_assert(sd!=NULL);
514                 *sd=0;
515                 g_hash_table_insert(hash,s,sd+1);
516                 }
517         g_assert(s==data+data_size);
518
519         if ((child_chroot_pid_hashkey_dir=g_hash_table_lookup(hash,"chroot_pid_hashkey_dir"))) {
520 const gchar *socketname,*socketpathname_src,*socketpathname_dest;
521 const gchar *chrooted_orbit_dir;
522
523                 /* IOR contains the full pathname with the setuid username encoded. */
524                 chrooted_orbit_dir=g_hash_table_lookup(hash,"chrooted_orbit_dir");
525                 g_assert(chrooted_orbit_dir!=NULL);
526                 captive_vfs_parent_object->corba_chrooted_orbit_dir=g_strdup(chrooted_orbit_dir);
527                 /* 0700 as this directory will not be reused
528                  * to commuicate with any other sandbox child.
529                  */
530                 if (mkdir(chrooted_orbit_dir,0700)) {
531                         g_assert(errno==EEXIST);
532                         }
533
534                 socketname=g_hash_table_lookup(hash,"socketname");
535                 g_assert(socketname!=NULL);
536                 captive_vfs_parent_object->corba_socketname=g_strdup(socketname);
537
538                 socketpathname_src=captive_printf_alloca("%s/%s/%s",child_chroot_pid_hashkey_dir,chrooted_orbit_dir,socketname);
539                 socketpathname_dest=g_strdup_printf("%s/%s",chrooted_orbit_dir,socketname);
540                 errint=link(socketpathname_src,socketpathname_dest);
541                 if (errint)
542                         g_error("link(\"%s\",\"%s\")=%d:%m",socketpathname_src,socketpathname_dest,errint);
543                 }
544         if (child_chroot_pid_hashkey_dirp)
545                 *child_chroot_pid_hashkey_dirp=g_strdup(child_chroot_pid_hashkey_dir);
546
547         ior=g_hash_table_lookup(hash,"ior");
548         g_assert(ior!=NULL);
549         ior=g_strdup(ior);
550         g_free(data);
551
552         g_hash_table_destroy(hash);
553
554         return ior;
555 }
556
557
558 static xmlNode *options_module_captive_to_xml
559                 (xmlNode *dest_xml_parent,const struct captive_options_module *src_options_module_captive)
560 {
561         g_return_val_if_fail(dest_xml_parent!=NULL,NULL);
562         g_return_val_if_fail(src_options_module_captive!=NULL,NULL);
563
564         { xmlNode *module=xmlNewTextChild(dest_xml_parent,NULL,"module",NULL);
565         const gchar *type_string="???"; /* Prevent: ... might be used uninitialized in this function */
566         const gchar *basename,*cgs;
567
568                 basename=src_options_module_captive->pathname_utf8;
569                 if ((cgs=strrchr(basename,'/')))
570                         basename=cgs+1;
571                 xmlNewProp(module,"basename",basename);
572                 switch (src_options_module_captive->type) {
573                         case CAPTIVE_OPTIONS_MODULE_TYPE_PE32:
574                                 type_string="PE32";
575                                 xmlNewProp(module,"length",captive_printf_alloca("%lu",(unsigned long)src_options_module_captive->u.pe32.length));
576                                 xmlNewProp(module,"md5"   ,src_options_module_captive->u.pe32.md5);
577                                 break;
578                         case CAPTIVE_OPTIONS_MODULE_TYPE_GMODULE:
579                                 type_string="gmodule";
580                                 break;
581                         default: g_assert_not_reached();
582                         }
583                 xmlNewProp(module,"type",type_string);  /* AFTER the 'switch' to set 'type_string'! */
584                 return module;
585                 }
586 }
587
588
589 static void sandbox_parent_bug_doc_make(CaptiveVfsParentObject *captive_vfs_parent_object)
590 {
591         { xmlDoc *doc=xmlNewDoc("1.0");
592                 captive_vfs_parent_object->corba_bug_doc=doc;
593                 { xmlNode *bug=xmlNewDocNode(captive_vfs_parent_object->corba_bug_doc,NULL,"bug",NULL);
594                         xmlDocSetRootElement(captive_vfs_parent_object->corba_bug_doc,bug);
595                         captive_vfs_parent_object->corba_bug=bug;
596                         { xmlNode *bug_captive=xmlNewTextChild(bug,NULL,"captive",NULL);
597                                 xmlNewProp(bug_captive,"version",VERSION);
598                                 }
599                         { xmlNode *bug_filesystem=xmlNewTextChild(bug,NULL,"filesystem",NULL);
600                                 options_module_captive_to_xml(bug_filesystem,&CAPTIVE_VFS_OBJECT(captive_vfs_parent_object)->options.filesystem);
601                                 }
602                         { xmlNode *bug_load_module=xmlNewTextChild(bug,NULL,"load_module",NULL);
603                         guint load_moduleui;
604                         struct captive_options_module *options_module;
605                         GList *load_module_node;
606
607                                 for (load_moduleui=0,load_module_node=CAPTIVE_VFS_OBJECT(captive_vfs_parent_object)->options.load_module;
608                                                 load_module_node;
609                                                 load_moduleui++,load_module_node=load_module_node->next) {
610                                         options_module=load_module_node->data;
611                                         options_module_captive_to_xml(bug_load_module,options_module);
612                                         }
613                                 }
614                         { xmlNode *bug_action=xmlNewTextChild(bug,NULL,"action",NULL);
615                                 captive_vfs_parent_object->corba_bug_action=bug_action;
616                                 }
617                         { xmlNode *bug_log=xmlNewTextChild(bug,NULL,"log",NULL);
618                                 captive_vfs_parent_object->corba_bug_log=bug_log;
619                                 }
620                         }
621                 }
622 }
623
624
625 static void sandbox_parent(const gchar *Vfs_IOR,const gchar *child_chroot_pid_hashkey_dir,CaptiveVfsParentObject *captive_vfs_parent_object)
626 {
627 Captive_Vfs Vfs_object;
628 Captive_GLogFunc GLogFunc_object;
629 Captive_CaptiveIOChannel CaptiveIOChannel_object;
630 Captive_CaptiveOptions options_corba;
631 guint load_module_length,load_moduleui;
632 struct captive_options_module *options_module;
633 GList *load_module_node;
634 const gchar *child_chroot_parent_own_orbit_socket,*child_chroot_parent_own_orbit_dir;
635 int errint;
636
637         g_return_if_fail(Vfs_IOR!=NULL);
638         /* 'child_chroot_pid_hashkey_dir' may be NULL */
639         g_return_if_fail(CAPTIVE_VFS_PARENT_IS_OBJECT(captive_vfs_parent_object));
640
641         Vfs_object=CORBA_ORB_string_to_object(captive_corba_orb,Vfs_IOR,&captive_corba_ev);
642         g_assert(validate_CORBA_Environment(&captive_corba_ev));
643
644         /* Init 'GLogFunc_object' */
645         GLogFunc_object=impl_Captive_GLogFunc__create(captive_corba_poa,captive_vfs_parent_object,&captive_corba_ev);
646         g_assert(validate_CORBA_Environment(&captive_corba_ev));
647
648         /* Init 'CaptiveIOChannel_object' */
649         if (!captive_vfs_parent_object->corba_parent_giochanel_blind_source)
650                 switch (CAPTIVE_VFS_OBJECT(captive_vfs_parent_object)->options.rwmode) {
651                         case CAPTIVE_OPTION_RWMODE_RO:
652                         case CAPTIVE_OPTION_RWMODE_RW:
653                                 captive_vfs_parent_object->corba_parent_giochanel_blind_source=CAPTIVE_VFS_OBJECT(captive_vfs_parent_object)->options.image_iochannel;
654                                 break;
655                         case CAPTIVE_OPTION_RWMODE_BLIND:
656                                 captive_vfs_parent_object->corba_parent_giochanel_blind_source=(GIOChannel *)captive_giochannel_blind_new(
657                                                 CAPTIVE_VFS_OBJECT(captive_vfs_parent_object)->options.image_iochannel, /* giochannel_orig */
658                                                 TRUE); /* writeable */
659                                 break;
660                         default: g_assert_not_reached();
661                         }
662         if (!captive_vfs_parent_object->corba_parent_giochanel_blind)
663                 captive_vfs_parent_object->corba_parent_giochanel_blind=(GIOChannel *)captive_giochannel_blind_new(
664                                 captive_vfs_parent_object->corba_parent_giochanel_blind_source,  /* giochannel_orig */
665                                 (CAPTIVE_VFS_OBJECT(captive_vfs_parent_object)->options.rwmode!=CAPTIVE_OPTION_RWMODE_RO)); /* writeable */
666         CaptiveIOChannel_object=impl_Captive_CaptiveIOChannel__create(captive_corba_poa,
667                         captive_vfs_parent_object->corba_parent_giochanel_blind,&captive_corba_ev);
668         g_assert(validate_CORBA_Environment(&captive_corba_ev));
669
670         /* Create the socket needed for 'sandbox_parent_own_orbit_socket' below
671          * by CORBA_ORB_object_to_string()->ORBit_marshal_object()->IOP_generate_profiles()->ORBit_ORB_start_servers...
672          */
673         {
674 char *GLogFunc_IOR;
675                 GLogFunc_IOR=CORBA_ORB_object_to_string(captive_corba_orb,GLogFunc_object,&captive_corba_ev);
676                 g_assert(validate_CORBA_Environment(&captive_corba_ev));
677                 g_assert(GLogFunc_IOR!=NULL);
678                 CORBA_free(GLogFunc_IOR);
679                 }
680
681         if (sandbox_parent_own_orbit_dir && !sandbox_parent_own_orbit_socket) {
682 DIR *dir;
683 struct dirent *dirent;
684
685                 dir=opendir(sandbox_parent_own_orbit_dir);
686                 g_assert(dir!=NULL);
687
688                 while (errno=0,(dirent=readdir(dir))) {
689                         if (!strcmp(dirent->d_name,".") || !strcmp(dirent->d_name,".."))
690                                 continue;
691                         g_assert(sandbox_parent_own_orbit_socket==NULL);
692                         sandbox_parent_own_orbit_socket=g_strdup_printf("%s/%s",sandbox_parent_own_orbit_dir,dirent->d_name);
693                         }
694                 g_assert(errno==0);
695                 errint=closedir(dir);
696                 g_assert(errint==0);
697                 g_assert(sandbox_parent_own_orbit_socket!=NULL);
698                 }
699
700         if (child_chroot_pid_hashkey_dir) {
701 gchar *s;
702
703                 child_chroot_parent_own_orbit_dir=captive_printf_alloca("%s/%s",child_chroot_pid_hashkey_dir,sandbox_parent_own_orbit_dir);
704                 s=(/* de-const */ gchar *)child_chroot_parent_own_orbit_dir;
705                 do {
706                         s=strchr(s,'/');
707                         if (s)
708                                 *s=0;
709                         if (*child_chroot_parent_own_orbit_dir) {
710                                 errint=mkdir(child_chroot_parent_own_orbit_dir,0777);
711                                 if (errint)
712                                         g_assert(errno==EEXIST);
713                                 else {
714                                         /* chmod(2) it to prevent mode limitation by
715                                          * active ulimit(2) of being executed by mount(8).
716                                          */
717                                         errint=chmod(child_chroot_parent_own_orbit_dir,0777);
718                                         g_assert(errint==0);
719                                         }
720                                 }
721                         if (s)
722                                 *s++='/';
723                         } while (s);
724                 child_chroot_parent_own_orbit_socket=captive_printf_alloca("%s/%s",
725                                 child_chroot_pid_hashkey_dir,sandbox_parent_own_orbit_socket);
726                 errint=link(sandbox_parent_own_orbit_socket,child_chroot_parent_own_orbit_socket);
727                 g_assert(errint==0);
728                 /* chmod(2)s also our orig. one (!) but this one is protected by its 0777 directory. */
729                 errint=chmod(child_chroot_parent_own_orbit_socket,0666);
730                 g_assert(errint==0);
731                 }
732
733         options_corba.g_log_func=CORBA_Object_duplicate(GLogFunc_object,&captive_corba_ev);
734         g_assert(validate_CORBA_Environment(&captive_corba_ev));
735
736         options_module_captive_to_options_module_corba(&options_corba.filesystem,&CAPTIVE_VFS_OBJECT(captive_vfs_parent_object)->options.filesystem);
737         /* Prevent secondary captive_giochannel_blind inside of our sandbox child
738          * as we already have one captive_giochannel_blind in the parent.
739          */
740         options_corba.rwmode        =(CAPTIVE_VFS_OBJECT(captive_vfs_parent_object)->options.rwmode == CAPTIVE_OPTION_RWMODE_BLIND ? CAPTIVE_OPTION_RWMODE_RW
741                         : CAPTIVE_VFS_OBJECT(captive_vfs_parent_object)->options.rwmode);
742         options_corba.media         =CAPTIVE_VFS_OBJECT(captive_vfs_parent_object)->options.media;
743         options_corba.debug_messages=CAPTIVE_VFS_OBJECT(captive_vfs_parent_object)->options.debug_messages;
744
745         options_corba.image_iochannel=CORBA_Object_duplicate(CaptiveIOChannel_object,&captive_corba_ev);
746         g_assert(validate_CORBA_Environment(&captive_corba_ev));
747
748         load_module_length=g_list_length(CAPTIVE_VFS_OBJECT(captive_vfs_parent_object)->options.load_module);
749         options_corba.load_module._maximum=load_module_length;
750         options_corba.load_module._length=load_module_length;
751         options_corba.load_module._buffer=Captive_CaptiveOptionsModuleList_allocbuf(options_corba.load_module._maximum);
752         options_corba.load_module._release=TRUE;
753         for (load_moduleui=0,load_module_node=CAPTIVE_VFS_OBJECT(captive_vfs_parent_object)->options.load_module;
754                         load_module_node;
755                         load_moduleui++,load_module_node=load_module_node->next) {
756                 options_module=load_module_node->data;
757                 options_module_captive_to_options_module_corba(options_corba.load_module._buffer+load_moduleui,options_module);
758                 }
759
760         Captive_Vfs_init(Vfs_object,&options_corba,&captive_corba_ev);
761         g_assert(validate_CORBA_Environment(&captive_corba_ev));
762
763         Captive_CaptiveOptions__freekids(&options_corba,
764                         NULL);  /* d; unused */
765
766         captive_vfs_parent_object->corba_Vfs_object=Vfs_object;
767         captive_vfs_parent_object->corba_GLogFunc_object=GLogFunc_object;
768         captive_vfs_parent_object->corba_CaptiveIOChannel_object=CaptiveIOChannel_object;
769
770         if (CAPTIVE_VFS_OBJECT(captive_vfs_parent_object)->options.bug_pathname)
771                 sandbox_parent_bug_doc_make(captive_vfs_parent_object);
772 }
773
774 static void fd_shiftup(int *fdp)
775 {
776         g_return_if_fail(fdp!=NULL);
777
778         while (*fdp<=2 /* STDERR */) {
779                 *fdp=dup(*fdp);
780                 g_assert(*fdp!=-1);
781                 }
782 }
783
784 void captive_sandbox_fd_closeup(int fd_first_to_delete)
785 {
786 DIR *dir;
787 int errint;
788 int dir_fd;
789 struct dirent *dirent;
790
791         dir=opendir("/proc/self/fd/");
792         g_return_if_fail(dir!=NULL);
793         dir_fd=dirfd(dir);
794         g_return_if_fail(dir_fd!=-1);
795
796         while (errno=0,(dirent=readdir(dir))) {
797 long dirent_fd;
798 char *endptr;
799
800                 if (0
801                                 || !strcmp(dirent->d_name,".")
802                                 || !strcmp(dirent->d_name,".."))
803                         continue;
804                 dirent_fd=strtol(dirent->d_name,&endptr,10 /* base */);
805                 g_assert(dirent_fd>=0 && (!endptr || !*endptr));
806                 if (dirent_fd<fd_first_to_delete || dirent_fd==dir_fd)
807                         continue;
808
809                 errint=close(dirent_fd);
810                 g_assert(errint==0);
811                 errno=0;
812                 errint=close(dirent_fd);
813                 g_assert(errint==-1); g_assert(errno==EBADF);
814                 }
815         g_return_if_fail(errno==0);     /* check for EOF */
816
817         errint=closedir(dir);
818         g_return_if_fail(errint==0);
819         errno=0;
820         close(dir_fd); g_assert(errno==EBADF);  /* just a bit of paranoia; it should be already closed by closedir() */
821 }
822
823 gboolean captive_sandbox_spawn(CaptiveVfsParentObject *captive_vfs_parent_object)
824 {
825 /* Vfs_IOR_fds[0] for reading by sandbox_parent() - client,
826  * Vfs_IOR_fds[1] for writing by sandbox_child()  - server
827  */
828 int Vfs_IOR_fds[2],parentheart_fds[2];
829 int errint;
830 gboolean errbool;
831
832         g_return_val_if_fail(CAPTIVE_VFS_PARENT_IS_OBJECT(captive_vfs_parent_object),FALSE);
833
834         errint=pipe(Vfs_IOR_fds);
835         g_return_val_if_fail(errint==0,FALSE);
836         errint=pipe(parentheart_fds);
837         g_return_val_if_fail(errint==0,FALSE);
838
839         /* Currently never called anywhere:
840          *     errbool=corba_shutdown(&captive_corba_ev,&captive_corba_orb,&captive_corba_poa);
841          *     g_assert(errbool==TRUE);
842          */
843
844         if (CAPTIVE_VFS_OBJECT(captive_vfs_parent_object)->options.sandbox_server_ior) {
845                 g_assert(CAPTIVE_VFS_OBJECT(captive_vfs_parent_object)->options.sandbox_server_argv==NULL);
846
847                 errbool=corba_init("captive-sandbox-parent",&captive_corba_ev,&captive_corba_orb,&captive_corba_poa);
848                 g_assert(errbool==TRUE);
849
850                 captive_vfs_parent_object->corba_parentheart_fds_1=-1;
851                 captive_vfs_parent_object->corba_child_pid=-1;
852                 sandbox_parent(
853                                 CAPTIVE_VFS_OBJECT(captive_vfs_parent_object)->options.sandbox_server_ior,      /* Vfs_IOR */
854                                 NULL,   /* child_chroot_pid_hashkey_dir */
855                                 captive_vfs_parent_object);     /* captive_vfs_parent_object */
856                 return TRUE;
857                 }
858
859         g_assert(CAPTIVE_VFS_OBJECT(captive_vfs_parent_object)->options.sandbox_server_argv!=NULL);
860         switch ((captive_vfs_parent_object->corba_child_pid=fork())) {
861                 case -1:        /* error */
862                         g_return_val_if_reached(FALSE);
863
864                 case 0: { /* child */
865
866                         errint=close(Vfs_IOR_fds[0]);   /* close Vfs_IOR_fd_read */
867                         g_return_val_if_fail(errint==0,FALSE);
868                         errint=close(parentheart_fds[1]);       /* close parentheart_fd_write */
869                         g_return_val_if_fail(errint==0,FALSE);
870
871                         fd_shiftup(Vfs_IOR_fds+1);      /* Vfs_IOR_fd_write */
872                         fd_shiftup(parentheart_fds+0);  /* parentheart_fd_read */
873                         errint=dup2(Vfs_IOR_fds[1],1 /* STDOUT */);     /* Vfs_IOR_fd_write */
874                         g_return_val_if_fail(errint==1 /* STDOUT */,FALSE);
875                         errint=dup2(parentheart_fds[0],0 /* STDIN */);  /* parentheart_fd_read */
876                         g_return_val_if_fail(errint==0 /* STDIN */,FALSE);
877
878                         captive_sandbox_fd_closeup(2 /* STDERR */ +1);
879
880                         execv(CAPTIVE_VFS_OBJECT(captive_vfs_parent_object)->options.sandbox_server_argv[0],
881                                         /* re-const */ (char * const *)CAPTIVE_VFS_OBJECT(captive_vfs_parent_object)->options.sandbox_server_argv);
882                         g_return_val_if_reached(FALSE);
883                         } /* NOTREACHED */
884
885                 default: {      /* parent */
886 gchar *Vfs_IOR;
887 gchar *child_chroot_pid_hashkey_dir;
888
889                         errint=close(Vfs_IOR_fds[1]);   /* close Vfs_IOR_fd_write */
890                         g_return_val_if_fail(errint==0,FALSE);
891                         errint=close(parentheart_fds[0]);       /* close parentheart_fd_read */
892                         g_return_val_if_fail(errint==0,FALSE);
893                         errint=fcntl(parentheart_fds[1],F_SETFD,FD_CLOEXEC);
894                         /* This fcntl(2) may not be enough - some fork(2) may duplicate this
895                          * write descriptor and even if we do some process finish the child
896                          * may remain alone connected with some unknown fork(2)er from us.
897                          * Currently I am not aware such case would occur.
898                          */
899                         g_return_val_if_fail(errint==0,FALSE);
900                         captive_vfs_parent_object->corba_parentheart_fds_1=parentheart_fds[1];
901
902                         Vfs_IOR=sandbox_parent_read_ior(
903                                         Vfs_IOR_fds[0], /* Vfs_IOR_fd_read */
904                                         &child_chroot_pid_hashkey_dir,
905                                         captive_vfs_parent_object);
906
907                         sandbox_parent(
908                                         Vfs_IOR,        /* Vfs_IOR */
909                                         child_chroot_pid_hashkey_dir,   /* child_chroot_pid_hashkey_dir */
910                                         captive_vfs_parent_object);     /* captive_vfs_parent_object */
911
912                         g_free(Vfs_IOR);
913                         g_free(child_chroot_pid_hashkey_dir);
914
915                         /* 'parentheart_fds[1]' - parentheart_fd_write - is left open here */
916                         return TRUE;
917                         }
918                 }
919         /* NOTREACHED */
920         g_return_val_if_reached(FALSE);
921 }
922
923
924 GnomeVFSResult captive_sandbox_parent_return_from_CORBA_Environment
925                 (CORBA_Environment *evp,CaptiveVfsParentObject *captive_vfs_parent_object)
926 {
927 GnomeVFSResult r;
928
929         if (evp->_major==CORBA_NO_EXCEPTION)
930                 return GNOME_VFS_OK;
931
932         /* If !CAPTIVE_VFS_OBJECT(captive_vfs_parent_object)->options.sandbox_server_argv it is CAPTIVE_VFS_OBJECT(captive_vfs_parent_object)->options.sandbox_server_ior
933          * where we cannot do any restart anyway.
934          */
935         if (captive_vfs_parent_object && CAPTIVE_VFS_OBJECT(captive_vfs_parent_object)->options.sandbox_server_argv
936                         && (evp->_major==CORBA_SYSTEM_EXCEPTION && !strcmp(ex_CORBA_COMM_FAILURE,CORBA_exception_id(evp)))) {
937                 r=GNOME_VFS_ERROR_SERVICE_NOT_AVAILABLE;
938                 if (captive_vfs_parent_object->corba_Vfs_object!=CORBA_OBJECT_NIL)
939                         captive_vfs_parent_object_aborted(captive_vfs_parent_object);   /* errors ignored */
940                 }
941         else if (evp->_major==CORBA_USER_EXCEPTION && !strcmp(ex_Captive_GnomeVFSResultException,CORBA_exception_id(evp))) {
942                 r=((Captive_GnomeVFSResultException *)CORBA_exception_value(evp))->gnome_vfs_result;
943                 g_assert(r!=GNOME_VFS_ERROR_SERVICE_NOT_AVAILABLE);     /* code reserved for sandbox restarts */
944                 }
945         else {
946                 r=GNOME_VFS_ERROR_GENERIC;
947                 g_warning(_("CORBA Exception occured: id=\"%s\", value=%p"),
948                                 CORBA_exception_id(evp),CORBA_exception_value(evp));
949                 }
950         CORBA_exception_free(evp);
951
952         return r;
953 }
954
955
956 void captive_sandbox_child_GnomeVFSResultException_throw(CORBA_Environment *evp,GnomeVFSResult errvfsresult)
957 {
958 Captive_GnomeVFSResultException *gnome_vfs_result_exception;
959
960         g_return_if_fail(evp!=NULL);
961
962         gnome_vfs_result_exception=Captive_GnomeVFSResultException__alloc();
963         gnome_vfs_result_exception->gnome_vfs_result=errvfsresult;
964         CORBA_exception_set(evp,CORBA_USER_EXCEPTION,ex_Captive_GnomeVFSResultException,gnome_vfs_result_exception);
965 }