]> git.donarmstrong.com Git - lilypond.git/blob - lily/main.cc
(do_chroot_jail): paranoia security for webserver
[lilypond.git] / lily / main.cc
1 /*
2   main.cc -- implement main () entrypoint.
3
4   source file of the GNU LilyPond music typesetter
5
6   (c) 1997--2005 Han-Wen Nienhuys <hanwen@cs.uu.nl>
7 */
8
9 #include "main.hh"
10
11 #include <cassert>
12 #include <clocale>
13 #include <cstring>
14
15 #include "config.hh"
16
17 #if HAVE_GETTEXT
18 #include <libintl.h>
19 #endif
20
21 #include "all-font-metrics.hh"
22 #include "file-name.hh"
23 #include "getopt-long.hh"
24 #include "global-ctor.hh"
25 #include "kpath.hh"
26 #include "lily-guile.hh"
27 #include "lily-version.hh"
28 #include "misc.hh"
29 #include "output-def.hh"
30 #include "warn.hh"
31 #include "freetype.hh"
32
33 /*
34  * Global options that can be overridden through command line.
35  */
36
37 /* Names of header fields to be dumped to a separate file. */
38 Array<String> dump_header_fieldnames_global;
39
40 /* Name of initialisation file. */
41 String init_name_global;
42
43 /* Selected output format.
44    One of tex, ps, scm, as.
45 */
46 String output_backend_global = "ps";
47 String output_format_global = "pdf";
48 bool is_pango_format_global;
49
50 /* Current output name. */
51 String output_name_global;
52
53 /* Run in safe mode? */
54 bool be_safe_global = false;
55
56 /* Verbose progress indication? */
57 bool be_verbose_global = false;
58
59 /* Scheme code to execute before parsing, after .scm init
60    This is where -e arguments are appended to.
61 */
62 String init_scheme_code_string = "(begin #t ";
63
64 bool make_preview = false;
65 bool make_pages = true;
66
67
68 /*
69  * Miscellaneous global stuff.
70  */
71 File_path global_path;
72
73
74 /*
75  * File globals.
76  */
77
78 static char const *AUTHORS =
79 "  Han-Wen Nienhuys <hanwen@cs.uu.nl>\n"
80 "  Jan Nieuwenhuizen <janneke@gnu.org>\n";
81
82 static char const *PROGRAM_NAME = "lilypond";
83 static char const *PROGRAM_URL = "http://lilypond.org";
84
85 static char const *NOTICE =
86 _f ("This program is free software.  It is covered by the GNU General Public\n"
87     "License and you are welcome to change it and/or distribute copies of it\n"
88     "under certain conditions.  Invoke as `%s --warranty' for more\n"
89     "information.\n", "lilypond").to_str0 ();
90   
91 static char const *WARRANTY =
92 _i ("    This program is free software; you can redistribute it and/or\n"
93     "modify it under the terms of the GNU General Public License version 2\n"
94     "as published by the Free Software Foundation.\n"
95     "\n"
96     "    This program is distributed in the hope that it will be useful,\n"
97     "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
98     "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n"
99     "General Public License for more details.\n"
100     "\n"
101     "    You should have received a copy (refer to the file COPYING) of the\n"
102     "GNU General Public License along with this program; if not, write to\n"
103     "the Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n"
104     "Boston, MA 02111-1307, USA.\n");
105
106
107 /* Where the init files live.  Typically:
108    LILYPOND_DATADIR = /usr/share/lilypond
109    LOCAL_LILYPOND_DATADIR = /usr/share/lilypond/<VERSION> */
110 char const *prefix_directories[] = {LILYPOND_DATADIR, LOCAL_LILYPOND_DATADIR, 0};
111
112 /* The jail specification: USER,GROUP,JAIL,DIR. */
113 String jail_spec;
114
115 /*  The option parser */
116 static Getopt_long *option_parser = 0;
117
118 /* Internationalisation kludge in two steps:
119    * use _i () to get entry in POT file
120    * call gettext () explicitely for actual "translation"  */
121
122 static Long_option_init options_static[] =
123   {
124     {_i ("EXT"), "backend", 'b', _i ("select backend to use")},
125     {_i ("EXPR"), "evaluate", 'e',
126      _i ("set option, use -e '(ly:option-usage)' for help")},
127     /* Bug in option parser: --output =foe is taken as an abbreviation
128        for --output-format.  */
129     {_i ("EXTs"), "formats", 'f', _i ("list of formats to dump")},
130     {0, "help", 'h',  _i ("print this help")},
131     {_i ("FIELD"), "header", 'H',  _i ("write header field to BASENAME.FIELD")},
132     {_i ("DIR"), "include", 'I',  _i ("add DIR to search path")},
133     {_i ("FILE"), "init", 'i',  _i ("use FILE as init file")},
134     {_i ("FILE"), "output", 'o',  _i ("write output to FILE (suffix will be added)")},
135     {_i ("USER,GROUP,JAIL,DIR"), "jail", 'j', _i ("chroot to JAIL, become USER:GROUP and cd into DIR")},
136     {0, "preview", 'p',  _i ("generate a preview")},
137     {0, "no-pages", 0,  _i ("don't generate full pages")},
138     {0, "png", 0,  _i ("generate PNG")},
139     {0, "ps", 0,  _i ("generate PostScript")},
140     {0, "dvi", 0,  _i ("generate DVI")},
141     {0, "pdf", 0,  _i ("generate PDF (default)")},
142     {0, "tex", 0,  _i ("generate TeX")},
143     {0, "safe-mode", 's',  _i ("run in safe mode")},
144     {0, "version", 'v',  _i ("print version number")},
145     {0, "verbose", 'V', _i ("be verbose")},
146     {0, "warranty", 'w',  _i ("show warranty and copyright")},
147     {0, 0, 0, 0}
148   };
149
150 static void
151 dir_info (FILE *out)
152 {
153   fputs ("\n", out);
154   fprintf (out, "LILYPOND_DATADIR =\"%s\"\n", LILYPOND_DATADIR);
155   fprintf (out, "LOCAL_LILYPOND_DATADIR =\"\%s\"\n", LOCAL_LILYPOND_DATADIR);
156   fprintf (out, "LOCALEDIR =\"%s\"\n", LOCALEDIR);
157
158   char *lilypond_prefix = getenv ("LILYPONDPREFIX");
159   fprintf (out, "LILYPONDPREFIX =\"%s\"\n",
160            (lilypond_prefix ? lilypond_prefix : ""));
161 }
162
163 static void
164 copyright ()
165 {
166   printf (_f ("Copyright (c) %s by\n%s  and others.",
167               "1996--2005",
168               AUTHORS).to_str0 ());
169   printf ("\n");
170 }
171
172 static void
173 identify (FILE *out)
174 {
175   fputs (gnu_lilypond_version_string ().to_str0 (), out);
176   fputs ("\n", out);
177 }
178  
179 static void
180 notice ()
181 {
182   identify (stdout);
183   printf (_f (NOTICE, PROGRAM_NAME).to_str0 ());
184   printf ("\n");
185   copyright ();
186 }
187
188 static void
189 usage ()
190 {
191   /* No version number or newline here.  It confuses help2man.  */
192   printf (_f ("Usage: %s [OPTION]... FILE...", PROGRAM_NAME).to_str0 ());
193   printf ("\n\n");
194   printf (_ ("Typeset music and/or produce MIDI from FILE.").to_str0 ());
195   printf ("\n\n");
196   printf (_ ("LilyPond produces beautiful music notation.").to_str0 ());
197   printf ("\n");
198   printf (_f ("For more information, see %s", PROGRAM_URL).to_str0 ());
199   printf ("\n\n");
200   printf (_ ("Options:").to_str0 ());
201   printf ("\n");
202   printf (Long_option_init::table_string (options_static).to_str0 ());
203   printf ("\n");
204   printf (_f ("Report bugs to %s.", "bug-lilypond@gnu.org").to_str0 ());
205   printf ("\n");
206   printf ("\n");
207 }
208
209 static void
210 warranty ()
211 {
212   identify (stdout);
213   printf ("\n");
214   copyright ();
215   printf ("\n");
216   printf (_ (WARRANTY).to_str0 ());
217 }
218
219 static void
220 setup_paths ()
221 {
222   if (char const *lilypond_prefix = getenv ("LILYPONDPREFIX"))
223     prefix_directories[1] = lilypond_prefix;
224
225   global_path.append ("");
226
227   /* Adding mf/out make lilypond unchanged source directory, when setting
228      LILYPONDPREFIX to lilypond-x.y.z */
229   char *suffixes[] = {"ly", "cff", "otf", "mf/out", "scm", "tfm", "ps", "svg",
230                       0};
231
232   for (unsigned i = 0; prefix_directories[i]; i++)
233     for (char **s = suffixes; *s; s++)
234       {
235         String p = prefix_directories[i] + to_string ('/') + String (*s);
236         global_path.prepend (p);
237         
238 #if !KPATHSEA
239         /* Urg: GNU make's $ (word) index starts at 1 */
240         int i  = 1;
241         while (global_path.try_append (p + to_string (".") + to_string (i)))
242           i++;
243 #endif
244       }
245 }
246   
247 static void
248 prepend_load_path (String dir)
249 {
250   String s = "(set! %load-path (cons \"" + dir + "\" %load-path))";
251   scm_c_eval_string (s.to_str0 ());
252 }
253
254 void init_global_tweak_registry ();
255 void init_fontconfig ();
256
257
258 static void
259 do_chroot_jail ()
260 {
261   /* Now we chroot, setuid/setgrp and chdir. If something goes wrong, we exit (this is a
262      security-sensitive area). First we split jail_spec into its components, then we
263      retrieve the user/group id (necessarily *before* chroot'ing!) and finally we perform
264      the actual actions. */
265
266   Array<String> components = String_convert::split(jail_spec, ',');
267   if (components.size() < 3)
268     {
269       error (_ ("too few elements in jail specification"));
270       exit(1);
271     }
272   if (components.size() > 4)
273     {
274       error (_ ("too many elements in jail specification"));
275       exit(1);
276     }
277
278   int uid, gid;
279   char *user_name = components[0].get_str0 ();
280   char *group_name = components[1].get_str0 ();
281   char *jail = components[2].get_str0 ();
282   char *wd = components[3].get_str0 ();
283
284   errno = 0;
285   struct passwd *passwd = getpwnam(user_name);
286   if (passwd == NULL)
287     {
288       if (errno == 0) 
289         error (_ ("user not found"));
290       else 
291         error(_f ("can't get user id from user name (%s)", strerror (errno)));
292       exit (3);
293     }
294   uid = passwd->pw_uid;
295
296   errno = 0;
297   struct group *group = getgrnam(group_name);
298   if (group == NULL)
299     {
300       if (errno == 0) 
301         error (_ ("group not found"));
302       else 
303         error(_f ("can't get group id from group name (%s)", strerror (errno)));
304       exit (3);
305     }
306   gid = group->gr_gid;
307
308   if (chroot (jail))
309     {
310       error (_f ("can't chroot (%s)", strerror (errno)));
311       exit (3);
312     }
313
314   if (setgid (gid))
315     {
316       error (_f ("can't change group id (%s)", strerror (errno)));
317       exit (3);
318     }
319
320   if (setuid (uid))
321     {
322       error (_f ("can't change user id (%s)", strerror (errno)));
323       exit (3);
324     }
325
326   if (chdir (wd))
327     {
328       error (_f ("can't change working directory (%s)", strerror (errno)));
329       exit (3);
330     }
331 }
332
333
334 static void
335 main_with_guile (void *, int, char **)
336 {
337   /* Engravers use lily.scm contents, need to make Guile find it.
338      Prepend onto GUILE %load-path, very ugh. */
339   for (unsigned i = 0; prefix_directories[i]; i++)
340     {
341       prepend_load_path (prefix_directories[i]);
342       /* Junk this.  We should make real modules iso. just loading files. */
343       prepend_load_path (String (prefix_directories[i]) + "/scm");
344     }
345
346   if (be_verbose_global)
347     dir_info (stderr);
348
349   ly_c_init_guile ();
350   call_constructors ();
351   init_global_tweak_registry ();
352   init_fontconfig ();
353   init_freetype ();
354
355   is_pango_format_global = (output_backend_global != "tex"
356                             && output_backend_global != "texstr");
357
358   all_fonts_global = new All_font_metrics (global_path.to_string ());
359
360   init_scheme_code_string += ")";
361   scm_c_eval_string ((char*) init_scheme_code_string.to_str0 ());
362
363   /* We accept multiple independent music files on the command line to
364      reduce compile time when processing lots of small files.
365      Starting the GUILE engine is very time consuming.  */
366
367   SCM files = SCM_EOL;
368   SCM *tail = &files;
369   while (char const *arg = option_parser->get_next_arg ())
370     {
371       *tail = scm_cons (scm_makfrom0str (arg), SCM_EOL);
372       tail = SCM_CDRLOC (*tail);
373     }
374   delete option_parser;
375   option_parser = 0;
376
377   if (files == SCM_EOL)
378     {
379       /* No FILE arguments is now a usage error to help newbies.  If you
380          want a filter, you're not a newbie and should know to use file
381          argument `-'.  */
382       usage ();
383       exit (2);
384     }
385
386   if (! jail_spec.is_empty ()) 
387      do_chroot_jail ();
388
389   SCM result = scm_call_1 (ly_lily_module_constant ("lilypond-main"), files);
390   (void) result;
391
392
393   /* Unreachable.  */
394   exit (0);
395 }
396
397 static void
398 setup_localisation ()
399 {
400 #if HAVE_GETTEXT
401   /* Enable locales */
402   setlocale (LC_ALL, "");
403   
404   /* FIXME: check if this is still true.
405     Disable localisation of float values.  This breaks TeX output.  */
406   setlocale (LC_NUMERIC, "C");
407   
408   String name (PACKAGE);
409   name.to_lower ();
410   bindtextdomain (name.to_str0 (), LOCALEDIR);
411   textdomain (name.to_str0 ());
412 #endif
413 }
414
415 static void
416 add_output_format (String format)
417 {
418   if (output_format_global != "")
419     output_format_global += ",";
420   output_format_global += format;
421 }
422
423
424 static void
425 parse_argv (int argc, char **argv)
426 {
427   bool help_b = false;
428   option_parser = new Getopt_long (argc, argv, options_static);
429   while (Long_option_init const *opt = (*option_parser) ())
430     {
431       switch (opt->shortname_char_)
432         {
433         case 0:
434           if (String (opt->longname_str0_) == "png"
435               || String (opt->longname_str0_) == "pdf"
436               || String (opt->longname_str0_) == "ps"
437               || String (opt->longname_str0_) == "dvi"
438               || String (opt->longname_str0_) == "tex")
439             {
440               add_output_format (opt->longname_str0_);
441             }
442           else if (String (opt->longname_str0_) == "preview")
443             make_preview = true;
444           else if (String (opt->longname_str0_) == "no-pages")
445             make_pages = false;
446           break;
447           
448         case 'v':
449           notice ();
450           exit (0);
451           break;
452         case 'o':
453           {
454             String s = option_parser->optional_argument_str0_;
455             File_name file_name (s);
456             output_name_global = file_name.to_string ();
457           }
458           break;
459         case 'j':
460           jail_spec = option_parser->optional_argument_str0_;
461           break;
462         case 'e':
463           init_scheme_code_string += option_parser->optional_argument_str0_;
464           break;
465         case 'w':
466           warranty ();
467           exit (0);
468           break;
469           
470         case 'b':
471           output_backend_global = option_parser->optional_argument_str0_;
472           break;
473
474         case 'f':
475           output_format_global = option_parser->optional_argument_str0_;
476           break;
477           
478         case 'H':
479           dump_header_fieldnames_global
480             .push (option_parser->optional_argument_str0_);
481           break;
482         case 'I':
483           global_path.append (option_parser->optional_argument_str0_);
484           break;
485         case 'i':
486           init_name_global = option_parser->optional_argument_str0_;
487           break;
488         case 'h':
489           help_b = true;
490           break;
491         case 'V':
492           be_verbose_global = true;
493           break;
494         case 's':
495           be_safe_global = true;
496           break;
497         case 'p':
498           make_preview = true;
499           break;
500         default:
501           programming_error (to_string ("unhandled short option: %c",
502                                         opt->shortname_char_));
503           assert (false);
504           break;
505         }
506     }
507
508   if (help_b)
509     {
510       identify (stdout);
511       usage ();
512       if (be_verbose_global)
513         dir_info (stdout);
514       exit (0);
515     }
516 }
517
518 int
519 main (int argc, char **argv)
520 {
521   setup_localisation ();
522   setup_paths ();
523   parse_argv (argc, argv);
524   identify (stderr);
525   initialize_kpathsea (argv[0]);
526
527   scm_boot_guile (argc, argv, main_with_guile, 0);
528
529   /* Unreachable */
530   return 0;
531 }