@ 261105.16
current
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

#include "env-inl.h"
#include "node_errors.h"
#include "node_external_reference.h"
#include "permission/permission.h"
#include "stream_base-inl.h"
#include "stream_wrap.h"
#include "util-inl.h"

#include <climits>
#include <cstdlib>
#include <cstring>

namespace node {

using v8::Array;
using v8::Context;
using v8::FunctionCallbackInfo;
using v8::FunctionTemplate;
using v8::HandleScope;
using v8::Int32;
using v8::Integer;
using v8::Isolate;
using v8::Just;
using v8::JustVoid;
using v8::Local;
using v8::Maybe;
using v8::Nothing;
using v8::Number;
using v8::Object;
using v8::String;
using v8::Uint32;
using v8::Value;

namespace {

enum ProcessFlags : uint32_t {
  kProcessFlagNone = 0,
  kProcessFlagDetached = 1 << 0,
  kProcessFlagWindowsHide = 1 << 1,
  kProcessFlagWindowsVerbatimArguments = 1 << 2,
};

class ProcessWrap : public HandleWrap {
 public:
  static void Initialize(Local<Object> target,
                         Local<Value> unused,
                         Local<Context> context,
                         void* priv) {
    Environment* env = Environment::GetCurrent(context);
    Isolate* isolate = env->isolate();
    Local<FunctionTemplate> constructor = NewFunctionTemplate(isolate, New);
    constructor->InstanceTemplate()->SetInternalFieldCount(
        ProcessWrap::kInternalFieldCount);

    constructor->Inherit(HandleWrap::GetConstructorTemplate(env));

    SetProtoMethod(isolate, constructor, "spawn", Spawn);
    SetProtoMethod(isolate, constructor, "kill", Kill);

    SetConstructorFunction(context, target, "Process", constructor);
    SetMethodNoSideEffect(context, target, "getEnvPairs", GetEnvPairs);

    Local<Object> constants = Object::New(isolate);
    NODE_DEFINE_CONSTANT(constants, kProcessFlagDetached);
    NODE_DEFINE_CONSTANT(constants, kProcessFlagWindowsHide);
    NODE_DEFINE_CONSTANT(constants, kProcessFlagWindowsVerbatimArguments);
    target->Set(context, env->constants_string(), constants).Check();
  }

  static void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
    registry->Register(New);
    registry->Register(Spawn);
    registry->Register(Kill);
    registry->Register(GetEnvPairs);
  }

  SET_NO_MEMORY_INFO()
  SET_MEMORY_INFO_NAME(ProcessWrap)
  SET_SELF_SIZE(ProcessWrap)

 private:
  static void New(const FunctionCallbackInfo<Value>& args) {
    // This constructor should not be exposed to public javascript.
    // Therefore we assert that we are not trying to call this as a
    // normal function.
    CHECK(args.IsConstructCall());
    Environment* env = Environment::GetCurrent(args);
    new ProcessWrap(env, args.This());
  }

  ProcessWrap(Environment* env, Local<Object> object)
      : HandleWrap(env,
                   object,
                   reinterpret_cast<uv_handle_t*>(&process_),
                   AsyncWrap::PROVIDER_PROCESSWRAP) {
    process_.pid = 0;
    MarkAsUninitialized();
  }

  static Maybe<uv_stream_t*> StreamForWrap(Environment* env,
                                           Local<Object> stdio) {
    Local<String> handle_key = env->handle_string();
    // This property has always been set by JS land if we are in this code path.
    Local<Value> val;
    if (!stdio->Get(env->context(), handle_key).ToLocal(&val)) {
      return Nothing<uv_stream_t*>();
    }
    Local<Object> handle = val.As<Object>();

    uv_stream_t* stream = LibuvStreamWrap::From(env, handle)->stream();
    CHECK_NOT_NULL(stream);
    return Just(stream);
  }

