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