2 * (C) Copyright 2007-2008 Jeremy Maitin-Shepard
4 * Use, modification, and distribution are subject to the terms specified in the
8 require("interactive.js");
12 function spawn_process_internal (program, args, blocking) {
13 var process = Cc["@mozilla.org/process/util;1"]
14 .createInstance(Ci.nsIProcess);
15 process.init(find_file_in_path(program));
16 return process.run(!!blocking, args, args.length);
19 var PATH_programs = null;
20 function get_shell_command_completer () {
21 if (PATH_programs == null) {
23 var file = Cc["@mozilla.org/file/local;1"]
24 .createInstance(Ci.nsILocalFile);
25 for (var i = 0, plen = PATH.length; i < plen; ++i) {
27 file.initWithPath(PATH[i]);
28 var entries = file.directoryEntries;
29 while (entries.hasMoreElements()) {
30 var entry = entries.getNext().QueryInterface(Ci.nsIFile);
31 PATH_programs.push(entry.leafName);
37 return prefix_completer($completions = PATH_programs,
38 $get_string = function (x) x);
42 minibuffer_auto_complete_preferences["shell-command"] = null;
44 /* FIXME: support a relative or full path as well as PATH commands */
45 define_keywords("$cwd");
46 minibuffer.prototype.read_shell_command = function () {
47 keywords(arguments, $history = "shell-command");
48 var prompt = arguments.$prompt || "Shell command [" + arguments.$cwd.path + "]:";
49 var result = yield this.read(
51 $history = "shell-command",
52 $auto_complete = "shell-command",
54 $validator = function (x, m) {
55 var s = x.replace(/^\s+|\s+$/g, '');
57 m.message("A blank shell command is not allowed.");
62 forward_keywords(arguments),
63 $completer = get_shell_command_completer());
64 yield co_return(result);
67 function find_spawn_helper () {
68 var f = file_locator_service.get("CurProcD", Ci.nsIFile);
69 f.append("conkeror-spawn-helper");
72 return find_file_in_path("conkeror-spawn-helper");
75 const STDIN_FILENO = 0;
76 const STDOUT_FILENO = 1;
77 const STDERR_FILENO = 2;
79 var spawn_process_helper_default_fd_wait_timeout = 1000;
80 var spawn_process_helper_setup_timeout = 2000;
84 * Specifies the full path to the program.
86 * An array of strings to pass as the arguments to the program. The
87 * first argument should be the program name. These strings must not
88 * have any NUL bytes in them.
90 * If non-null, must be an nsILocalFile. spawn_process will switch
91 * to this path before running the program.
92 * @param finished_callback
93 * Called with a single argument, the exit code of the process, as
94 * returned by the wait system call.
95 * @param failure_callback
96 * Called with a single argument, an exception, if one occurs.
98 * If non-null, must be an object with only non-negative integer
99 * properties set. Each such property specifies that the corresponding
100 * file descriptor in the spawned process should be redirected. Note
101 * that 0 corresponds to STDIN, 1 corresponds to STDOUT, and 2
102 * corresponds to STDERR. Note that every redirected file descriptor can
103 * be used for both input and output, although STDIN, STDOUT, and STDERR
104 * are typically used only unidirectionally. Each property must be an
105 * object itself, with an input and/or output property specifying
106 * callback functions that are called with an nsIAsyncInputStream or
107 * nsIAsyncOutputStream when the stream for that file descriptor is
109 * @param fd_wait_timeout
110 * Specifies the number of milliseconds to wait for the file descriptor
111 * redirection sockets to be closed after the control socket indicates
112 * the process has exited before they are closed forcefully. A negative
113 * value means to wait indefinitely. If fd_wait_timeout is null,
114 * spawn_process_helper_default_fd_wait_timeout is used instead.
116 * A function that can be called to prematurely terminate the spawned
119 function spawn_process (program_name, args, working_dir,
120 fds, fd_wait_timeout) {
122 let deferred = Promise.defer();
124 var spawn_process_helper_program = find_spawn_helper();
125 if (spawn_process_helper_program == null)
126 throw new Error("Error spawning process: conkeror-spawn-helper not found");
129 args[0] = (program_name instanceof Ci.nsIFile) ? program_name.path : program_name;
131 program_name = find_file_in_path(program_name).path;
133 const key_length = 100;
134 const fd_spec_size = 15;
139 if (fd_wait_timeout === undefined)
140 fd_wait_timeout = spawn_process_helper_default_fd_wait_timeout;
142 var unregistered_transports = [];
143 var registered_transports = [];
146 var setup_timer = null;
148 const CONTROL_CONNECTED = 0;
149 const CONTROL_SENDING_KEY = 1;
150 const CONTROL_SENT_KEY = 2;
152 var control_state = CONTROL_CONNECTED;
153 var terminate_pending = false;
155 var control_transport = null;
157 var control_binary_input_stream = null;
158 var control_output_stream = null, control_input_stream = null;
159 var exit_status = null;
163 // Make sure key does not have any 0 bytes in it.
164 for (let i = 0; i < key_length; ++i)
165 client_key += String.fromCharCode(Math.floor(Math.random() * 255) + 1);
167 // Make sure key does not have any 0 bytes in it.
168 for (let i = 0; i < key_length; ++i)
169 server_key += String.fromCharCode(Math.floor(Math.random() * 255) + 1);
171 var key_file_fd_data = "";
173 // This is the total number of redirected file descriptors.
174 var total_client_fds = 0;
176 // This is the total number of redirected file descriptors that will use a socket connection.
180 if (fds.hasOwnProperty(i)) {
181 if (fds[i] == null) {
185 key_file_fd_data += i + "\0";
188 if (fd.perms == null)
190 key_file_fd_data += fd.file + "\0" + fd.mode + "\0" + fd.perms + "\0";
191 delete fds[i]; // Remove it from fds, as we won't need to work with it anymore
194 key_file_fd_data += "\0";
199 var key_file_data = client_key + "\0" + server_key + "\0" + program_name + "\0" +
200 (working_dir != null ? working_dir.path : "") + "\0" +
202 args.join("\0") + "\0" +
203 total_client_fds + "\0" + key_file_fd_data;
206 if (!terminate_pending) {
212 function cleanup_server () {
217 for (let i in unregistered_transports) {
218 unregistered_transports[i].close(0);
219 delete unregistered_transports[i];
223 function cleanup_fd_sockets () {
224 for (let i in registered_transports) {
225 registered_transports[i].transport.close(0);
226 delete registered_transports[i];
230 function cleanup_control () {
231 if (control_transport) {
232 control_binary_input_stream.close();
233 control_binary_input_stream = null;
234 control_transport.close(0);
235 control_transport = null;
236 control_input_stream = null;
237 control_output_stream = null;
241 function control_send_terminate () {
242 control_input_stream = null;
243 control_binary_input_stream.close();
244 control_binary_input_stream = null;
245 async_binary_write(control_output_stream, "\0", function () {
246 control_output_stream = null;
247 control_transport.close(0);
248 control_transport = null;
252 function terminate () {
253 if (terminate_pending)
255 terminate_pending = true;
257 setup_timer.cancel();
261 cleanup_fd_sockets();
262 if (control_transport) {
263 switch (control_state) {
264 case CONTROL_SENT_KEY:
265 control_send_terminate();
267 case CONTROL_CONNECTED:
271 * case CONTROL_SENDING_KEY: in this case once the key
272 * is sent, the terminate_pending flag will be noticed
273 * and control_send_terminate will be called, so nothing
274 * more needs to be done here.
281 function canceler (e) {
282 if (!terminate_pending) {
288 function finished () {
289 // Only call success_callback if terminate was not already called
290 if (!terminate_pending) {
291 deferred.resolve(exit_status);
296 // Create server socket to listen for connections from the external helper program
298 server = Cc['@mozilla.org/network/server-socket;1']
299 .createInstance(Ci.nsIServerSocket);
301 var key_file = get_temporary_file("conkeror-spawn-helper-key.dat");
303 write_binary_file(key_file, key_file_data);
304 server.init(-1 /* choose a port automatically */,
305 true /* bind to localhost only */,
306 -1 /* select backlog size automatically */);
308 setup_timer = call_after_timeout(function () {
310 if (control_state != CONTROL_SENT_KEY)
311 fail("setup timeout");
312 }, spawn_process_helper_setup_timeout);
314 function wait_for_fd_sockets () {
315 var remaining_streams = total_fds * 2;
317 function handler () {
318 if (remaining_streams != null) {
320 if (remaining_streams == 0) {
327 for each (let f in registered_transports) {
328 input_stream_async_wait(f.input, handler, false /* wait for closure */);
329 output_stream_async_wait(f.output, handler, false /* wait for closure */);
331 if (fd_wait_timeout != null) {
332 timer = call_after_timeout(function() {
333 remaining_streams = null;
339 var control_data = "";
341 function handle_control_input () {
342 if (terminate_pending)
345 let avail = control_input_stream.available();
347 control_data += control_binary_input_stream.readBytes(avail);
348 var off = control_data.indexOf("\0");
350 let message = control_data.substring(0,off);
351 exit_status = parseInt(message);
353 /* wait for all fd sockets to close? */
355 wait_for_fd_sockets();
361 input_stream_async_wait(control_input_stream, handle_control_input);
363 // Control socket closed: terminate
369 var registered_fds = 0;
373 onSocketAccepted: function (server, transport) {
374 unregistered_transports.push(transport);
375 function remove_from_unregistered () {
377 i = unregistered_transports.indexOf(transport);
379 unregistered_transports.splice(i, 1);
386 remove_from_unregistered();
388 var received_data = "";
389 var header_size = key_length + fd_spec_size;
391 var in_stream, bin_stream, out_stream;
393 function handle_input () {
394 if (terminate_pending)
397 let remaining = header_size - received_data.length;
398 let avail = in_stream.available();
400 if (avail > remaining)
402 received_data += bin_stream.readBytes(avail);
404 if (received_data.length < header_size) {
405 input_stream_async_wait(in_stream, handle_input);
408 if (received_data.substring(0, key_length) != client_key)
415 var fdspec = received_data.substring(key_length);
416 if (fdspec.charCodeAt(0) == 0) {
418 // This is the control connection
419 if (control_transport)
420 throw "Control transport already exists";
421 control_transport = transport;
422 control_output_stream = out_stream;
423 control_input_stream = in_stream;
424 control_binary_input_stream = bin_stream;
425 remove_from_unregistered();
427 var fd = parseInt(fdspec);
428 if (!fds.hasOwnProperty(fd) || (fd in registered_transports))
430 remove_from_unregistered();
432 registered_transports[fd] = {transport: transport,
437 if (control_transport && registered_fds == total_fds) {
439 control_state = CONTROL_SENDING_KEY;
440 async_binary_write(control_output_stream, server_key,
444 control_state = CONTROL_SENT_KEY;
446 setup_timer.cancel();
449 if (terminate_pending) {
450 control_send_terminate();
454 let t = registered_transports[i];
466 input_stream_async_wait(control_input_stream, handle_control_input);
474 in_stream = transport.openInputStream(Ci.nsITransport.OPEN_NON_BLOCKING, 0, 0);
475 out_stream = transport.openOutputStream(Ci.nsITransport.OPEN_NON_BLOCKING, 0, 0);
476 bin_stream = binary_input_stream(in_stream);
477 input_stream_async_wait(in_stream, handle_input);
482 onStopListening: function (s, status) {
486 spawn_process_internal(spawn_process_helper_program, [key_file.path, server.port], false);
487 return make_cancelable(deferred.promise, canceler);
491 if ((e instanceof Ci.nsIException) && e.result == Cr.NS_ERROR_INVALID_POINTER) {
493 throw new Error("Error spawning process: not yet supported on MS Windows");
495 throw new Error("Error spawning process: conkeror-spawn-helper not found");
497 // Allow the exception to propagate to the caller
503 * spawn_process_blind: spawn a process and forget about it
505 define_keywords("$cwd", "$fds");
506 function spawn_process_blind (program_name, args) {
508 /* Check if we can use spawn_process_internal */
509 var cwd = arguments.$cwd;
510 var fds = arguments.$fds;
511 if (cwd == null && fds == null && args[0] == null)
512 spawn_process_internal(program_name, args.slice(1));
514 spawn_process(program_name, args, cwd, fds);
519 // Keyword arguments: $cwd, $fds
520 function spawn_and_wait_for_process (program_name, args) {
521 keywords(arguments, $cwd = null, $fds = null);
522 let result = yield spawn_process(program_name, args, arguments.$cwd,
524 yield co_return(result);
527 // Keyword arguments: $cwd, $fds
528 function shell_command_blind (cmd) {
530 /* Check if we can use spawn_process_internal */
531 var cwd = arguments.$cwd;
532 var fds = arguments.$fds;
540 full_cmd = "cd \"" + shell_quote(cwd.path) + "\"; " + cmd;
543 program_name = getenv("SHELL") || "/bin/sh";
544 args = [null, "-c", full_cmd];
549 if (cwd.path.match(/[a-z]:/i)) {
550 full_cmd += cwd.path.substring(0,2) + " && ";
552 full_cmd += "cd \"" + shell_quote(cwd.path) + "\" && " + cmd;
556 /* Need to convert the single command-line into a list of
557 * arguments that will then get converted back into a *
558 command-line by Mozilla. */
559 var out = [null, "/C"];
562 for (var i = 0; i < full_cmd.length; ++i) {
563 var ch = full_cmd[i];
579 if (cur_arg.length > 0)
581 program_name = "cmd.exe";
584 spawn_process_blind(program_name, args, $fds = arguments.$fds);
587 function substitute_shell_command_argument (cmdline, argument) {
588 if (!cmdline.match("{}"))
589 return cmdline + " \"" + shell_quote(argument) + "\"";
591 return cmdline.replace("{}", "\"" + shell_quote(argument) + "\"");
594 function shell_command_with_argument_blind (command, arg) {
595 shell_command_blind(substitute_shell_command_argument(command, arg), forward_keywords(arguments));
600 * $cwd: The current working directory for the process.
601 * $fds: File descriptors to use.
603 function shell_command (command) {
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))));
616 provide("spawn-process");