Replace uses of co_call/continuation API with uses of spawn/Promise API
[conkeror.git] / modules / spawn-process.js
blobb43aeb321d5bbcc7c8deb3629ad4d444697fe09e
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");
10 require("env.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) {
22         PATH_programs = [];
23         var file = Cc["@mozilla.org/file/local;1"]
24             .createInstance(Ci.nsILocalFile);
25         for (var i = 0, plen = PATH.length; i < plen; ++i) {
26             try {
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);
32                 }
33             } catch (e) {}
34         }
35         PATH_programs.sort();
36     }
37     return prefix_completer($completions = PATH_programs,
38                             $get_string = function (x) x);
41 // use default
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(
50         $prompt = prompt,
51         $history = "shell-command",
52         $auto_complete = "shell-command",
53         $select,
54         $validator = function (x, m) {
55             var s = x.replace(/^\s+|\s+$/g, '');
56             if (s.length == 0) {
57                 m.message("A blank shell command is not allowed.");
58                 return false;
59             }
60             return true;
61         },
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");
70     if (f.exists())
71         return f;
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;
82 /**
83  * @param program_name
84  *        Specifies the full path to the program.
85  * @param args
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.
89  * @param working_dir       
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.
97  * @param fds
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
108  *        available.
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.
115  * @return
116  *        A function that can be called to prematurely terminate the spawned
117  *        process.
118  */
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");
127     args = args.slice();
128     if (args[0] == null)
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;
136     if (fds == null)
137         fds = {};
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 = [];
145     var server = null;
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;
161     var client_key = "";
162     var server_key = "";
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.
177     var total_fds = 0;
179     for (let i in fds) {
180         if (fds.hasOwnProperty(i)) {
181             if (fds[i] == null) {
182                 delete fds[i];
183                 continue;
184             }
185             key_file_fd_data += i + "\0";
186             let fd = fds[i];
187             if ('file' in fd) {
188                 if (fd.perms == null)
189                     fd.perms = 0666;
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
192             } else {
193                 ++total_fds;
194                 key_file_fd_data += "\0";
195             }
196             ++total_client_fds;
197         }
198     }
199     var key_file_data = client_key + "\0" + server_key + "\0" + program_name + "\0" +
200         (working_dir != null ? working_dir.path : "") + "\0" +
201         args.length + "\0" +
202         args.join("\0") + "\0" +
203         total_client_fds + "\0" + key_file_fd_data;
205     function fail (e) {
206         if (!terminate_pending) {
207             deferred.reject(e);
208             terminate();
209         }
210     }
212     function cleanup_server () {
213         if (server) {
214             server.close();
215             server = null;
216         }
217         for (let i in unregistered_transports) {
218             unregistered_transports[i].close(0);
219             delete unregistered_transports[i];
220         }
221     }
223     function cleanup_fd_sockets () {
224         for (let i in registered_transports) {
225             registered_transports[i].transport.close(0);
226             delete registered_transports[i];
227         }
228     }
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;
238         }
239     }
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;
249         });
250     }
252     function terminate () {
253         if (terminate_pending)
254             return exit_status;
255         terminate_pending = true;
256         if (setup_timer) {
257             setup_timer.cancel();
258             setup_timer = null;
259         }
260         cleanup_server();
261         cleanup_fd_sockets();
262         if (control_transport) {
263             switch (control_state) {
264             case CONTROL_SENT_KEY:
265                 control_send_terminate();
266                 break;
267             case CONTROL_CONNECTED:
268                 cleanup_control();
269                 break;
270                 /**
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.
275                  */
276             }
277         }
278         return exit_status;
279     }
281     function canceler (e) {
282         if (!terminate_pending) {
283             deferred.reject(e);
284             terminate();
285         }
286     }
288     function finished () {
289         // Only call success_callback if terminate was not already called
290         if (!terminate_pending) {
291             deferred.resolve(exit_status);
292             terminate();
293         }
294     }
296     // Create server socket to listen for connections from the external helper program
297     try {
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 () {
309             setup_timer = null;
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;
316             var timer = null;
317             function handler () {
318                 if (remaining_streams != null) {
319                     --remaining_streams;
320                     if (remaining_streams == 0) {
321                         if (timer)
322                             timer.cancel();
323                         finished();
324                     }
325                 }
326             }
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 */);
330             }
331             if (fd_wait_timeout != null) {
332                 timer = call_after_timeout(function() {
333                     remaining_streams = null;
334                     finished();
335                 }, fd_wait_timeout);
336             }
337         }
339         var control_data = "";
341         function handle_control_input () {
342             if (terminate_pending)
343                 return;
344             try {
345                 let avail = control_input_stream.available();
346                 if (avail > 0) {
347                     control_data += control_binary_input_stream.readBytes(avail);
348                     var off = control_data.indexOf("\0");
349                     if (off >= 0) {
350                         let message = control_data.substring(0,off);
351                         exit_status = parseInt(message);
352                         cleanup_control();
353                         /* wait for all fd sockets to close? */
354                         if (total_fds > 0)
355                             wait_for_fd_sockets();
356                         else
357                             finished();
358                         return;
359                     }
360                 }
361                 input_stream_async_wait(control_input_stream, handle_control_input);
362             } catch (e) {
363                 // Control socket closed: terminate
364                 cleanup_control();
365                 fail(e);
366             }
367         }
369         var registered_fds = 0;
371         server.asyncListen(
372             {
373                 onSocketAccepted: function (server, transport) {
374                     unregistered_transports.push(transport);
375                     function remove_from_unregistered () {
376                         var i;
377                         i = unregistered_transports.indexOf(transport);
378                         if (i >= 0) {
379                             unregistered_transports.splice(i, 1);
380                             return true;
381                         }
382                         return false;
383                     }
384                     function close () {
385                         transport.close(0);
386                         remove_from_unregistered();
387                     }
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)
395                             return;
396                         try {
397                             let remaining = header_size - received_data.length;
398                             let avail = in_stream.available();
399                             if (avail > 0) {
400                                 if (avail > remaining)
401                                     avail = remaining;
402                                 received_data += bin_stream.readBytes(avail);
403                             }
404                             if (received_data.length < header_size) {
405                                 input_stream_async_wait(in_stream, handle_input);
406                                 return;
407                             } else {
408                                 if (received_data.substring(0, key_length) != client_key)
409                                     throw "Invalid key";
410                             }
411                         } catch (e) {
412                             close();
413                         }
414                         try {
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();
426                             } else {
427                                 var fd = parseInt(fdspec);
428                                 if (!fds.hasOwnProperty(fd) || (fd in registered_transports))
429                                     throw "Invalid fd";
430                                 remove_from_unregistered();
431                                 bin_stream = null;
432                                 registered_transports[fd] = {transport: transport,
433                                                              input: in_stream,
434                                                              output: out_stream};
435                                 ++registered_fds;
436                             }
437                             if (control_transport && registered_fds == total_fds) {
438                                 cleanup_server();
439                                 control_state = CONTROL_SENDING_KEY;
440                                 async_binary_write(control_output_stream, server_key,
441                                                    function (error) {
442                                                        if (error != null)
443                                                            fail(error);
444                                                        control_state = CONTROL_SENT_KEY;
445                                                        if (setup_timer) {
446                                                            setup_timer.cancel();
447                                                            setup_timer = null;
448                                                        }
449                                                        if (terminate_pending) {
450                                                            control_send_terminate();
451                                                        } else {
452                                                            for (let i in fds) {
453                                                                let f = fds[i];
454                                                                let t = registered_transports[i];
455                                                                if ('input' in f)
456                                                                    f.input(t.input);
457                                                                else
458                                                                    t.input.close();
459                                                                if ('output' in f)
460                                                                    f.output(t.output);
461                                                                else
462                                                                    t.output.close();
463                                                            }
464                                                        }
465                                                    });
466                                 input_stream_async_wait(control_input_stream, handle_control_input);
467                             }
468                         } catch (e) {
469                             fail(e);
470                         }
471                     }
473                     try {
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);
478                     } catch (e) {
479                         close();
480                     }
481                 },
482                 onStopListening: function (s, status) {
483                 }
484             });
486         spawn_process_internal(spawn_process_helper_program, [key_file.path, server.port], false);
487         return make_cancelable(deferred.promise, canceler);
488     } catch (e) {
489         terminate();
491         if ((e instanceof Ci.nsIException) && e.result == Cr.NS_ERROR_INVALID_POINTER) {
492             if (WINDOWS)
493                 throw new Error("Error spawning process: not yet supported on MS Windows");
494             else
495                 throw new Error("Error spawning process: conkeror-spawn-helper not found");
496         }
497         // Allow the exception to propagate to the caller
498         throw e;
499     }
503  * spawn_process_blind: spawn a process and forget about it
504  */
505 define_keywords("$cwd", "$fds");
506 function spawn_process_blind (program_name, args) {
507     keywords(arguments);
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));
513     else {
514         spawn_process(program_name, args, cwd, fds);
515     }
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,
523                                      arguments.$fds);
524     yield co_return(result);
527 // Keyword arguments: $cwd, $fds
528 function shell_command_blind (cmd) {
529     keywords(arguments);
530     /* Check if we can use spawn_process_internal */
531     var cwd = arguments.$cwd;
532     var fds = arguments.$fds;
534     var program_name;
535     var args;
537     if (POSIX) {
538         var full_cmd;
539         if (cwd)
540             full_cmd = "cd \"" + shell_quote(cwd.path) + "\"; " + cmd;
541         else
542             full_cmd = cmd;
543         program_name = getenv("SHELL") || "/bin/sh";
544         args = [null, "-c", full_cmd];
545     } else {
546         var full_cmd;
547         if (cwd) {
548             full_cmd = "";
549             if (cwd.path.match(/[a-z]:/i)) {
550                 full_cmd += cwd.path.substring(0,2) + " && ";
551             }
552             full_cmd += "cd \"" + shell_quote(cwd.path) + "\" && " + cmd;
553         } else
554             full_cmd = 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"];
560         var cur_arg = "";
561         var quoting = false;
562         for (var i = 0; i < full_cmd.length; ++i) {
563             var ch = full_cmd[i];
564             if (ch == " ") {
565                 if (quoting) {
566                     cur_arg += ch;
567                 } else {
568                     out.push(cur_arg);
569                     cur_arg = "";
570                 }
571                 continue;
572             }
573             if (ch == "\"") {
574                 quoting = !quoting;
575                 continue;
576             }
577             cur_arg += ch;
578         }
579         if (cur_arg.length > 0)
580             out.push(cur_arg);
581         program_name = "cmd.exe";
582         args = out;
583     }
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) + "\"";
590     else
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));
599  * Keyword arguments:
600  * $cwd: The current working directory for the process.
601  * $fds: File descriptors to use.
602  */
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))));
616 provide("spawn-process");