1 #! /usr/local/bin/guile -s
3 ;;; examples/safe/safe -- Example for safe (sand-boxed) evaluation.
7 ;;; This is a demo program for evaluating arbitrary (untrusted) Scheme
8 ;;; code in a controlled, safe environment. Evaluation in safe
9 ;;; environments restricts the evaluated code's access to some given
10 ;;; primitives, which are considered `safe', that means which cannot
11 ;;; do any harm to the world outside of Guile (creating/deleting files
14 ;;; *Note* that the files in this directory are only suitable for
15 ;;; demonstration purposes, if you have to implement safe evaluation
16 ;;; mechanisms in important environments, you will have to do more
17 ;;; than shown here -- for example disabling input/output operations.
19 ;;; Author: Martin Grabmueller
24 ;; Safe module creation is implemented in this module:
26 (use-modules (ice-9 safe))
28 ;; This is the main program. It expects one parameter in the format
29 ;; returned by (command-line) and expects that exactly one file name
30 ;; is passed in this list (after the script name, which is passed as
31 ;; the 0th parameter.)
33 ;; The given file is opened for reading, one expression after the
34 ;; other is read and evaluated in a safe environment. All exceptions
35 ;; caused by this evaluation are caught and printed out.
37 (define (main cmd-line)
39 ;; Internal definition of the procedure which prints usage
42 (define (display-help)
43 (display "Usage: safe FILENAME")
47 ;; Check that we received exactly one command line argument after
50 (if (not (= (length cmd-line) 2))
52 (let ((port (open-input-file (cadr cmd-line)))
54 ;; Create the safe module.
55 (safe-module (make-safe-module)))
57 ;; Read one expression a time.
58 (let lp ((expr (read port)))
59 ;; End of file? -> Return.
60 (if (eof-object? expr)
64 ;; Evaluate the expression in the safe environment.
65 (eval expr safe-module)
66 ;; ... and read the next expression if no error occured.
69 ;; Handle exceptions. This procedure will be called when an
70 ;; error occurs while evaluating the expression. It just
71 ;; prints out a message telling so and returns from the
72 ;; evaluation loop, thus terminating the program.
75 (display "** Exception: ")
79 ;; Start the main program.