  static Maybe<void> ParseStdioOptions(
      Environment* env,
      Local<Value> stdios_val,
      std::vector<uv_stdio_container_t>* options_stdio) {
    Local<Context> context = env->context();
    if (!stdios_val->IsArray()) {
      THROW_ERR_INVALID_ARG_TYPE(env, "options.stdio must be an array");
      return Nothing<void>();
    }
    Local<Array> stdios = stdios_val.As<Array>();

    uint32_t len = stdios->Length();
    options_stdio->resize(len);

    for (uint32_t i = 0; i < len; i++) {
      Local<Value> val;
      if (!stdios->Get(context, i).ToLocal(&val)) {
        return Nothing<void>();
      }
      Local<Object> stdio = val.As<Object>();
      Local<Value> type;
      if (!stdio->Get(context, env->type_string()).ToLocal(&type)) {
        return Nothing<void>();
      }

      if (type->StrictEquals(env->ignore_string())) {
        (*options_stdio)[i].flags = UV_IGNORE;
      } else if (type->StrictEquals(env->pipe_string())) {
        (*options_stdio)[i].flags = static_cast<uv_stdio_flags>(
            UV_CREATE_PIPE | UV_READABLE_PIPE | UV_WRITABLE_PIPE);
        if (!StreamForWrap(env, stdio).To(&(*options_stdio)[i].data.stream)) {
          return Nothing<void>();
        }
      } else if (type->StrictEquals(env->overlapped_string())) {
        (*options_stdio)[i].flags =
            static_cast<uv_stdio_flags>(UV_CREATE_PIPE | UV_READABLE_PIPE |
                                        UV_WRITABLE_PIPE | UV_OVERLAPPED_PIPE);
        if (!StreamForWrap(env, stdio).To(&(*options_stdio)[i].data.stream)) {
          return Nothing<void>();
        }
      } else if (type->StrictEquals(env->wrap_string())) {
        (*options_stdio)[i].flags = UV_INHERIT_STREAM;
        if (!StreamForWrap(env, stdio).To(&(*options_stdio)[i].data.stream)) {
          return Nothing<void>();
        }
      } else {
        Local<String> fd_key = env->fd_string();
        Local<Value> fd_value;
        if (!stdio->Get(context, fd_key).ToLocal(&fd_value)) {
          return Nothing<void>();
        }
        CHECK(fd_value->IsNumber());
        int fd = FromV8Value<int>(fd_value);
        (*options_stdio)[i].flags = UV_INHERIT_FD;
        (*options_stdio)[i].data.fd = fd;
      }
    }
    return JustVoid();
  }

  static void Spawn(const FunctionCallbackInfo<Value>& args) {
    Environment* env = Environment::GetCurrent(args);
    Local<Context> context = env->context();
    ProcessWrap* wrap;
    ASSIGN_OR_RETURN_UNWRAP(&wrap, args.This());
    int err = 0;

    uv_process_options_t options;
    memset(&options, 0, sizeof(uv_process_options_t));

    options.exit_cb = OnExit;

    // args[0] file
    CHECK(args[0]->IsString());
    node::Utf8Value file(env->isolate(), args[0]);
    options.file = *file;

    THROW_IF_INSUFFICIENT_PERMISSIONS(
        env, permission::PermissionScope::kChildProcess, file.ToStringView());

    // args[6] uid
    Local<Value> uid_v = args[6];
    if (!uid_v->IsUndefined() && !uid_v->IsNull()) {
      CHECK(uid_v->IsInt32());
      const int32_t uid = uid_v.As<Int32>()->Value();
      options.flags |= UV_PROCESS_SETUID;
      options.uid = static_cast<uv_uid_t>(uid);
    }

    // args[7] gid
    Local<Value> gid_v = args[7];
    if (!gid_v->IsUndefined() && !gid_v->IsNull()) {
      CHECK(gid_v->IsInt32());
      const int32_t gid = gid_v.As<Int32>()->Value();
      options.flags |= UV_PROCESS_SETGID;
      options.gid = static_cast<uv_gid_t>(gid);
    }

    // Undocumented feature of Win32 CreateProcess API allows spawning
    // batch files directly but is potentially insecure because arguments
    // are not escaped (and sometimes cannot be unambiguously escaped),
    // hence why they are rejected here.
#ifdef _WIN32
    if (IsWindowsBatchFile(options.file))
      err = UV_EINVAL;
#endif

    // args[1] args
    std::vector<char*> options_args;
    std::vector<std::string> args_vals;
    if (args[1]->IsArray()) {
      Local<Array> js_argv = args[1].As<Array>();
      int argc = js_argv->Length();
      CHECK_LT(argc, INT_MAX);  // Check for overflow.
      args_vals.reserve(argc);
      for (int i = 0; i < argc; i++) {
        Local<Value> val;
        if (!js_argv->Get(context, i).ToLocal(&val)) {
          return;
        }
        node::Utf8Value arg(env->isolate(), val);
        args_vals.emplace_back(arg.ToString());
      }
      options_args.resize(args_vals.size() + 1);
      for (size_t i = 0; i < args_vals.size(); i++) {
        options_args[i] = const_cast<char*>(args_vals[i].c_str());
        CHECK_NOT_NULL(options_args[i]);
      }
      options_args.back() = nullptr;
      options.args = options_args.data();
    }

    // args[2] cwd
    node::Utf8Value cwd(env->isolate(),
                        args[2]->IsString() ? args[2] : Local<Value>());
    if (cwd.length() > 0) {
      options.cwd = *cwd;
    }

    // args[3] envPairs
    std::vector<char*> options_env;
    std::vector<std::string> env_vals;
    if (args[3]->IsArray()) {
      Local<Array> env_opt = args[3].As<Array>();
      int envc = env_opt->Length();
      CHECK_LT(envc, INT_MAX);            // Check for overflow.
      env_vals.reserve(envc);
      for (int i = 0; i < envc; i++) {
        Local<Value> val;
        if (!env_opt->Get(context, i).ToLocal(&val)) {
          return;
        }
        node::Utf8Value pair(env->isolate(), val);
        env_vals.emplace_back(pair.ToString());
      }
      options_env.resize(env_vals.size() + 1);
      for (size_t i = 0; i < env_vals.size(); i++) {
        options_env[i] = const_cast<char*>(env_vals[i].c_str());
        CHECK_NOT_NULL(options_env[i]);
      }
      options_env.back() = nullptr;
      options.env = options_env.data();
    }

    // args[4] stdio
    std::vector<uv_stdio_container_t> options_stdio;
    if (ParseStdioOptions(env, args[4], &options_stdio).IsNothing()) {
      return;
    }
    options.stdio = options_stdio.data();
    options.stdio_count = options_stdio.size();

    // args[5] flags (detached, windowsHide, windowsVerbatimArguments)
    CHECK(args[5]->IsUint32());
    const uint32_t flags = args[5].As<Uint32>()->Value();

    if (flags & kProcessFlagWindowsHide) {
      options.flags |= UV_PROCESS_WINDOWS_HIDE;
    }

    if (env->hide_console_windows()) {
      options.flags |= UV_PROCESS_WINDOWS_HIDE_CONSOLE;
    }

    if (flags & kProcessFlagWindowsVerbatimArguments) {
      options.flags |= UV_PROCESS_WINDOWS_VERBATIM_ARGUMENTS;
    }

    if (flags & kProcessFlagDetached) {
      options.flags |= UV_PROCESS_DETACHED;
    }

    if (err == 0) {
      err = uv_spawn(env->event_loop(), &wrap->process_, &options);
      wrap->MarkAsInitialized();
    }

    if (err == 0) {
      CHECK_EQ(wrap->process_.data, wrap);
      if (wrap->object()
              ->Set(context,
                    env->pid_string(),
                    Integer::New(env->isolate(), wrap->process_.pid))
              .IsNothing()) {
        return;
      }
    }

    args.GetReturnValue().Set(err);
  }

