]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - unix/gtkmain.c
Make gtkmain.c contain the actual main().
[PuTTY.git] / unix / gtkmain.c
1 /*
2  * gtkmain.c: the common main-program code between the straight-up
3  * Unix PuTTY and pterm, which they do not share with the
4  * multi-session gtkapp.c.
5  */
6
7 #define _GNU_SOURCE
8
9 #include <string.h>
10 #include <assert.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include <signal.h>
14 #include <stdio.h>
15 #include <time.h>
16 #include <errno.h>
17 #include <locale.h>
18 #include <fcntl.h>
19 #include <unistd.h>
20 #include <sys/types.h>
21 #include <sys/wait.h>
22 #include <gtk/gtk.h>
23 #if !GTK_CHECK_VERSION(3,0,0)
24 #include <gdk/gdkkeysyms.h>
25 #endif
26
27 #if GTK_CHECK_VERSION(2,0,0)
28 #include <gtk/gtkimmodule.h>
29 #endif
30
31 #define MAY_REFER_TO_GTK_IN_HEADERS
32
33 #include "putty.h"
34 #include "terminal.h"
35 #include "gtkcompat.h"
36 #include "gtkfont.h"
37 #include "gtkmisc.h"
38
39 #ifndef NOT_X_WINDOWS
40 #include <gdk/gdkx.h>
41 #include <X11/Xlib.h>
42 #include <X11/Xutil.h>
43 #include <X11/Xatom.h>
44 #endif
45
46 static char *progname, **gtkargvstart;
47 static int ngtkargs;
48
49 extern char **pty_argv;        /* declared in pty.c */
50 extern int use_pty_argv;
51
52 static const char *app_name = "pterm";
53
54 char *x_get_default(const char *key)
55 {
56 #ifndef NOT_X_WINDOWS
57     return XGetDefault(GDK_DISPLAY_XDISPLAY(gdk_display_get_default()),
58                        app_name, key);
59 #else
60     return NULL;
61 #endif
62 }
63
64 void fork_and_exec_self(int fd_to_close, ...)
65 {
66     /*
67      * Re-execing ourself is not an exact science under Unix. I do
68      * the best I can by using /proc/self/exe if available and by
69      * assuming argv[0] can be found on $PATH if not.
70      * 
71      * Note that we also have to reconstruct the elements of the
72      * original argv which gtk swallowed, since the user wants the
73      * new session to appear on the same X display as the old one.
74      */
75     char **args;
76     va_list ap;
77     int i, n;
78     int pid;
79
80     /*
81      * Collect the arguments with which to re-exec ourself.
82      */
83     va_start(ap, fd_to_close);
84     n = 2;                             /* progname and terminating NULL */
85     n += ngtkargs;
86     while (va_arg(ap, char *) != NULL)
87         n++;
88     va_end(ap);
89
90     args = snewn(n, char *);
91     args[0] = progname;
92     args[n-1] = NULL;
93     for (i = 0; i < ngtkargs; i++)
94         args[i+1] = gtkargvstart[i];
95
96     i++;
97     va_start(ap, fd_to_close);
98     while ((args[i++] = va_arg(ap, char *)) != NULL);
99     va_end(ap);
100
101     assert(i == n);
102
103     /*
104      * Do the double fork.
105      */
106     pid = fork();
107     if (pid < 0) {
108         perror("fork");
109         sfree(args);
110         return;
111     }
112
113     if (pid == 0) {
114         int pid2 = fork();
115         if (pid2 < 0) {
116             perror("fork");
117             _exit(1);
118         } else if (pid2 > 0) {
119             /*
120              * First child has successfully forked second child. My
121              * Work Here Is Done. Note the use of _exit rather than
122              * exit: the latter appears to cause destroy messages
123              * to be sent to the X server. I suspect gtk uses
124              * atexit.
125              */
126             _exit(0);
127         }
128
129         /*
130          * If we reach here, we are the second child, so we now
131          * actually perform the exec.
132          */
133         if (fd_to_close >= 0)
134             close(fd_to_close);
135
136         execv("/proc/self/exe", args);
137         execvp(progname, args);
138         perror("exec");
139         _exit(127);
140
141     } else {
142         int status;
143         sfree(args);
144         waitpid(pid, &status, 0);
145     }
146
147 }
148
149 void launch_duplicate_session(Conf *conf)
150 {
151     /*
152      * For this feature we must marshal conf and (possibly) pty_argv
153      * into a byte stream, create a pipe, and send this byte stream
154      * to the child through the pipe.
155      */
156     int i, ret, sersize, size;
157     char *data;
158     char option[80];
159     int pipefd[2];
160
161     if (pipe(pipefd) < 0) {
162         perror("pipe");
163         return;
164     }
165
166     size = sersize = conf_serialised_size(conf);
167     if (use_pty_argv && pty_argv) {
168         for (i = 0; pty_argv[i]; i++)
169             size += strlen(pty_argv[i]) + 1;
170     }
171
172     data = snewn(size, char);
173     conf_serialise(conf, data);
174     if (use_pty_argv && pty_argv) {
175         int p = sersize;
176         for (i = 0; pty_argv[i]; i++) {
177             strcpy(data + p, pty_argv[i]);
178             p += strlen(pty_argv[i]) + 1;
179         }
180         assert(p == size);
181     }
182
183     sprintf(option, "---[%d,%d]", pipefd[0], size);
184     noncloexec(pipefd[0]);
185     fork_and_exec_self(pipefd[1], option, NULL);
186     close(pipefd[0]);
187
188     i = ret = 0;
189     while (i < size && (ret = write(pipefd[1], data + i, size - i)) > 0)
190         i += ret;
191     if (ret < 0)
192         perror("write to pipe");
193     close(pipefd[1]);
194     sfree(data);
195 }
196
197 void launch_new_session(void)
198 {
199     fork_and_exec_self(-1, NULL);
200 }
201
202 void launch_saved_session(const char *str)
203 {
204     fork_and_exec_self(-1, "-load", str, NULL);
205 }
206
207 int read_dupsession_data(Conf *conf, char *arg)
208 {
209     int fd, i, ret, size, size_used;
210     char *data;
211
212     if (sscanf(arg, "---[%d,%d]", &fd, &size) != 2) {
213         fprintf(stderr, "%s: malformed magic argument `%s'\n", appname, arg);
214         exit(1);
215     }
216
217     data = snewn(size, char);
218     i = ret = 0;
219     while (i < size && (ret = read(fd, data + i, size - i)) > 0)
220         i += ret;
221     if (ret < 0) {
222         perror("read from pipe");
223         exit(1);
224     } else if (i < size) {
225         fprintf(stderr, "%s: unexpected EOF in Duplicate Session data\n",
226                 appname);
227         exit(1);
228     }
229
230     size_used = conf_deserialise(conf, data, size);
231     if (use_pty_argv && size > size_used) {
232         int n = 0;
233         i = size_used;
234         while (i < size) {
235             while (i < size && data[i]) i++;
236             if (i >= size) {
237                 fprintf(stderr, "%s: malformed Duplicate Session data\n",
238                         appname);
239                 exit(1);
240             }
241             i++;
242             n++;
243         }
244         pty_argv = snewn(n+1, char *);
245         pty_argv[n] = NULL;
246         n = 0;
247         i = size_used;
248         while (i < size) {
249             char *p = data + i;
250             while (i < size && data[i]) i++;
251             assert(i < size);
252             i++;
253             pty_argv[n++] = dupstr(p);
254         }
255     }
256
257     sfree(data);
258
259     return 0;
260 }
261
262 static void help(FILE *fp) {
263     if(fprintf(fp,
264 "pterm option summary:\n"
265 "\n"
266 "  --display DISPLAY         Specify X display to use (note '--')\n"
267 "  -name PREFIX              Prefix when looking up resources (default: pterm)\n"
268 "  -fn FONT                  Normal text font\n"
269 "  -fb FONT                  Bold text font\n"
270 "  -geometry GEOMETRY        Position and size of window (size in characters)\n"
271 "  -sl LINES                 Number of lines of scrollback\n"
272 "  -fg COLOUR, -bg COLOUR    Foreground/background colour\n"
273 "  -bfg COLOUR, -bbg COLOUR  Foreground/background bold colour\n"
274 "  -cfg COLOUR, -bfg COLOUR  Foreground/background cursor colour\n"
275 "  -T TITLE                  Window title\n"
276 "  -ut, +ut                  Do(default) or do not update utmp\n"
277 "  -ls, +ls                  Do(default) or do not make shell a login shell\n"
278 "  -sb, +sb                  Do(default) or do not display a scrollbar\n"
279 "  -log PATH, -sessionlog PATH  Log all output to a file\n"
280 "  -nethack                  Map numeric keypad to hjklyubn direction keys\n"
281 "  -xrm RESOURCE-STRING      Set an X resource\n"
282 "  -e COMMAND [ARGS...]      Execute command (consumes all remaining args)\n"
283          ) < 0 || fflush(fp) < 0) {
284         perror("output error");
285         exit(1);
286     }
287 }
288
289 static void version(FILE *fp) {
290     if(fprintf(fp, "%s: %s\n", appname, ver) < 0 || fflush(fp) < 0) {
291         perror("output error");
292         exit(1);
293     }
294 }
295
296 static struct gui_data *the_inst;
297
298 static const char *geometry_string;
299
300 int do_cmdline(int argc, char **argv, int do_everything, int *allow_launch,
301                Conf *conf)
302 {
303     int err = 0;
304     char *val;
305
306     /*
307      * Macros to make argument handling easier. Note that because
308      * they need to call `continue', they cannot be contained in
309      * the usual do {...} while (0) wrapper to make them
310      * syntactically single statements; hence it is not legal to
311      * use one of these macros as an unbraced statement between
312      * `if' and `else'.
313      */
314 #define EXPECTS_ARG { \
315     if (--argc <= 0) { \
316         err = 1; \
317         fprintf(stderr, "%s: %s expects an argument\n", appname, p); \
318         continue; \
319     } else \
320         val = *++argv; \
321 }
322 #define SECOND_PASS_ONLY { if (!do_everything) continue; }
323
324     while (--argc > 0) {
325         const char *p = *++argv;
326         int ret;
327
328         /*
329          * Shameless cheating. Debian requires all X terminal
330          * emulators to support `-T title'; but
331          * cmdline_process_param will eat -T (it means no-pty) and
332          * complain that pterm doesn't support it. So, in pterm
333          * only, we convert -T into -title.
334          */
335         if ((cmdline_tooltype & TOOLTYPE_NONNETWORK) &&
336             !strcmp(p, "-T"))
337             p = "-title";
338
339         ret = cmdline_process_param(p, (argc > 1 ? argv[1] : NULL),
340                                     do_everything ? 1 : -1, conf);
341
342         if (ret == -2) {
343             cmdline_error("option \"%s\" requires an argument", p);
344         } else if (ret == 2) {
345             --argc, ++argv;            /* skip next argument */
346             continue;
347         } else if (ret == 1) {
348             continue;
349         }
350
351         if (!strcmp(p, "-fn") || !strcmp(p, "-font")) {
352             FontSpec *fs;
353             EXPECTS_ARG;
354             SECOND_PASS_ONLY;
355             fs = fontspec_new(val);
356             conf_set_fontspec(conf, CONF_font, fs);
357             fontspec_free(fs);
358
359         } else if (!strcmp(p, "-fb")) {
360             FontSpec *fs;
361             EXPECTS_ARG;
362             SECOND_PASS_ONLY;
363             fs = fontspec_new(val);
364             conf_set_fontspec(conf, CONF_boldfont, fs);
365             fontspec_free(fs);
366
367         } else if (!strcmp(p, "-fw")) {
368             FontSpec *fs;
369             EXPECTS_ARG;
370             SECOND_PASS_ONLY;
371             fs = fontspec_new(val);
372             conf_set_fontspec(conf, CONF_widefont, fs);
373             fontspec_free(fs);
374
375         } else if (!strcmp(p, "-fwb")) {
376             FontSpec *fs;
377             EXPECTS_ARG;
378             SECOND_PASS_ONLY;
379             fs = fontspec_new(val);
380             conf_set_fontspec(conf, CONF_wideboldfont, fs);
381             fontspec_free(fs);
382
383         } else if (!strcmp(p, "-cs")) {
384             EXPECTS_ARG;
385             SECOND_PASS_ONLY;
386             conf_set_str(conf, CONF_line_codepage, val);
387
388         } else if (!strcmp(p, "-geometry")) {
389             EXPECTS_ARG;
390             SECOND_PASS_ONLY;
391             geometry_string = val;
392         } else if (!strcmp(p, "-sl")) {
393             EXPECTS_ARG;
394             SECOND_PASS_ONLY;
395             conf_set_int(conf, CONF_savelines, atoi(val));
396
397         } else if (!strcmp(p, "-fg") || !strcmp(p, "-bg") ||
398                    !strcmp(p, "-bfg") || !strcmp(p, "-bbg") ||
399                    !strcmp(p, "-cfg") || !strcmp(p, "-cbg")) {
400             EXPECTS_ARG;
401             SECOND_PASS_ONLY;
402
403             {
404 #if GTK_CHECK_VERSION(3,0,0)
405                 GdkRGBA rgba;
406                 int success = gdk_rgba_parse(&rgba, val);
407 #else
408                 GdkColor col;
409                 int success = gdk_color_parse(val, &col);
410 #endif
411
412                 if (!success) {
413                     err = 1;
414                     fprintf(stderr, "%s: unable to parse colour \"%s\"\n",
415                             appname, val);
416                 } else {
417 #if GTK_CHECK_VERSION(3,0,0)
418                     int r = rgba.red * 255;
419                     int g = rgba.green * 255;
420                     int b = rgba.blue * 255;
421 #else
422                     int r = col.red / 256;
423                     int g = col.green / 256;
424                     int b = col.blue / 256;
425 #endif
426
427                     int index;
428                     index = (!strcmp(p, "-fg") ? 0 :
429                              !strcmp(p, "-bg") ? 2 :
430                              !strcmp(p, "-bfg") ? 1 :
431                              !strcmp(p, "-bbg") ? 3 :
432                              !strcmp(p, "-cfg") ? 4 :
433                              !strcmp(p, "-cbg") ? 5 : -1);
434                     assert(index != -1);
435
436                     conf_set_int_int(conf, CONF_colours, index*3+0, r);
437                     conf_set_int_int(conf, CONF_colours, index*3+1, g);
438                     conf_set_int_int(conf, CONF_colours, index*3+2, b);
439                 }
440             }
441
442         } else if (use_pty_argv && !strcmp(p, "-e")) {
443             /* This option swallows all further arguments. */
444             if (!do_everything)
445                 break;
446
447             if (--argc > 0) {
448                 int i;
449                 pty_argv = snewn(argc+1, char *);
450                 ++argv;
451                 for (i = 0; i < argc; i++)
452                     pty_argv[i] = argv[i];
453                 pty_argv[argc] = NULL;
454                 break;                 /* finished command-line processing */
455             } else
456                 err = 1, fprintf(stderr, "%s: -e expects an argument\n",
457                                  appname);
458
459         } else if (!strcmp(p, "-title")) {
460             EXPECTS_ARG;
461             SECOND_PASS_ONLY;
462             conf_set_str(conf, CONF_wintitle, val);
463
464         } else if (!strcmp(p, "-log")) {
465             Filename *fn;
466             EXPECTS_ARG;
467             SECOND_PASS_ONLY;
468             fn = filename_from_str(val);
469             conf_set_filename(conf, CONF_logfilename, fn);
470             conf_set_int(conf, CONF_logtype, LGTYP_DEBUG);
471             filename_free(fn);
472
473         } else if (!strcmp(p, "-ut-") || !strcmp(p, "+ut")) {
474             SECOND_PASS_ONLY;
475             conf_set_int(conf, CONF_stamp_utmp, 0);
476
477         } else if (!strcmp(p, "-ut")) {
478             SECOND_PASS_ONLY;
479             conf_set_int(conf, CONF_stamp_utmp, 1);
480
481         } else if (!strcmp(p, "-ls-") || !strcmp(p, "+ls")) {
482             SECOND_PASS_ONLY;
483             conf_set_int(conf, CONF_login_shell, 0);
484
485         } else if (!strcmp(p, "-ls")) {
486             SECOND_PASS_ONLY;
487             conf_set_int(conf, CONF_login_shell, 1);
488
489         } else if (!strcmp(p, "-nethack")) {
490             SECOND_PASS_ONLY;
491             conf_set_int(conf, CONF_nethack_keypad, 1);
492
493         } else if (!strcmp(p, "-sb-") || !strcmp(p, "+sb")) {
494             SECOND_PASS_ONLY;
495             conf_set_int(conf, CONF_scrollbar, 0);
496
497         } else if (!strcmp(p, "-sb")) {
498             SECOND_PASS_ONLY;
499             conf_set_int(conf, CONF_scrollbar, 1);
500
501         } else if (!strcmp(p, "-name")) {
502             EXPECTS_ARG;
503             app_name = val;
504
505         } else if (!strcmp(p, "-xrm")) {
506             EXPECTS_ARG;
507             provide_xrm_string(val);
508
509         } else if(!strcmp(p, "-help") || !strcmp(p, "--help")) {
510             help(stdout);
511             exit(0);
512
513         } else if(!strcmp(p, "-version") || !strcmp(p, "--version")) {
514             version(stdout);
515             exit(0);
516
517         } else if (!strcmp(p, "-pgpfp")) {
518             pgp_fingerprints();
519             exit(1);
520
521         } else if(p[0] != '-' && (!do_everything ||
522                                   process_nonoption_arg(p, conf,
523                                                         allow_launch))) {
524             /* do nothing */
525
526         } else {
527             err = 1;
528             fprintf(stderr, "%s: unrecognized option '%s'\n", appname, p);
529         }
530     }
531
532     return err;
533 }
534
535 extern int cfgbox(Conf *conf);
536
537 int main(int argc, char **argv)
538 {
539     Conf *conf;
540     int need_config_box;
541
542     setlocale(LC_CTYPE, "");
543
544     {
545         /* Call the function in ux{putty,pterm}.c to do app-type
546          * specific setup */
547         extern void setup(int);
548         setup(TRUE);     /* TRUE means we are a one-session process */
549     }
550
551     progname = argv[0];
552
553     /*
554      * Copy the original argv before letting gtk_init fiddle with
555      * it. It will be required later.
556      */
557     {
558         int i, oldargc;
559         gtkargvstart = snewn(argc-1, char *);
560         for (i = 1; i < argc; i++)
561             gtkargvstart[i-1] = dupstr(argv[i]);
562         oldargc = argc;
563         gtk_init(&argc, &argv);
564         ngtkargs = oldargc - argc;
565     }
566
567     conf = conf_new();
568
569     gtkcomm_setup();
570
571     /*
572      * Block SIGPIPE: if we attempt Duplicate Session or similar and
573      * it falls over in some way, we certainly don't want SIGPIPE
574      * terminating the main pterm/PuTTY. However, we'll have to
575      * unblock it again when pterm forks.
576      */
577     block_signal(SIGPIPE, 1);
578
579     if (argc > 1 && !strncmp(argv[1], "---", 3)) {
580         read_dupsession_data(conf, argv[1]);
581         /* Splatter this argument so it doesn't clutter a ps listing */
582         smemclr(argv[1], strlen(argv[1]));
583
584         assert(conf_launchable(conf));
585         need_config_box = FALSE;
586     } else {
587         /* By default, we bring up the config dialog, rather than launching
588          * a session. This gets set to TRUE if something happens to change
589          * that (e.g., a hostname is specified on the command-line). */
590         int allow_launch = FALSE;
591         if (do_cmdline(argc, argv, 0, &allow_launch, conf))
592             exit(1);                   /* pre-defaults pass to get -class */
593         do_defaults(NULL, conf);
594         if (do_cmdline(argc, argv, 1, &allow_launch, conf))
595             exit(1);                   /* post-defaults, do everything */
596
597         cmdline_run_saved(conf);
598
599         if (loaded_session)
600             allow_launch = TRUE;
601
602         need_config_box = (!allow_launch || !conf_launchable(conf));
603     }
604
605     /*
606      * Put up the config box.
607      */
608     if (need_config_box && !cfgbox(conf))
609         exit(0);                       /* config box hit Cancel */
610
611     /*
612      * Create the main session window. We don't really need to keep
613      * the return value - the fact that it'll be linked from a zillion
614      * GTK and glib bits and bobs known to the main loop will be
615      * sufficient to make everything actually happen - but we stash it
616      * in a global variable anyway, so that it'll be easy to find in a
617      * debugger.
618      */
619     the_inst = new_session_window(conf, geometry_string);
620
621     gtk_main();
622
623     return 0;
624 }