summaryrefslogtreecommitdiff
path: root/ipc/ril/Ril.cpp
blob: 5c48643cc34171d9d38a353a35295b2e8e43b412 (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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
/* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
/* vim: set ts=2 et sw=2 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/Ril.h"
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/un.h>
#include "jsfriendapi.h"
#include "mozilla/ArrayUtils.h"
#include "mozilla/dom/ScriptSettings.h"
#include "mozilla/dom/workers/Workers.h"
#include "mozilla/ipc/RilSocket.h"
#include "mozilla/ipc/RilSocketConsumer.h"
#include "nsThreadUtils.h" // For NS_IsMainThread.
#include "RilConnector.h"

#ifdef CHROMIUM_LOG
#undef CHROMIUM_LOG
#endif

#define CHROMIUM_LOG(args...)  printf(args);

namespace mozilla {
namespace ipc {

USING_WORKERS_NAMESPACE;
using namespace JS;

class RilConsumer;

static const char RIL_SOCKET_NAME[] = "/dev/socket/rilproxy";

static nsTArray<UniquePtr<RilConsumer>> sRilConsumers;

//
// RilConsumer
//

class RilConsumer final : public RilSocketConsumer
{
public:
  RilConsumer();

  nsresult ConnectWorkerToRIL(JSContext* aCx);

  nsresult Register(unsigned long aClientId,
                    WorkerCrossThreadDispatcher* aDispatcher);
  void Unregister();

  // Methods for |RilSocketConsumer|
  //

  void ReceiveSocketData(JSContext* aCx,
                         int aIndex,
                         UniquePtr<UnixSocketBuffer>& aBuffer) override;
  void OnConnectSuccess(int aIndex) override;
  void OnConnectError(int aIndex) override;
  void OnDisconnect(int aIndex) override;

protected:
  static bool PostRILMessage(JSContext* aCx, unsigned aArgc, Value* aVp);

  nsresult Send(JSContext* aCx, const CallArgs& aArgs);
  nsresult Receive(JSContext* aCx,
                   uint32_t aClientId,
                   const UnixSocketBuffer* aBuffer);
  void Close();

private:
  RefPtr<RilSocket> mSocket;
  nsCString mAddress;
  bool mShutdown;
};

RilConsumer::RilConsumer()
  : mShutdown(false)
{ }

nsresult
RilConsumer::ConnectWorkerToRIL(JSContext* aCx)
{
  // Set up the postRILMessage on the function for worker -> RIL thread
  // communication.
  Rooted<JSObject*> workerGlobal(aCx, CurrentGlobalOrNull(aCx));

  // Check whether |postRILMessage| has been defined.  No one but this class
  // should ever define |postRILMessage| in a RIL worker.
  Rooted<Value> val(aCx);
  if (!JS_GetProperty(aCx, workerGlobal, "postRILMessage", &val)) {
    // Just returning failure here will cause the exception on the JSContext to
    // be reported as needed.
    return NS_ERROR_FAILURE;
  }

  // Make sure that |postRILMessage| is a function.
  if (JSTYPE_FUNCTION == JS_TypeOfValue(aCx, val)) {
    return NS_OK;
  }

  JSFunction* postRILMessage = JS_DefineFunction(aCx, workerGlobal,
                                                 "postRILMessage",
                                                 PostRILMessage, 2, 0);
  if (NS_WARN_IF(!postRILMessage)) {
    // Just returning failure here will cause the exception on the JSContext to
    // be reported as needed.
    return NS_ERROR_FAILURE;
  }
  return NS_OK;
}

nsresult
RilConsumer::Register(unsigned long aClientId,
                      WorkerCrossThreadDispatcher* aDispatcher)
{
  // Only append client id after RIL_SOCKET_NAME when it's not connected to
  // the first(0) rilproxy for compatibility.
  if (!aClientId) {
    mAddress = RIL_SOCKET_NAME;
  } else {
    struct sockaddr_un addr_un;
    snprintf(addr_un.sun_path, sizeof addr_un.sun_path, "%s%lu",
             RIL_SOCKET_NAME, aClientId);
    mAddress = addr_un.sun_path;
  }

  mSocket = new RilSocket(aDispatcher, this, aClientId);

  nsresult rv = mSocket->Connect(new RilConnector(mAddress, aClientId));
  if (NS_FAILED(rv)) {
    return rv;
  }

  return NS_OK;
}

void
RilConsumer::Unregister()
{
  mShutdown = true;
  Close();
}

bool
RilConsumer::PostRILMessage(JSContext* aCx, unsigned aArgc, Value* aVp)
{
  CallArgs args = CallArgsFromVp(aArgc, aVp);

  if (args.length() != 2) {
    JS_ReportErrorASCII(aCx, "Expecting two arguments with the RIL message");
    return false;
  }

  int clientId = args[0].toInt32();

  if ((ssize_t)sRilConsumers.Length() <= clientId || !sRilConsumers[clientId]) {
    // Probably shutting down.
    return true;
  }

  nsresult rv = sRilConsumers[clientId]->Send(aCx, args);
  if (NS_FAILED(rv)) {
    return false;
  }

  return true;
}

nsresult
RilConsumer::Send(JSContext* aCx, const CallArgs& aArgs)
{
  if (NS_WARN_IF(!mSocket) ||
      NS_WARN_IF(mSocket->GetConnectionStatus() == SOCKET_DISCONNECTED)) {
    // Probably shutting down.
    return NS_OK;
  }

  UniquePtr<UnixSocketRawData> raw;

  Value v = aArgs[1];

  if (v.isString()) {
    JSAutoByteString abs;
    Rooted<JSString*> str(aCx, v.toString());
    if (!abs.encodeUtf8(aCx, str)) {
      return NS_ERROR_FAILURE;
    }

    raw = MakeUnique<UnixSocketRawData>(abs.ptr(), abs.length());
  } else if (!v.isPrimitive()) {
    JSObject* obj = v.toObjectOrNull();
    if (!JS_IsTypedArrayObject(obj)) {
      JS_ReportErrorASCII(aCx, "Object passed in wasn't a typed array");
      return NS_ERROR_FAILURE;
    }

    uint32_t type = JS_GetArrayBufferViewType(obj);
    if (type != js::Scalar::Int8 &&
        type != js::Scalar::Uint8 &&
        type != js::Scalar::Uint8Clamped) {
      JS_ReportErrorASCII(aCx, "Typed array data is not octets");
      return NS_ERROR_FAILURE;
    }

    size_t size = JS_GetTypedArrayByteLength(obj);
    bool isShared;
    void* data;
    {
      AutoCheckCannotGC nogc;
      data = JS_GetArrayBufferViewData(obj, &isShared, nogc);
    }
    if (isShared) {
      JS_ReportErrorASCII(
        aCx, "Incorrect argument.  Shared memory not supported");
      return NS_ERROR_FAILURE;
    }
    raw = MakeUnique<UnixSocketRawData>(data, size);
  } else {
    JS_ReportErrorASCII(
      aCx, "Incorrect argument. Expecting a string or a typed array");
    return NS_ERROR_FAILURE;
  }

  if (!raw) {
    JS_ReportErrorASCII(aCx, "Unable to post to RIL");
    return NS_ERROR_FAILURE;
  }

  mSocket->SendSocketData(raw.release());

  return NS_OK;
}

nsresult
RilConsumer::Receive(JSContext* aCx,
                     uint32_t aClientId,
                     const UnixSocketBuffer* aBuffer)
{
  MOZ_ASSERT(aBuffer);

  Rooted<JSObject*> obj(aCx, CurrentGlobalOrNull(aCx));

  Rooted<JSObject*> array(aCx, JS_NewUint8Array(aCx, aBuffer->GetSize()));
  if (NS_WARN_IF(!array)) {
    // Just suppress the exception, since our callers don't have a way to
    // indicate they failed.
    JS_ClearPendingException(aCx);
    return NS_ERROR_FAILURE;
  }
  {
    AutoCheckCannotGC nogc;
    bool isShared;
    memcpy(JS_GetArrayBufferViewData(array, &isShared, nogc),
           aBuffer->GetData(), aBuffer->GetSize());
    MOZ_ASSERT(!isShared);      // Array was constructed above.
  }

  AutoValueArray<2> args(aCx);
  args[0].setNumber(aClientId);
  args[1].setObject(*array);

  Rooted<Value> rval(aCx);
  JS_CallFunctionName(aCx, obj, "onRILMessage", args, &rval);
  // Just suppress the exception, since our callers don't have a way to
  // indicate they failed.
  JS_ClearPendingException(aCx);

  return NS_OK;
}

void
RilConsumer::Close()
{
  if (mSocket) {
    mSocket->Close();
    mSocket = nullptr;
  }
}

// |RilSocketConnector|

void
RilConsumer::ReceiveSocketData(JSContext* aCx,
                               int aIndex,
                               UniquePtr<UnixSocketBuffer>& aBuffer)
{
  Receive(aCx, (uint32_t)aIndex, aBuffer.get());
}

void
RilConsumer::OnConnectSuccess(int aIndex)
{
  // Nothing to do here.
  CHROMIUM_LOG("RIL[%d]: %s\n", aIndex, __FUNCTION__);
}

void
RilConsumer::OnConnectError(int aIndex)
{
  CHROMIUM_LOG("RIL[%d]: %s\n", aIndex, __FUNCTION__);
  Close();
}

void
RilConsumer::OnDisconnect(int aIndex)
{
  CHROMIUM_LOG("RIL[%d]: %s\n", aIndex, __FUNCTION__);
  if (mShutdown) {
    return;
  }
  mSocket->Connect(new RilConnector(mAddress, aIndex),
                   mSocket->GetSuggestedConnectDelayMs());
}

//
// RilWorker
//

nsTArray<UniquePtr<RilWorker>> RilWorker::sRilWorkers;

nsresult
RilWorker::Register(unsigned int aClientId,
                    WorkerCrossThreadDispatcher* aDispatcher)
{
  MOZ_ASSERT(NS_IsMainThread());

  sRilWorkers.EnsureLengthAtLeast(aClientId + 1);

  if (sRilWorkers[aClientId]) {
    NS_WARNING("RilWorkers already registered");
    return NS_ERROR_FAILURE;
  }

  // Now that we're set up, connect ourselves to the RIL thread.
  sRilWorkers[aClientId] = MakeUnique<RilWorker>(aDispatcher);

  nsresult rv = sRilWorkers[aClientId]->RegisterConsumer(aClientId);
  if (NS_FAILED(rv)) {
    return rv;
  }

  return NS_OK;
}

void
RilWorker::Shutdown()
{
  MOZ_ASSERT(NS_IsMainThread());

  for (size_t i = 0; i < sRilWorkers.Length(); ++i) {
    if (!sRilWorkers[i]) {
      continue;
    }
    sRilWorkers[i]->UnregisterConsumer(i);
    sRilWorkers[i] = nullptr;
  }
}

RilWorker::RilWorker(WorkerCrossThreadDispatcher* aDispatcher)
  : mDispatcher(aDispatcher)
{
  MOZ_ASSERT(mDispatcher);
}

class RilWorker::RegisterConsumerTask : public WorkerTask
{
public:
  RegisterConsumerTask(unsigned int aClientId,
                       WorkerCrossThreadDispatcher* aDispatcher)
    : mClientId(aClientId)
    , mDispatcher(aDispatcher)
  {
    MOZ_ASSERT(mDispatcher);
  }

  bool RunTask(JSContext* aCx) override
  {
    sRilConsumers.EnsureLengthAtLeast(mClientId + 1);

    MOZ_ASSERT(!sRilConsumers[mClientId]);

    auto rilConsumer = MakeUnique<RilConsumer>();

    nsresult rv = rilConsumer->ConnectWorkerToRIL(aCx);
    if (NS_FAILED(rv)) {
      return false;
    }

    rv = rilConsumer->Register(mClientId, mDispatcher);
    if (NS_FAILED(rv)) {
      return false;
    }
    sRilConsumers[mClientId] = Move(rilConsumer);

    return true;
  }

private:
  unsigned int mClientId;
  RefPtr<WorkerCrossThreadDispatcher> mDispatcher;
};

nsresult
RilWorker::RegisterConsumer(unsigned int aClientId)
{
  RefPtr<RegisterConsumerTask> task = new RegisterConsumerTask(aClientId,
                                                                 mDispatcher);
  if (!mDispatcher->PostTask(task)) {
    NS_WARNING("Failed to post register-consumer task.");
    return NS_ERROR_UNEXPECTED;
  }

  return NS_OK;
}

class RilWorker::UnregisterConsumerTask : public WorkerTask
{
public:
  UnregisterConsumerTask(unsigned int aClientId)
    : mClientId(aClientId)
  { }

  bool RunTask(JSContext* aCx) override
  {
    MOZ_ASSERT(mClientId < sRilConsumers.Length());
    MOZ_ASSERT(sRilConsumers[mClientId]);

    sRilConsumers[mClientId]->Unregister();
    sRilConsumers[mClientId] = nullptr;

    return true;
  }

private:
  unsigned int mClientId;
};

void
RilWorker::UnregisterConsumer(unsigned int aClientId)
{
  RefPtr<UnregisterConsumerTask> task =
    new UnregisterConsumerTask(aClientId);

  if (!mDispatcher->PostTask(task)) {
    NS_WARNING("Failed to post unregister-consumer task.");
    return;
  }
}

} // namespace ipc
} // namespace mozilla