download-manager.js: fix bug resulting in un-killable special buffers
[conkeror.git] / modules / spawn-process.js
blob247e99337687ec28c509f36a96acccb56c9ebbbd
1 /**
2  * (C) Copyright 2007-2008 Jeremy Maitin-Shepard
3  *
4  * Use, modification, and distribution are subject to the terms specified in the
5  * COPYING file.
6 **/
8 require("interactive.js");
9 require("io.js");
11 const WINDOWS = (get_os() == "WINNT");
12 const POSIX = !WINDOWS;
13 const PATH = getenv("PATH").split(POSIX ? ":" : ";");
15 const path_component_regexp = POSIX ? /^[^\/]+$/ : /^[^\/\\]+$/;
17 function get_file_in_path(name) {
18     if (name instanceof Ci.nsIFile) {
19         if (name.exists())
20             return name;
21         return null;
22     }
23     var file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsILocalFile);
24     if (!path_component_regexp.test(name)) {
25         // Absolute path
26         try {
27             file.initWithPath(name);
28             if (file.exists())
29                 return file;
30         } catch (e) {}
31         return null;
32     } else {
33         // Relative path
34         for (var i = 0; i < PATH.length; ++i) {
35             try {
36                 file.initWithPath(PATH[i]);
37                 file.appendRelativePath(name);
38                 if (file.exists())
39                     return file;
40             } catch(e) {}
41         }
42     }
43     return null;
46 function spawn_process_internal(program, args, blocking) {
47     var process = Cc["@mozilla.org/process/util;1"].createInstance(Ci.nsIProcess);
48     process.init(get_file_in_path(program));
49     return process.run(!!blocking, args, args.length);
52 var PATH_programs = null;
53 function get_shell_command_completer() {
54     if (PATH_programs == null) {
55         PATH_programs = [];
56         var file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsILocalFile);
57         for (var i = 0; i < PATH.length; ++i) {
58             try {
59                 file.initWithPath(PATH[i]);
60                 var entries = file.directoryEntries;
61                 while (entries.hasMoreElements()) {
62                     var entry = entries.getNext().QueryInterface(Ci.nsIFile);
63                     PATH_programs.push(entry.leafName);
64                 }
65             } catch (e) {}
66         }
67         PATH_programs.sort();
68     }
70     return prefix_completer($completions = PATH_programs,
71                             $get_string = function (x) { return x; });
74 // use default
75 minibuffer_auto_complete_preferences["shell-command"] = null;
77 /* FIXME: support a relative or full path as well as PATH commands */
78 define_keywords("$cwd");
79 minibuffer.prototype.read_shell_command = function () {
80     keywords(arguments, $history = "shell-command");
81     var prompt = arguments.$prompt || "Shell command [" + arguments.$cwd + "]:";
82     var result = yield this.read(
83         $prompt = prompt,
84         $history = "shell-command",
85         $auto_complete = "shell-command",
86         $select,
87         $validator = function (x, m) {
88             var s = x.replace(/^\s+|\s+$/g, '');
89             if (s.length == 0) {
90                 m.message("A blank shell command is not allowed.");
91                 return false;
92             }
93             return true;
94         },
95         forward_keywords(arguments),
96         $completer = get_shell_command_completer());
97     yield co_return(result);
100 const STDIN_FILENO = 0;
101 const STDOUT_FILENO = 1;
102 const STDERR_FILENO = 2;
104 var spawn_process_helper_default_fd_wait_timeout = 1000;
105 var spawn_process_helper_setup_timeout = 2000;
106 var spawn_process_helper_program = file_locator.get("CurProcD", Ci.nsIFile);
107 spawn_process_helper_program.append("conkeror-spawn-helper");
110  * @param program_name
111  *                 Specifies the full path to the program.
112  * @param args
113  *                 An array of strings to pass as the arguments to the program.
114  *                 The first argument should be the program name.  These strings must not have
115  *                 any NUL bytes in them.
116  * @param working_dir
117  *                 If non-null, switch to the specified path before running the program.
118  * @param finished_callback
119  *                 Called with a single argument, the exit code of the process, as returned by the wait system call.
120  * @param failure_callback
121  *                 Called with a single argument, an exception, if one occurs.
122  * @param fds
123  *                 If non-null, must be an object with only non-negative integer properties set.  Each such property
124  *                 specifies that the corresponding file descriptor in the spaned process should be redirected.  Note that
125  *                 0 corresponds to STDIN, 1 corresponds to STDOUT, and 2 corresponds to STDERR.  Note that every redirected
126  *                 file descriptor can be used for both input and output, although STDIN, STDOUT, and STDERR are typically
127  *                 used only unidirectionally.  Each property must be an object itself, with an input and/or output property
128  *                 specifying callback functions that are called with an nsIAsyncInputStream or nsIAsyncOutputStream when the
129  *                 stream for that file descriptor is available.
130  * @param fd_wait_timeout
131  *                 Specifies the number of milliseconds to wait for the file descriptor redirection sockets to be closed after
132  *                 the control socket indicates the process has exited before they are closed forcefully.  A negative value
133  *                 means to wait indefinitely.  If fd_wait_timeout is null, spawn_process_helper_default_fd_wait_timeout
134  *                 is used instead.
137  * @returns
138  *                 A function that can be called to prematurely terminate the spawned process.
139  */
140 function spawn_process(program_name, args, working_dir,
141                        success_callback, failure_callback, fds,
142                        fd_wait_timeout) {
144     args = args.slice();
145     if (args[0] == null)
146         args[0] = (program_name instanceof Ci.nsIFile) ? program_name.path : program_name;
148     program_name = get_file_in_path(program_name).path;
150     const key_length = 100;
151     const fd_spec_size = 15;
153     if (fds == null)
154         fds = {};
156     if (fd_wait_timeout === undefined)
157         fd_wait_timeout = spawn_process_helper_default_fd_wait_timeout;
159     var unregistered_transports = [];
160     var registered_transports = [];
162     var server = null;
163     var setup_timer = null;
165     const CONTROL_CONNECTED = 0;
166     const CONTROL_SENDING_KEY = 1;
167     const CONTROL_SENT_KEY = 2;
169     var control_state = CONTROL_CONNECTED;
170     var terminate_pending = false;
172     var control_transport = null;
174     var control_binary_input_stream = null;
175     var control_output_stream = null, control_input_stream = null;
176     var exit_status = null;
178     var client_key = "";
179     var server_key = "";
180     // Make sure key does not have any 0 bytes in it.
181     for (let i = 0; i < key_length; ++i) client_key += String.fromCharCode(Math.floor(Math.random() * 255) + 1);
183     // Make sure key does not have any 0 bytes in it.
184     for (let i = 0; i < key_length; ++i) server_key += String.fromCharCode(Math.floor(Math.random() * 255) + 1);
186     var key_file_fd_data = "";
188     // This is the total number of redirected file descriptors.
189     var total_client_fds = 0;
191     // This is the total number of redirected file descriptors that will use a socket connection.
192     var total_fds = 0;
194     for (let i in fds) {
195         if (fds.hasOwnProperty(i)) {
196             key_file_fd_data += i + "\0";
197             let fd = fds[i];
198             if ('file' in fd) {
199                 if (fd.perms == null)
200                     fd.perms = 0666;
201                 key_file_fd_data += fd.file + "\0" + fd.mode + "\0" + fd.perms + "\0";
202                 delete fds[i]; // Remove it from fds, as we won't need to work with it anymore
203             } else
204                 ++total_fds;
205             ++total_client_fds;
206         }
207     }
208     var key_file_data = client_key + "\0" + server_key + "\0" + program_name + "\0" +
209         (working_dir != null ? working_dir : "") + "\0" +
210         args.length + "\0" +
211         args.join("\0") + "\0" +
212         total_client_fds + "\0" + key_file_fd_data;
214     function fail(e) {
215         if (!terminate_pending) {
216             terminate();
217             if (failure_callback)
218                 failure_callback(e);
219         }
220     }
222     function cleanup_server() {
223         if (server) {
224             server.close();
225             server = null;
226         }
227         for (let i in unregistered_transports) {
228             unregistered_transports[i].close(0);
229             delete unregistered_transports[i];
230         }
231     }
233     function cleanup_fd_sockets() {
234         for (let i in registered_transports) {
235             registered_transports[i].transport.close(0);
236             delete registered_transports[i];
237         }
238     }
240     function cleanup_control() {
241         if (control_transport) {
242             control_binary_input_stream.close();
243             control_binary_input_stream = null;
244             control_transport.close(0);
245             control_transport = null;
246             control_input_stream = null;
247             control_output_stream = null;
248         }
249     }
251     function control_send_terminate() {
252         control_input_stream = null;
253         control_binary_input_stream.close();
254         control_binary_input_stream = null;
255         async_binary_write(control_output_stream, "\0", function () {
256             control_output_stream = null;
257             control_transport.close(0);
258             control_transport = null;
259         });
260     }
262     function terminate() {
263         if (terminate_pending)
264             return exit_status;
265         terminate_pending = true;
266         if (setup_timer) {
267             setup_timer.cancel();
268             setup_timer = null;
269         }
270         cleanup_server();
271         cleanup_fd_sockets();
272         if (control_transport) {
273             switch (control_state) {
274             case CONTROL_SENT_KEY:
275                 control_send_terminate();
276                 break;
277             case CONTROL_CONNECTED:
278                 cleanup_control();
279                 break;
280                 /**
281                  * case CONTROL_SENDING_KEY: in this case once the key
282                  * is sent, the terminate_pending flag will be noticed
283                  * and control_send_terminate will be called, so nothing
284                  * more needs to be done here.
285                  */
286             }
287         }
288         return exit_status;
289     }
291     function finished() {
292         // Only call success_callback if terminate was not already called
293         if (!terminate_pending) {
294             terminate();
295             if (success_callback)
296                 success_callback(exit_status);
297         }
298     }
300     // Create server socket to listen for connections from the external helper program
301     try {
302         server = Cc['@mozilla.org/network/server-socket;1'].createInstance(Ci.nsIServerSocket);
304         var key_file = get_temporary_file("spawn_process_key.dat");
306         write_binary_file(key_file, key_file_data);
307         server.init(-1 /* choose a port automatically */,
308                     true /* bind to localhost only */,
309                     -1 /* select backlog size automatically */);
311         setup_timer = call_after_timeout(function () {
312             setup_timer = null;
313             if (control_state != CONTROL_SENT_KEY)
314                 fail("setup timeout");
315         }, spawn_process_helper_setup_timeout);
318         function wait_for_fd_sockets() {
319             var remaining_streams = total_fds * 2;
320             var timer = null;
321             function handler() {
322                 if (remaining_streams != null) {
323                     --remaining_streams;
324                     if (remaining_streams == 0) {
325                         if (timer)
326                             timer.cancel();
327                         finished();
328                     }
329                 }
330             }
331             for each (let f in registered_transports) {
332                 input_stream_async_wait(f.input, handler, false /* wait for closure */);
333                 output_stream_async_wait(f.output, handler, false /* wait for closure */);
334             }
335             if (fd_wait_timeout != null) {
336                 timer = call_after_timeout(function() {
337                     remaining_streams = null;
338                     finished();
339                 }, fd_wait_timeout);
340             }
341         }
343         var control_data = "";
345         function handle_control_input() {
346             if (terminate_pending)
347                 return;
348             try {
349                 let avail = control_input_stream.available();
350                 if (avail > 0) {
351                     control_data += control_binary_input_stream.readBytes(avail);
352                     var off = control_data.indexOf("\0");
353                     if (off >= 0) {
354                         let message = control_data.substring(0,off);
355                         exit_status = parseInt(message);
356                         cleanup_control();
357                         /* wait for all fd sockets to close? */
358                         if (total_fds > 0)
359                             wait_for_fd_sockets();
360                         else
361                             finished();
362                         return;
363                     }
364                 }
365                 input_stream_async_wait(control_input_stream, handle_control_input);
366             } catch (e) {
367                 // Control socket closed: terminate
368                 cleanup_control();
369                 fail(e);
370             }
371         }
373         var registered_fds = 0;
375         server.asyncListen(
376             {
377                 onSocketAccepted: function (server, transport) {
378                     unregistered_transports.push(transport);
379                     function remove_from_unregistered() {
380                         var i;
381                         i = unregistered_transports.indexOf(transport);
382                         if (i >= 0) {
383                             unregistered_transports.splice(i, 1);
384                             return true;
385                         }
386                         return false;
387                     }
388                     function close() {
389                         transport.close(0);
390                         remove_from_unregistered();
391                     }
392                     var received_data = "";
393                     var header_size = key_length + fd_spec_size;
395                     var in_stream, bin_stream, out_stream;
397                     function handle_input() {
398                         if (terminate_pending)
399                             return;
400                         try {
401                             let remaining = header_size - received_data.length;
402                             let avail = in_stream.available();
403                             if (avail > 0) {
404                                 if (avail > remaining)
405                                     avail = remaining;
406                                 received_data += bin_stream.readBytes(avail);
407                             }
408                             if (received_data.length < header_size) {
409                                 input_stream_async_wait(in_stream, handle_input);
410                                 return;
411                             } else {
412                                 if (received_data.substring(0, key_length) != client_key)
413                                     throw "Invalid key";
414                             }
415                         } catch (e) {
416                             close();
417                         }
418                         try {
419                             var fdspec = received_data.substring(key_length);
420                             if (fdspec.charCodeAt(0) == 0) {
422                                 // This is the control connection
423                                 if (control_transport)
424                                     throw "Control transport already exists";
425                                 control_transport = transport;
426                                 control_output_stream = out_stream;
427                                 control_input_stream = in_stream;
428                                 control_binary_input_stream = bin_stream;
429                                 remove_from_unregistered();
430                             } else {
431                                 var fd = parseInt(fdspec);
432                                 if (!fds.hasOwnProperty(fd) || (fd in registered_transports))
433                                     throw "Invalid fd";
434                                 bin_stream.close();
435                                 bin_stream = null;
436                                 registered_transports[fd] = {transport: transport,
437                                                              input: in_stream,
438                                                              output: out_stream};
439                                 ++registered_fds;
440                             }
441                             if (control_transport && registered_fds == total_fds) {
442                                 cleanup_server();
443                                 control_state = CONTROL_SENDING_KEY;
444                                 async_binary_write(control_output_stream, server_key,
445                                                    function () {
446                                                        control_state = CONTROL_SENT_KEY;
447                                                        if (setup_timer) {
448                                                            setup_timer.cancel();
449                                                            setup_timer = null;
450                                                        }
451                                                        if (terminate_pending) {
452                                                            control_send_terminate();
453                                                        } else {
454                                                            for (let i in fds) {
455                                                                let f = fds[i];
456                                                                let t = registered_transports[i];
457                                                                if ('input' in f)
458                                                                    f.input(t.input);
459                                                                if ('output' in f)
460                                                                    f.output(t.output);
461                                                            }
462                                                        }
463                                                    });
464                                 input_stream_async_wait(control_input_stream, handle_control_input);
465                             }
466                         } catch (e) {
467                             fail(e);
468                         }
469                     }
471                     try {
472                         in_stream = transport.openInputStream(Ci.nsITransport.OPEN_NON_BLOCKING, 0, 0);
473                         out_stream = transport.openOutputStream(Ci.nsITransport.OPEN_NON_BLOCKING, 0, 0);
474                         bin_stream = binary_input_stream(in_stream);
475                         input_stream_async_wait(in_stream, handle_input);
476                     } catch (e) {
477                         close();
478                     }
479                 },
480                 onStopListening: function (s, status) {
481                 }
482             });
484         spawn_process_internal(spawn_process_helper_program, [key_file.path, server.port], false);
485         return terminate;
486     } catch (e) {
487         terminate();
489         if ((e instanceof Ci.nsIException) && e.result == Cr.NS_ERROR_INVALID_POINTER) {
490             if (WINDOWS)
491                 throw new Error("Error spawning process: not yet supported on MS Windows");
492             else
493                 throw new Error("Error spawning process: conkeror-spawn-helper not found; try running \"make\"");
494         }
495         // Allow the exception to propagate to the caller
496         throw e;
497     }
501  * spawn_process_blind: spawn a process and forget about it
502  */
503 define_keywords("$cwd", "$fds");
504 function spawn_process_blind(program_name, args) {
505     keywords(arguments);
506     /* Check if we can use spawn_process_internal */
507     var cwd = arguments.$cwd;
508     var fds = arguments.$fds;
509     if (cwd == null && fds == null && args[0] == null)
510         spawn_process_internal(program_name, args.slice(1));
511     else {
512         spawn_process(program_name, args, cwd,
513                       null /* success callback */,
514                       null /* failure callback */,
515                       fds);
516     }
520 //  Keyword arguments: $cwd, $fds
521 function spawn_and_wait_for_process(program_name, args) {
522     keywords(arguments);
523     var cc = yield CONTINUATION;
524     spawn_process(program_name, args, arguments.$cwd,
525                   cc, cc.throw,
526                   arguments.$fds);
527     var result = yield SUSPEND;
528     yield co_return(result);
531 // Keyword arguments: $cwd, $fds
532 function shell_command_blind(cmd) {
533     keywords(arguments);
534     /* Check if we can use spawn_process_internal */
535     var cwd = arguments.$cwd;
536     var fds = arguments.$fds;
538     var program_name;
539     var args;
541     if (POSIX) {
542         var full_cmd;
543         if (cwd)
544             full_cmd = "cd \"" + shell_quote(cwd) + "\"; " + cmd;
545         else
546             full_cmd = cmd;
547         program_name = getenv("SHELL") || "/bin/sh";
548         args = [null, "-c", full_cmd];
549     } else {
550         var full_cmd;
551         if (cwd) {
552             full_cmd = "";
553             if (cwd.match(/[a-z]:/i)) {
554                 full_cmd += cwd.substring(0,2) + " && ";
555             }
556             full_cmd += "cd \"" + shell_quote(cwd) + "\" && " + cmd;
557         } else
558             full_cmd = cmd;
560         /* Need to convert the single command-line into a list of
561             * arguments that will then get converted back into a *
562             command-line by Mozilla. */
563         var out = [null, "/C"];
564         var cur_arg = "";
565         var quoting = false;
566         for (var i = 0; i < full_cmd.length; ++i) {
567             var ch = full_cmd[i];
568             if (ch == " ") {
569                 if (quoting) {
570                     cur_arg += ch;
571                 } else {
572                     out.push(cur_arg);
573                     cur_arg = "";
574                 }
575                 continue;
576             }
577             if (ch == "\"") {
578                 quoting = !quoting;
579                 continue;
580             }
581             cur_arg += ch;
582         }
583         if (cur_arg.length > 0)
584             out.push(cur_arg);
585         program_name = "cmd.exe";
586         args = out;
587     }
588     spawn_process_blind(program_name, args, $fds = arguments.$fds);
591 function substitute_shell_command_argument(cmdline, argument) {
592     if (!cmdline.match("{}"))
593         return cmdline + " \"" + shell_quote(argument) + "\"";
594     else
595         return cmdline.replace("{}", "\"" + shell_quote(argument) + "\"");
598 function shell_command_with_argument_blind(command, arg) {
599     shell_command_blind(substitute_shell_command_argument(command, arg), forward_keywords(arguments));
602 // Keyword arguments: $cwd, $fds
603 function shell_command(command) {
604     if (!POSIX)
605         throw new Error("shell_command: Your OS is not yet supported");
606     var result = yield spawn_and_wait_for_process(getenv("SHELL") || "/bin/sh",
607                                                   [null, "-c", command],
608                                                   forward_keywords(arguments));
609     yield co_return(result);
612 function shell_command_with_argument(command, arg) {
613     yield co_return((yield shell_command(substitute_shell_command_argument(command, arg), forward_keywords(arguments))));