33a675e37dddc1c2a657cb0f283311f43bc90231
[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 const gchar *ior_read_error;
483
484         /* Initialize /tmp/orbit-$username directory for linking IOR socket. */
485         errbool=corba_init("captive-sandbox-parent",&captive_corba_ev,&captive_corba_orb,&captive_corba_poa);
486         g_assert(errbool==TRUE);
487
488         /* FIXME: Security: Duplicate giop_tmpdir_init() here. */
489         if (!sandbox_parent_own_orbit_dir) {
490                 /* FIXME: Make 'CAPTIVE_SANDBOX_CHROOT' configurable. */
491                 sandbox_parent_own_orbit_dir=g_strdup_printf("%s/tmp/captive-orbit-%d",CAPTIVE_SANDBOX_CHROOT,getpid());
492                 if (mkdir(sandbox_parent_own_orbit_dir,0700)) {
493                         g_assert(errno==EEXIST);
494                         sandbox_parent_own_orbit_dir_cleanup_init();
495                         unlink_nonrecursive(sandbox_parent_own_orbit_dir);
496                         if (mkdir(sandbox_parent_own_orbit_dir,0700))
497                                 g_assert_not_reached();
498                         }
499                 sandbox_parent_own_orbit_dir_cleanup_init();
500 #ifdef HAVE_ORBIT_LINK
501                 link_set_tmpdir(sandbox_parent_own_orbit_dir);
502 #else
503                 linc_set_tmpdir(sandbox_parent_own_orbit_dir);
504 #endif
505                 }
506
507         data=captive_rtl_file_read(Vfs_IOR_fd_read,&data_size); /* data_fd_read */
508         errint=close(Vfs_IOR_fd_read);
509         ior_read_error=NULL;
510 #define IOR_READ_ERROR(cond) G_STMT_START { \
511                 if (!ior_read_error && !(cond)) \
512                         ior_read_error=G_STRINGIFY(cond); \
513                 } G_STMT_END
514         IOR_READ_ERROR(errint==0);
515         IOR_READ_ERROR(data!=NULL);
516         IOR_READ_ERROR(data_size>=1);
517         IOR_READ_ERROR(data[data_size-1]=='\n');
518         if (ior_read_error)
519                 g_error(_("Error connecting to the sandbox server (failed \"%s\"). Try running by hand: %s"),
520                                 ior_read_error,CAPTIVE_VFS_OBJECT(captive_vfs_parent_object)->options.sandbox_server_argv[0]);
521 #undef IOR_READ_ERROR
522
523         hash=g_hash_table_new(g_str_hash,g_str_equal);
524
525         for (s=data;s<data+data_size;s=se+1) {
526                 se=strchr(s,'\n');
527                 g_assert(se!=NULL);
528                 *se=0;
529                 sd=strchr(s,'=');
530                 g_assert(sd!=NULL);
531                 *sd=0;
532                 g_hash_table_insert(hash,s,sd+1);
533                 }
534         g_assert(s==data+data_size);
535
536         if ((child_chroot_pid_hashkey_dir=g_hash_table_lookup(hash,"chroot_pid_hashkey_dir"))) {
537 const gchar *socketname,*socketpathname_src,*socketpathname_dest;
538 const gchar *chrooted_orbit_dir;
539
540                 /* IOR contains the full pathname with the setuid username encoded. */
541                 chrooted_orbit_dir=g_hash_table_lookup(hash,"chrooted_orbit_dir");
542                 g_assert(chrooted_orbit_dir!=NULL);
543                 captive_vfs_parent_object->corba_chrooted_orbit_dir=g_strdup(chrooted_orbit_dir);
544                 /* 0700 as this directory will not be reused
545                  * to commuicate with any other sandbox child.
546                  */
547                 if (mkdir(chrooted_orbit_dir,0700)) {
548                         g_assert(errno==EEXIST);
549                         }
550
551                 socketname=g_hash_table_lookup(hash,"socketname");
552                 g_assert(socketname!=NULL);
553                 captive_vfs_parent_object->corba_socketname=g_strdup(socketname);
554
555                 socketpathname_src=captive_printf_alloca("%s/%s/%s",child_chroot_pid_hashkey_dir,chrooted_orbit_dir,socketname);
556                 socketpathname_dest=g_strdup_printf("%s/%s",chrooted_orbit_dir,socketname);
557                 errint=link(socketpathname_src,socketpathname_dest);
558                 if (errint)
559                         g_error("link(\"%s\",\"%s\")=%d:%m",socketpathname_src,socketpathname_dest,errint);
560                 }
561         if (child_chroot_pid_hashkey_dirp)
562                 *child_chroot_pid_hashkey_dirp=g_strdup(child_chroot_pid_hashkey_dir);
563
564         ior=g_hash_table_lookup(hash,"ior");
565         g_assert(ior!=NULL);
566         ior=g_strdup(ior);
567         g_free(data);
568
569         g_hash_table_destroy(hash);
570
571         return ior;
572 }
573
574
575 static xmlNode *options_module_captive_to_xml
576                 (xmlNode *dest_xml_parent,const struct captive_options_module *src_options_module_captive)
577 {
578         g_return_val_if_fail(dest_xml_parent!=NULL,NULL);
579         g_return_val_if_fail(src_options_module_captive!=NULL,NULL);
580
581         { xmlNode *module=xmlNewTextChild(dest_xml_parent,NULL,"module",NULL);
582         const gchar *type_string="???"; /* Prevent: ... might be used uninitialized in this function */
583         const gchar *basename,*cgs;
584
585                 basename=src_options_module_captive->pathname_utf8;
586                 if ((cgs=strrchr(basename,'/')))
587                         basename=cgs+1;
588                 xmlNewProp(module,"basename",basename);
589                 switch (src_options_module_captive->type) {
590                         case CAPTIVE_OPTIONS_MODULE_TYPE_PE32:
591                                 type_string="PE32";
592                                 xmlNewProp(module,"length",captive_printf_alloca("%lu",(unsigned long)src_options_module_captive->u.pe32.length));
593                                 xmlNewProp(module,"md5"   ,src_options_module_captive->u.pe32.md5);
594                                 break;
595                         case CAPTIVE_OPTIONS_MODULE_TYPE_GMODULE:
596                                 type_string="gmodule";
597                                 break;
598                         default: g_assert_not_reached();
599                         }
600                 xmlNewProp(module,"type",type_string);  /* AFTER the 'switch' to set 'type_string'! */
601                 return module;
602                 }
603 }
604
605
606 static void sandbox_parent_bug_doc_make(CaptiveVfsParentObject *captive_vfs_parent_object)
607 {
608         { xmlDoc *doc=xmlNewDoc("1.0");
609                 captive_vfs_parent_object->corba_bug_doc=doc;
610                 { xmlNode *bug=xmlNewDocNode(captive_vfs_parent_object->corba_bug_doc,NULL,"bug",NULL);
611                         xmlDocSetRootElement(captive_vfs_parent_object->corba_bug_doc,bug);
612                         captive_vfs_parent_object->corba_bug=bug;
613                         { xmlNode *bug_captive=xmlNewTextChild(bug,NULL,"captive",NULL);
614                                 xmlNewProp(bug_captive,"version",VERSION);
615                                 }
616                         { xmlNode *bug_filesystem=xmlNewTextChild(bug,NULL,"filesystem",NULL);
617                                 options_module_captive_to_xml(bug_filesystem,&CAPTIVE_VFS_OBJECT(captive_vfs_parent_object)->options.filesystem);
618                                 }
619                         { xmlNode *bug_load_module=xmlNewTextChild(bug,NULL,"load_module",NULL);
620                         guint load_moduleui;
621                         struct captive_options_module *options_module;
622                         GList *load_module_node;
623
624                                 for (load_moduleui=0,load_module_node=CAPTIVE_VFS_OBJECT(captive_vfs_parent_object)->options.load_module;
625                                                 load_module_node;
626                                                 load_moduleui++,load_module_node=load_module_node->next) {
627                                         options_module=load_module_node->data;
628                                         options_module_captive_to_xml(bug_load_module,options_module);
629                                         }
630                                 }
631                         { xmlNode *bug_action=xmlNewTextChild(bug,NULL,"action",NULL);
632                                 captive_vfs_parent_object->corba_bug_action=bug_action;
633                                 }
634                         { xmlNode *bug_log=xmlNewTextChild(bug,NULL,"log",NULL);
635                                 captive_vfs_parent_object->corba_bug_log=bug_log;
636                                 }
637                         }
638                 }
639 }
640
641
642 static void sandbox_parent(const gchar *Vfs_IOR,const gchar *child_chroot_pid_hashkey_dir,CaptiveVfsParentObject *captive_vfs_parent_object)
643 {
644 Captive_Vfs Vfs_object;
645 Captive_GLogFunc GLogFunc_object;
646 Captive_CaptiveIOChannel CaptiveIOChannel_object;
647 Captive_CaptiveOptions options_corba;
648 guint load_module_length,load_moduleui;
649 struct captive_options_module *options_module;
650 GList *load_module_node;
651 const gchar *child_chroot_parent_own_orbit_socket,*child_chroot_parent_own_orbit_dir;
652 int errint;
653
654         g_return_if_fail(Vfs_IOR!=NULL);
655         /* 'child_chroot_pid_hashkey_dir' may be NULL */
656         g_return_if_fail(CAPTIVE_VFS_PARENT_IS_OBJECT(captive_vfs_parent_object));
657
658         Vfs_object=CORBA_ORB_string_to_object(captive_corba_orb,Vfs_IOR,&captive_corba_ev);
659         g_assert(validate_CORBA_Environment(&captive_corba_ev));
660
661         /* Init 'GLogFunc_object' */
662         GLogFunc_object=impl_Captive_GLogFunc__create(captive_corba_poa,captive_vfs_parent_object,&captive_corba_ev);
663         g_assert(validate_CORBA_Environment(&captive_corba_ev));
664
665         /* Init 'CaptiveIOChannel_object' */
666         if (!captive_vfs_parent_object->corba_parent_giochanel_blind_source) {
667 GIOChannel *giochannel;
668
669                 giochannel=CAPTIVE_VFS_OBJECT(captive_vfs_parent_object)->options.image_iochannel;
670                 g_io_channel_ref(giochannel);
671
672                 giochannel=captive_storage_relastblock(giochannel);
673
674                 switch (CAPTIVE_VFS_OBJECT(captive_vfs_parent_object)->options.rwmode) {
675                         case CAPTIVE_OPTION_RWMODE_RO:
676                         case CAPTIVE_OPTION_RWMODE_RW:
677                                 break;
678                         case CAPTIVE_OPTION_RWMODE_BLIND: {
679 GIOChannel *giochannel_orig;
680
681                                 giochannel_orig=giochannel;
682                                 giochannel=(GIOChannel *)captive_giochannel_blind_new(
683                                                 giochannel,     /* giochannel_orig */
684                                                 TRUE); /* writeable */
685                                 g_io_channel_unref(giochannel_orig);    /* reffed by captive_giochannel_blind_new() */
686                                 } break;
687                         default: g_assert_not_reached();
688                         }
689                 captive_vfs_parent_object->corba_parent_giochanel_blind_source=giochannel;
690                 }
691
692         if (!captive_vfs_parent_object->corba_parent_giochanel_blind)
693                 captive_vfs_parent_object->corba_parent_giochanel_blind=(GIOChannel *)captive_giochannel_blind_new(
694                                 captive_vfs_parent_object->corba_parent_giochanel_blind_source,  /* giochannel_orig */
695                                 (CAPTIVE_VFS_OBJECT(captive_vfs_parent_object)->options.rwmode!=CAPTIVE_OPTION_RWMODE_RO)); /* writeable */
696         CaptiveIOChannel_object=impl_Captive_CaptiveIOChannel__create(captive_corba_poa,
697                         captive_vfs_parent_object->corba_parent_giochanel_blind,&captive_corba_ev);
698         g_assert(validate_CORBA_Environment(&captive_corba_ev));
699
700         /* Create the socket needed for 'sandbox_parent_own_orbit_socket' below
701          * by CORBA_ORB_object_to_string()->ORBit_marshal_object()->IOP_generate_profiles()->ORBit_ORB_start_servers...
702          */
703         {
704 char *GLogFunc_IOR;
705                 GLogFunc_IOR=CORBA_ORB_object_to_string(captive_corba_orb,GLogFunc_object,&captive_corba_ev);
706                 g_assert(validate_CORBA_Environment(&captive_corba_ev));
707                 g_assert(GLogFunc_IOR!=NULL);
708                 CORBA_free(GLogFunc_IOR);
709                 }
710
711         if (sandbox_parent_own_orbit_dir && !sandbox_parent_own_orbit_socket) {
712 DIR *dir;
713 struct dirent *dirent;
714
715                 dir=opendir(sandbox_parent_own_orbit_dir);
716                 g_assert(dir!=NULL);
717
718                 while (errno=0,(dirent=readdir(dir))) {
719                         if (!strcmp(dirent->d_name,".") || !strcmp(dirent->d_name,".."))
720                                 continue;
721                         g_assert(sandbox_parent_own_orbit_socket==NULL);
722                         sandbox_parent_own_orbit_socket=g_strdup_printf("%s/%s",sandbox_parent_own_orbit_dir,dirent->d_name);
723                         }
724                 g_assert(errno==0);
725                 errint=closedir(dir);
726                 g_assert(errint==0);
727                 g_assert(sandbox_parent_own_orbit_socket!=NULL);
728                 }
729
730         if (child_chroot_pid_hashkey_dir) {
731 gchar *s;
732
733                 child_chroot_parent_own_orbit_dir=captive_printf_alloca("%s/%s",child_chroot_pid_hashkey_dir,sandbox_parent_own_orbit_dir);
734                 s=(/* de-const */ gchar *)child_chroot_parent_own_orbit_dir;
735                 do {
736                         s=strchr(s,'/');
737                         if (s)
738                                 *s=0;
739                         if (*child_chroot_parent_own_orbit_dir) {
740                                 errint=mkdir(child_chroot_parent_own_orbit_dir,0777);
741                                 if (errint)
742                                         g_assert(errno==EEXIST);
743                                 else {
744                                         /* chmod(2) it to prevent mode limitation by
745                                          * active ulimit(2) of being executed by mount(8).
746                                          */
747                                         errint=chmod(child_chroot_parent_own_orbit_dir,0777);
748                                         g_assert(errint==0);
749                                         }
750                                 }
751                         if (s)
752                                 *s++='/';
753                         } while (s);
754                 child_chroot_parent_own_orbit_socket=captive_printf_alloca("%s/%s",
755                                 child_chroot_pid_hashkey_dir,sandbox_parent_own_orbit_socket);
756                 errint=link(sandbox_parent_own_orbit_socket,child_chroot_parent_own_orbit_socket);
757                 g_assert(errint==0);
758                 /* chmod(2)s also our orig. one (!) but this one is protected by its 0777 directory. */
759                 errint=chmod(child_chroot_parent_own_orbit_socket,0666);
760                 g_assert(errint==0);
761                 }
762
763         options_corba.g_log_func=CORBA_Object_duplicate(GLogFunc_object,&captive_corba_ev);
764         g_assert(validate_CORBA_Environment(&captive_corba_ev));
765
766         options_module_captive_to_options_module_corba(&options_corba.filesystem,&CAPTIVE_VFS_OBJECT(captive_vfs_parent_object)->options.filesystem);
767         /* Prevent secondary captive_giochannel_blind inside of our sandbox child
768          * as we already have one captive_giochannel_blind in the parent.
769          */
770         options_corba.rwmode        =(CAPTIVE_VFS_OBJECT(captive_vfs_parent_object)->options.rwmode == CAPTIVE_OPTION_RWMODE_BLIND ? CAPTIVE_OPTION_RWMODE_RW
771                         : CAPTIVE_VFS_OBJECT(captive_vfs_parent_object)->options.rwmode);
772         options_corba.media         =CAPTIVE_VFS_OBJECT(captive_vfs_parent_object)->options.media;
773         options_corba.debug_messages=CAPTIVE_VFS_OBJECT(captive_vfs_parent_object)->options.debug_messages;
774
775         options_corba.image_iochannel=CORBA_Object_duplicate(CaptiveIOChannel_object,&captive_corba_ev);
776         g_assert(validate_CORBA_Environment(&captive_corba_ev));
777
778         load_module_length=g_list_length(CAPTIVE_VFS_OBJECT(captive_vfs_parent_object)->options.load_module);
779         options_corba.load_module._maximum=load_module_length;
780         options_corba.load_module._length=load_module_length;
781         options_corba.load_module._buffer=Captive_CaptiveOptionsModuleList_allocbuf(options_corba.load_module._maximum);
782         options_corba.load_module._release=TRUE;
783         for (load_moduleui=0,load_module_node=CAPTIVE_VFS_OBJECT(captive_vfs_parent_object)->options.load_module;
784                         load_module_node;
785                         load_moduleui++,load_module_node=load_module_node->next) {
786                 options_module=load_module_node->data;
787                 options_module_captive_to_options_module_corba(options_corba.load_module._buffer+load_moduleui,options_module);
788                 }
789
790         Captive_Vfs_init(Vfs_object,&options_corba,&captive_corba_ev);
791         g_assert(validate_CORBA_Environment(&captive_corba_ev));
792
793         Captive_CaptiveOptions__freekids(&options_corba,
794                         NULL);  /* d; unused */
795
796         captive_vfs_parent_object->corba_Vfs_object=Vfs_object;
797         captive_vfs_parent_object->corba_GLogFunc_object=GLogFunc_object;
798         captive_vfs_parent_object->corba_CaptiveIOChannel_object=CaptiveIOChannel_object;
799
800         if (CAPTIVE_VFS_OBJECT(captive_vfs_parent_object)->options.bug_pathname)
801                 sandbox_parent_bug_doc_make(captive_vfs_parent_object);
802 }
803
804 static void fd_shiftup(int *fdp)
805 {
806         g_return_if_fail(fdp!=NULL);
807
808         while (*fdp<=2 /* STDERR */) {
809                 *fdp=dup(*fdp);
810                 g_assert(*fdp!=-1);
811                 }
812 }
813
814 void captive_sandbox_fd_closeup(int fd_first_to_delete)
815 {
816 DIR *dir;
817 int errint;
818 int dir_fd;
819 struct dirent *dirent;
820
821         dir=opendir("/proc/self/fd/");
822         g_return_if_fail(dir!=NULL);
823         dir_fd=dirfd(dir);
824         g_return_if_fail(dir_fd!=-1);
825
826         while (errno=0,(dirent=readdir(dir))) {
827 long dirent_fd;
828 char *endptr;
829
830                 if (0
831                                 || !strcmp(dirent->d_name,".")
832                                 || !strcmp(dirent->d_name,".."))
833                         continue;
834                 dirent_fd=strtol(dirent->d_name,&endptr,10 /* base */);
835                 g_assert(dirent_fd>=0 && (!endptr || !*endptr));
836                 if (dirent_fd<fd_first_to_delete || dirent_fd==dir_fd)
837                         continue;
838
839                 errint=close(dirent_fd);
840                 g_assert(errint==0);
841                 errno=0;
842                 errint=close(dirent_fd);
843                 g_assert(errint==-1); g_assert(errno==EBADF);
844                 }
845         g_return_if_fail(errno==0);     /* check for EOF */
846
847         errint=closedir(dir);
848         g_return_if_fail(errint==0);
849         errno=0;
850         close(dir_fd); g_assert(errno==EBADF);  /* just a bit of paranoia; it should be already closed by closedir() */
851 }
852
853 gboolean captive_sandbox_spawn(CaptiveVfsParentObject *captive_vfs_parent_object)
854 {
855 /* Vfs_IOR_fds[0] for reading by sandbox_parent() - client,
856  * Vfs_IOR_fds[1] for writing by sandbox_child()  - server
857  */
858 int Vfs_IOR_fds[2],parentheart_fds[2];
859 int errint;
860 gboolean errbool;
861
862         g_return_val_if_fail(CAPTIVE_VFS_PARENT_IS_OBJECT(captive_vfs_parent_object),FALSE);
863
864         errint=pipe(Vfs_IOR_fds);
865         g_return_val_if_fail(errint==0,FALSE);
866         errint=pipe(parentheart_fds);
867         g_return_val_if_fail(errint==0,FALSE);
868
869         /* Currently never called anywhere:
870          *     errbool=corba_shutdown(&captive_corba_ev,&captive_corba_orb,&captive_corba_poa);
871          *     g_assert(errbool==TRUE);
872          */
873
874         if (CAPTIVE_VFS_OBJECT(captive_vfs_parent_object)->options.sandbox_server_ior) {
875                 g_assert(CAPTIVE_VFS_OBJECT(captive_vfs_parent_object)->options.sandbox_server_argv==NULL);
876
877                 errbool=corba_init("captive-sandbox-parent",&captive_corba_ev,&captive_corba_orb,&captive_corba_poa);
878                 g_assert(errbool==TRUE);
879
880                 captive_vfs_parent_object->corba_parentheart_fds_1=-1;
881                 captive_vfs_parent_object->corba_child_pid=-1;
882                 sandbox_parent(
883                                 CAPTIVE_VFS_OBJECT(captive_vfs_parent_object)->options.sandbox_server_ior,      /* Vfs_IOR */
884                                 NULL,   /* child_chroot_pid_hashkey_dir */
885                                 captive_vfs_parent_object);     /* captive_vfs_parent_object */
886                 return TRUE;
887                 }
888
889         g_assert(CAPTIVE_VFS_OBJECT(captive_vfs_parent_object)->options.sandbox_server_argv!=NULL);
890         switch ((captive_vfs_parent_object->corba_child_pid=fork())) {
891                 case -1:        /* error */
892                         g_return_val_if_reached(FALSE);
893
894                 case 0: { /* child */
895
896                         errint=close(Vfs_IOR_fds[0]);   /* close Vfs_IOR_fd_read */
897                         g_return_val_if_fail(errint==0,FALSE);
898                         errint=close(parentheart_fds[1]);       /* close parentheart_fd_write */
899                         g_return_val_if_fail(errint==0,FALSE);
900
901                         fd_shiftup(Vfs_IOR_fds+1);      /* Vfs_IOR_fd_write */
902                         fd_shiftup(parentheart_fds+0);  /* parentheart_fd_read */
903                         errint=dup2(Vfs_IOR_fds[1],1 /* STDOUT */);     /* Vfs_IOR_fd_write */
904                         g_return_val_if_fail(errint==1 /* STDOUT */,FALSE);
905                         errint=dup2(parentheart_fds[0],0 /* STDIN */);  /* parentheart_fd_read */
906                         g_return_val_if_fail(errint==0 /* STDIN */,FALSE);
907
908                         captive_sandbox_fd_closeup(2 /* STDERR */ +1);
909
910                         execv(CAPTIVE_VFS_OBJECT(captive_vfs_parent_object)->options.sandbox_server_argv[0],
911                                         /* re-const */ (char * const *)CAPTIVE_VFS_OBJECT(captive_vfs_parent_object)->options.sandbox_server_argv);
912                         g_return_val_if_reached(FALSE);
913                         } /* NOTREACHED */
914
915                 default: {      /* parent */
916 gchar *Vfs_IOR;
917 gchar *child_chroot_pid_hashkey_dir;
918
919                         errint=close(Vfs_IOR_fds[1]);   /* close Vfs_IOR_fd_write */
920                         g_return_val_if_fail(errint==0,FALSE);
921                         errint=close(parentheart_fds[0]);       /* close parentheart_fd_read */
922                         g_return_val_if_fail(errint==0,FALSE);
923                         errint=fcntl(parentheart_fds[1],F_SETFD,FD_CLOEXEC);
924                         /* This fcntl(2) may not be enough - some fork(2) may duplicate this
925                          * write descriptor and even if we do some process finish the child
926                          * may remain alone connected with some unknown fork(2)er from us.
927                          * Currently I am not aware such case would occur.
928                          */
929                         g_return_val_if_fail(errint==0,FALSE);
930                         captive_vfs_parent_object->corba_parentheart_fds_1=parentheart_fds[1];
931
932                         Vfs_IOR=sandbox_parent_read_ior(
933                                         Vfs_IOR_fds[0], /* Vfs_IOR_fd_read */
934                                         &child_chroot_pid_hashkey_dir,
935                                         captive_vfs_parent_object);
936
937                         sandbox_parent(
938                                         Vfs_IOR,        /* Vfs_IOR */
939                                         child_chroot_pid_hashkey_dir,   /* child_chroot_pid_hashkey_dir */
940                                         captive_vfs_parent_object);     /* captive_vfs_parent_object */
941
942                         g_free(Vfs_IOR);
943                         g_free(child_chroot_pid_hashkey_dir);
944
945                         /* 'parentheart_fds[1]' - parentheart_fd_write - is left open here */
946                         return TRUE;
947                         }
948                 }
949         /* NOTREACHED */
950         g_return_val_if_reached(FALSE);
951 }
952
953
954 GnomeVFSResult captive_sandbox_parent_return_from_CORBA_Environment
955                 (CORBA_Environment *evp,CaptiveVfsParentObject *captive_vfs_parent_object)
956 {
957 GnomeVFSResult r;
958
959         if (evp->_major==CORBA_NO_EXCEPTION)
960                 return GNOME_VFS_OK;
961
962         /* 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
963          * where we cannot do any restart anyway.
964          */
965         if (captive_vfs_parent_object && CAPTIVE_VFS_OBJECT(captive_vfs_parent_object)->options.sandbox_server_argv
966                         && (evp->_major==CORBA_SYSTEM_EXCEPTION && !strcmp(ex_CORBA_COMM_FAILURE,CORBA_exception_id(evp)))) {
967                 r=GNOME_VFS_ERROR_SERVICE_NOT_AVAILABLE;
968                 if (captive_vfs_parent_object->corba_Vfs_object!=CORBA_OBJECT_NIL)
969                         captive_vfs_parent_object_aborted(captive_vfs_parent_object);   /* errors ignored */
970                 }
971         else if (evp->_major==CORBA_USER_EXCEPTION && !strcmp(ex_Captive_GnomeVFSResultException,CORBA_exception_id(evp))) {
972                 r=((Captive_GnomeVFSResultException *)CORBA_exception_value(evp))->gnome_vfs_result;
973                 g_assert(r!=GNOME_VFS_ERROR_SERVICE_NOT_AVAILABLE);     /* code reserved for sandbox restarts */
974                 }
975         else {
976                 r=GNOME_VFS_ERROR_GENERIC;
977                 g_warning(_("CORBA Exception occured: id=\"%s\", value=%p"),
978                                 CORBA_exception_id(evp),CORBA_exception_value(evp));
979                 }
980         CORBA_exception_free(evp);
981
982         return r;
983 }
984
985
986 void captive_sandbox_child_GnomeVFSResultException_throw(CORBA_Environment *evp,GnomeVFSResult errvfsresult)
987 {
988 Captive_GnomeVFSResultException *gnome_vfs_result_exception;
989
990         g_return_if_fail(evp!=NULL);
991
992         gnome_vfs_result_exception=Captive_GnomeVFSResultException__alloc();
993         gnome_vfs_result_exception->gnome_vfs_result=errvfsresult;
994         CORBA_exception_set(evp,CORBA_USER_EXCEPTION,ex_Captive_GnomeVFSResultException,gnome_vfs_result_exception);
995 }