  // The current environment as ["KEY=value", ...], i.e. what a spawned
  // child inherits by default, produced in one pass over the environment
  // block instead of one interceptor round trip per variable.
  static void GetEnvPairs(const FunctionCallbackInfo<Value>& args) {
    Environment* env = Environment::GetCurrent(args);
    Local<Array> pairs;
    if (env->env_vars()->Pairs(env->isolate()).ToLocal(&pairs)) {
      args.GetReturnValue().Set(pairs);
    }
  }

  static void Kill(const FunctionCallbackInfo<Value>& args) {
    Environment* env = Environment::GetCurrent(args);
    ProcessWrap* wrap;
    ASSIGN_OR_RETURN_UNWRAP(&wrap, args.This());
    int signal;
    if (!args[0]->Int32Value(env->context()).To(&signal)) {
      return;
    }
#ifdef _WIN32
    if (signal != SIGKILL && signal != SIGTERM && signal != SIGINT &&
        signal != SIGQUIT && signal != 0 && signal != SIGWINCH) {
      signal = SIGKILL;
    }
#endif
    // uv_spawn() only assigns a pid when it succeeds, and kill(0, signal)
    // signals every process in our own process group.
    int err = wrap->process_.pid > 0 ? uv_process_kill(&wrap->process_, signal)
                                     : UV_ESRCH;
    args.GetReturnValue().Set(err);
  }

  static void OnExit(uv_process_t* handle,
                     int64_t exit_status,
                     int term_signal) {
    ProcessWrap* wrap = ContainerOf(&ProcessWrap::process_, handle);
    CHECK_EQ(&wrap->process_, handle);

    Environment* env = wrap->env();
    HandleScope handle_scope(env->isolate());
    Context::Scope context_scope(env->context());

    Local<Value> argv[] = {
      Number::New(env->isolate(), static_cast<double>(exit_status)),
      OneByteString(env->isolate(), signo_string(term_signal))
    };

    wrap->MakeCallback(env->onexit_string(), arraysize(argv), argv);
  }

  uv_process_t process_;
};


}  // anonymous namespace
}  // namespace node

NODE_BINDING_CONTEXT_AWARE_INTERNAL(process_wrap, node::ProcessWrap::Initialize)
NODE_BINDING_EXTERNAL_REFERENCE(process_wrap,
                                node::ProcessWrap::RegisterExternalReferences)