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