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");
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) {
23 var file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsILocalFile);
24 if (!path_component_regexp.test(name)) {
27 file.initWithPath(name);
34 for (var i = 0; i < PATH.length; ++i) {
36 file.initWithPath(PATH[i]);
37 file.appendRelativePath(name);
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) {
56 var file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsILocalFile);
57 for (var i = 0; i < PATH.length; ++i) {
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);
70 return prefix_completer($completions = PATH_programs,
71 $get_string = function (x) { return x; });
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(
84 $history = "shell-command",
85 $auto_complete = "shell-command",
87 $validator = function (x, m) {
88 var s = x.replace(/^\s+|\s+$/g, '');
90 m.message("A blank shell command is not allowed.");
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.
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.
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.
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
138 * A function that can be called to prematurely terminate the spawned process.
140 function spawn_process(program_name, args, working_dir,
141 success_callback, failure_callback, fds,
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;
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 = [];
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;
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.
195 if (fds.hasOwnProperty(i)) {
196 key_file_fd_data += i + "\0";
199 if (fd.perms == null)
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
208 var key_file_data = client_key + "\0" + server_key + "\0" + program_name + "\0" +
209 (working_dir != null ? working_dir : "") + "\0" +
211 args.join("\0") + "\0" +
212 total_client_fds + "\0" + key_file_fd_data;
215 if (!terminate_pending) {
217 if (failure_callback)
222 function cleanup_server() {
227 for (let i in unregistered_transports) {
228 unregistered_transports[i].close(0);
229 delete unregistered_transports[i];
233 function cleanup_fd_sockets() {
234 for (let i in registered_transports) {
235 registered_transports[i].transport.close(0);
236 delete registered_transports[i];
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;
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;
262 function terminate() {
263 if (terminate_pending)
265 terminate_pending = true;
267 setup_timer.cancel();
271 cleanup_fd_sockets();
272 if (control_transport) {
273 switch (control_state) {
274 case CONTROL_SENT_KEY:
275 control_send_terminate();
277 case CONTROL_CONNECTED:
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.
291 function finished() {
292 // Only call success_callback if terminate was not already called
293 if (!terminate_pending) {
295 if (success_callback)
296 success_callback(exit_status);
300 // Create server socket to listen for connections from the external helper program
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 () {
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;
322 if (remaining_streams != null) {
324 if (remaining_streams == 0) {
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 */);
335 if (fd_wait_timeout != null) {
336 timer = call_after_timeout(function() {
337 remaining_streams = null;
343 var control_data = "";
345 function handle_control_input() {
346 if (terminate_pending)
349 let avail = control_input_stream.available();
351 control_data += control_binary_input_stream.readBytes(avail);
352 var off = control_data.indexOf("\0");
354 let message = control_data.substring(0,off);
355 exit_status = parseInt(message);
357 /* wait for all fd sockets to close? */
359 wait_for_fd_sockets();
365 input_stream_async_wait(control_input_stream, handle_control_input);
367 // Control socket closed: terminate
373 var registered_fds = 0;
377 onSocketAccepted: function (server, transport) {
378 unregistered_transports.push(transport);
379 function remove_from_unregistered() {
381 i = unregistered_transports.indexOf(transport);
383 unregistered_transports.splice(i, 1);
390 remove_from_unregistered();
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)
401 let remaining = header_size - received_data.length;
402 let avail = in_stream.available();
404 if (avail > remaining)
406 received_data += bin_stream.readBytes(avail);
408 if (received_data.length < header_size) {
409 input_stream_async_wait(in_stream, handle_input);
412 if (received_data.substring(0, key_length) != client_key)
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();
431 var fd = parseInt(fdspec);
432 if (!fds.hasOwnProperty(fd) || (fd in registered_transports))
436 registered_transports[fd] = {transport: transport,
441 if (control_transport && registered_fds == total_fds) {
443 control_state = CONTROL_SENDING_KEY;
444 async_binary_write(control_output_stream, server_key,
446 control_state = CONTROL_SENT_KEY;
448 setup_timer.cancel();
451 if (terminate_pending) {
452 control_send_terminate();
456 let t = registered_transports[i];
464 input_stream_async_wait(control_input_stream, handle_control_input);
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);
480 onStopListening: function (s, status) {
484 spawn_process_internal(spawn_process_helper_program, [key_file.path, server.port], false);
489 if ((e instanceof Ci.nsIException) && e.result == Cr.NS_ERROR_INVALID_POINTER) {
491 throw new Error("Error spawning process: not yet supported on MS Windows");
493 throw new Error("Error spawning process: conkeror-spawn-helper not found; try running \"make\"");
495 // Allow the exception to propagate to the caller
501 * spawn_process_blind: spawn a process and forget about it
503 define_keywords("$cwd", "$fds");
504 function spawn_process_blind(program_name, args) {
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));
512 spawn_process(program_name, args, cwd,
513 null /* success callback */,
514 null /* failure callback */,
520 // Keyword arguments: $cwd, $fds
521 function spawn_and_wait_for_process(program_name, args) {
523 var cc = yield CONTINUATION;
524 spawn_process(program_name, args, arguments.$cwd,
527 var result = yield SUSPEND;
528 yield co_return(result);
531 // Keyword arguments: $cwd, $fds
532 function shell_command_blind(cmd) {
534 /* Check if we can use spawn_process_internal */
535 var cwd = arguments.$cwd;
536 var fds = arguments.$fds;
544 full_cmd = "cd \"" + shell_quote(cwd) + "\"; " + cmd;
547 program_name = getenv("SHELL") || "/bin/sh";
548 args = [null, "-c", full_cmd];
553 if (cwd.match(/[a-z]:/i)) {
554 full_cmd += cwd.substring(0,2) + " && ";
556 full_cmd += "cd \"" + shell_quote(cwd) + "\" && " + 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"];
566 for (var i = 0; i < full_cmd.length; ++i) {
567 var ch = full_cmd[i];
583 if (cur_arg.length > 0)
585 program_name = "cmd.exe";
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) + "\"";
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) {
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))));