summaryrefslogtreecommitdiffstats
path: root/ipc/glue/ForkServer.cpp
blob: 23ce9362fb428b88f092f7f8ba35524e75e7ff15 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* vim: set ts=8 sts=4 et sw=4 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "mozilla/ipc/ForkServer.h"
#include "mozilla/Logging.h"
#include "chrome/common/chrome_switches.h"
#include "mozilla/BlockingResourceBase.h"
#include "mozilla/ipc/ProtocolMessageUtils.h"
#include "mozilla/ipc/FileDescriptor.h"
#include "mozilla/ipc/IPDLParamTraits.h"
#include "ipc/IPCMessageUtilsSpecializations.h"
#include "nsTraceRefcnt.h"

#include <string.h>
#include <unistd.h>
#include <fcntl.h>

#if defined(XP_LINUX) && defined(MOZ_SANDBOX)
#  include "mozilla/SandboxLaunch.h"
#endif

#include <algorithm>

namespace mozilla {
namespace ipc {

LazyLogModule gForkServiceLog("ForkService");

ForkServer::ForkServer() {}

/**
 * Prepare an environment for running a fork server.
 */
void ForkServer::InitProcess(int* aArgc, char*** aArgv) {
  base::InitForkServerProcess();

  mTcver = MakeUnique<MiniTransceiver>(kClientPipeFd,
                                       DataBufferClear::AfterReceiving);
}

/**
 * Start providing the service at the IPC channel.
 */
bool ForkServer::HandleMessages() {
  while (true) {
    UniquePtr<IPC::Message> msg;
    if (!mTcver->Recv(msg)) {
      break;
    }

    OnMessageReceived(std::move(msg));

    if (mAppProcBuilder) {
      // New process - child
      return false;
    }
  }
  // Stop the server
  return true;
}

inline void CleanCString(nsCString& str) {
  char* data;
  int sz = str.GetMutableData(&data);

  memset(data, ' ', sz);
}

inline void CleanString(std::string& str) {
  const char deadbeef[] =
      "\xde\xad\xbe\xef\xde\xad\xbe\xef\xde\xad\xbe\xef\xde\xad\xbe\xef"
      "\xde\xad\xbe\xef\xde\xad\xbe\xef\xde\xad\xbe\xef\xde\xad\xbe\xef";
  int pos = 0;
  size_t sz = str.size();
  while (sz > 0) {
    int toclean = std::min(sz, sizeof(deadbeef) - 1);
    str.replace(pos, toclean, deadbeef);
    sz -= toclean;
    pos += toclean;
  }
}

inline void PrepareArguments(std::vector<std::string>& aArgv,
                             nsTArray<nsCString>& aArgvArray) {
  for (auto& elt : aArgvArray) {
    aArgv.push_back(elt.get());
    CleanCString(elt);
  }
}

// Prepare aOptions->env_map
inline void PrepareEnv(base::LaunchOptions* aOptions,
                       nsTArray<EnvVar>& aEnvMap) {
  for (auto& elt : aEnvMap) {
    nsCString& var = std::get<0>(elt);
    nsCString& val = std::get<1>(elt);
    aOptions->env_map[var.get()] = val.get();
    CleanCString(var);
    CleanCString(val);
  }
}

// Prepare aOptions->fds_to_remap
inline void PrepareFdsRemap(base::LaunchOptions* aOptions,
                            nsTArray<FdMapping>& aFdsRemap) {
  MOZ_LOG(gForkServiceLog, LogLevel::Verbose, ("fds mapping:"));
  for (auto& elt : aFdsRemap) {
    // FDs are duplicated here.
    int fd = std::get<0>(elt).ClonePlatformHandle().release();
    std::pair<int, int> fdmap(fd, std::get<1>(elt));
    aOptions->fds_to_remap.push_back(fdmap);
    MOZ_LOG(gForkServiceLog, LogLevel::Verbose,
            ("\t%d => %d", fdmap.first, fdmap.second));
  }
}

template <class P>
static void ReadParamInfallible(IPC::MessageReader* aReader, P* aResult,
                                const char* aCrashMessage) {
  if (!IPC::ReadParam(aReader, aResult)) {
    MOZ_CRASH_UNSAFE(aCrashMessage);
  }
}

/**
 * Parse a Message to get a list of arguments and fill a LaunchOptions.
 */
inline bool ParseForkNewSubprocess(IPC::Message& aMsg,
                                   std::vector<std::string>& aArgv,
                                   base::LaunchOptions* aOptions) {
  if (aMsg.type() != Msg_ForkNewSubprocess__ID) {
    MOZ_LOG(gForkServiceLog, LogLevel::Verbose,
            ("unknown message type %d\n", aMsg.type()));
    return false;
  }

  IPC::MessageReader reader(aMsg);
  nsTArray<nsCString> argv_array;
  nsTArray<EnvVar> env_map;
  nsTArray<FdMapping> fds_remap;

  ReadParamInfallible(&reader, &argv_array,
                      "Error deserializing 'nsCString[]'");
  ReadParamInfallible(&reader, &env_map, "Error deserializing 'EnvVar[]'");
  ReadParamInfallible(&reader, &fds_remap, "Error deserializing 'FdMapping[]'");
  reader.EndRead();

  PrepareArguments(aArgv, argv_array);
  PrepareEnv(aOptions, env_map);
  PrepareFdsRemap(aOptions, fds_remap);

  return true;
}

inline void SanitizeBuffers(IPC::Message& aMsg, std::vector<std::string>& aArgv,
                            base::LaunchOptions& aOptions) {
  // Clean all buffers in the message to make sure content processes
  // not peeking others.
  auto& blist = aMsg.Buffers();
  for (auto itr = blist.Iter(); !itr.Done();
       itr.Advance(blist, itr.RemainingInSegment())) {
    memset(itr.Data(), 0, itr.RemainingInSegment());
  }

  // clean all data string made from the message.
  for (auto& var : aOptions.env_map) {
    // Do it anyway since it is not going to be used anymore.
    CleanString(*const_cast<std::string*>(&var.first));
    CleanString(var.second);
  }
  for (auto& arg : aArgv) {
    CleanString(arg);
  }
}

/**
 * Extract parameters from the |Message| to create a
 * |base::AppProcessBuilder| as |mAppProcBuilder|.
 *
 * It will return in both the fork server process and the new content
 * process.  |mAppProcBuilder| is null for the fork server.
 */
void ForkServer::OnMessageReceived(UniquePtr<IPC::Message> message) {
  std::vector<std::string> argv;
  base::LaunchOptions options;
  if (!ParseForkNewSubprocess(*message, argv, &options)) {
    return;
  }

#if defined(XP_LINUX) && defined(MOZ_SANDBOX)
  mozilla::SandboxLaunchForkServerPrepare(argv, options);
#endif

  base::ProcessHandle child_pid = -1;
  mAppProcBuilder = MakeUnique<base::AppProcessBuilder>();
  if (!mAppProcBuilder->ForkProcess(argv, options, &child_pid)) {
    MOZ_CRASH("fail to fork");
  }
  MOZ_ASSERT(child_pid >= 0);

  if (child_pid == 0) {
    // Content process
    return;
  }

  // Fork server process

  mAppProcBuilder = nullptr;

  IPC::Message reply(MSG_ROUTING_CONTROL, Reply_ForkNewSubprocess__ID);
  IPC::MessageWriter writer(reply);
  WriteIPDLParam(&writer, nullptr, child_pid);
  mTcver->SendInfallible(reply, "failed to send a reply message");

  // Without this, the content processes that is forked later are
  // able to read the content of buffers even the buffers have been
  // released.
  SanitizeBuffers(*message, argv, options);
}

/**
 * Setup and run a fork server at the main thread.
 *
 * This function returns for two reasons:
 *  - the fork server is stopped normally, or
 *  - a new process is forked from the fork server and this function
 *    returned in the child, the new process.
 *
 * For the later case, aArgc and aArgv are modified to pass the
 * arguments from the chrome process.
 */
bool ForkServer::RunForkServer(int* aArgc, char*** aArgv) {
#ifdef DEBUG
  if (getenv("MOZ_FORKSERVER_WAIT_GDB")) {
    printf(
        "Waiting for 30 seconds."
        "  Attach the fork server with gdb %s %d\n",
        (*aArgv)[0], base::GetCurrentProcId());
    sleep(30);
  }
  bool sleep_newproc = !!getenv("MOZ_FORKSERVER_WAIT_GDB_NEWPROC");
#endif

  // Do this before NS_LogInit() to avoid log files taking lower
  // FDs.
  ForkServer forkserver;
  forkserver.InitProcess(aArgc, aArgv);

  XRE_SetProcessType("forkserver");
  NS_LogInit();
  mozilla::LogModule::Init(0, nullptr);
  MOZ_LOG(gForkServiceLog, LogLevel::Verbose, ("Start a fork server"));
  {
    DebugOnly<base::ProcessHandle> forkserver_pid = base::GetCurrentProcId();
    if (forkserver.HandleMessages()) {
      // In the fork server process
      // The server has stopped.
      MOZ_LOG(gForkServiceLog, LogLevel::Verbose,
              ("Terminate the fork server"));
      NS_LogTerm();
      return true;
    }
    // Now, we are running in a content process just forked from
    // the fork server process.
    MOZ_ASSERT(base::GetCurrentProcId() != forkserver_pid);
    MOZ_LOG(gForkServiceLog, LogLevel::Verbose, ("Fork a new content process"));
  }
#ifdef DEBUG
  if (sleep_newproc) {
    printf(
        "Waiting for 30 seconds."
        "  Attach the new process with gdb %s %d\n",
        (*aArgv)[0], base::GetCurrentProcId());
    sleep(30);
  }
#endif
  NS_LogTerm();

  MOZ_ASSERT(forkserver.mAppProcBuilder);
  // |messageloop| has been destroyed.  So, we can intialized the
  // process safely.  Message loops may allocates some file
  // descriptors.  If it is destroyed later, it may mess up this
  // content process by closing wrong file descriptors.
  forkserver.mAppProcBuilder->InitAppProcess(aArgc, aArgv);
  forkserver.mAppProcBuilder.reset();

  MOZ_ASSERT("tab"_ns == (*aArgv)[*aArgc - 1], "Only |tab| is allowed!");

  // Open log files again with right names and the new PID.
  nsTraceRefcnt::ResetLogFiles((*aArgv)[*aArgc - 1]);

  return false;
}

}  // namespace ipc
}  // namespace mozilla