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