summaryrefslogtreecommitdiffstats
path: root/ppapi/proxy/udp_socket_resource_base.cc
blob: 521a6e2f4e284220d649e8d49934f503b6245127 (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
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ppapi/proxy/udp_socket_resource_base.h"

#include <algorithm>
#include <cstring>

#include "base/logging.h"
#include "ppapi/c/pp_bool.h"
#include "ppapi/c/pp_completion_callback.h"
#include "ppapi/c/pp_errors.h"
#include "ppapi/proxy/error_conversion.h"
#include "ppapi/proxy/plugin_globals.h"
#include "ppapi/proxy/ppapi_messages.h"
#include "ppapi/shared_impl/socket_option_data.h"
#include "ppapi/thunk/enter.h"
#include "ppapi/thunk/resource_creation_api.h"

namespace ppapi {
namespace proxy {

const int32_t UDPSocketResourceBase::kMaxReadSize = 128 * 1024;
const int32_t UDPSocketResourceBase::kMaxWriteSize = 128 * 1024;
const int32_t UDPSocketResourceBase::kMaxSendBufferSize =
    1024 * UDPSocketResourceBase::kMaxWriteSize;
const int32_t UDPSocketResourceBase::kMaxReceiveBufferSize =
    1024 * UDPSocketResourceBase::kMaxReadSize;
const size_t UDPSocketResourceBase::kPluginReceiveBufferSlots = 32u;

UDPSocketResourceBase::UDPSocketResourceBase(Connection connection,
                                             PP_Instance instance,
                                             bool private_api)
    : PluginResource(connection, instance),
      private_api_(private_api),
      bound_(false),
      closed_(false),
      read_buffer_(NULL),
      bytes_to_read_(-1),
      recvfrom_addr_resource_(NULL) {
  recvfrom_addr_.size = 0;
  memset(recvfrom_addr_.data, 0,
         arraysize(recvfrom_addr_.data) * sizeof(*recvfrom_addr_.data));
  bound_addr_.size = 0;
  memset(bound_addr_.data, 0,
         arraysize(bound_addr_.data) * sizeof(*bound_addr_.data));

  if (private_api)
    SendCreate(BROWSER, PpapiHostMsg_UDPSocket_CreatePrivate());
  else
    SendCreate(BROWSER, PpapiHostMsg_UDPSocket_Create());

  PluginGlobals::Get()->resource_reply_thread_registrar()->HandleOnIOThread(
      PpapiPluginMsg_UDPSocket_PushRecvResult::ID);
}

UDPSocketResourceBase::~UDPSocketResourceBase() {
}

int32_t UDPSocketResourceBase::SetOptionImpl(
    PP_UDPSocket_Option name,
    const PP_Var& value,
    scoped_refptr<TrackedCallback> callback) {
  if (closed_)
    return PP_ERROR_FAILED;

  SocketOptionData option_data;
  switch (name) {
    case PP_UDPSOCKET_OPTION_ADDRESS_REUSE:
    case PP_UDPSOCKET_OPTION_BROADCAST: {
      if (bound_)
        return PP_ERROR_FAILED;
      if (value.type != PP_VARTYPE_BOOL)
        return PP_ERROR_BADARGUMENT;
      option_data.SetBool(PP_ToBool(value.value.as_bool));
      break;
    }
    case PP_UDPSOCKET_OPTION_SEND_BUFFER_SIZE:
    case PP_UDPSOCKET_OPTION_RECV_BUFFER_SIZE: {
      if (!bound_)
        return PP_ERROR_FAILED;
      if (value.type != PP_VARTYPE_INT32)
        return PP_ERROR_BADARGUMENT;
      option_data.SetInt32(value.value.as_int);
      break;
    }
    default: {
      NOTREACHED();
      return PP_ERROR_BADARGUMENT;
    }
  }

  Call<PpapiPluginMsg_UDPSocket_SetOptionReply>(
      BROWSER,
      PpapiHostMsg_UDPSocket_SetOption(name, option_data),
      base::Bind(&UDPSocketResourceBase::OnPluginMsgSetOptionReply,
                 base::Unretained(this),
                 callback),
      callback);
  return PP_OK_COMPLETIONPENDING;
}

int32_t UDPSocketResourceBase::BindImpl(
    const PP_NetAddress_Private* addr,
    scoped_refptr<TrackedCallback> callback) {
  if (!addr)
    return PP_ERROR_BADARGUMENT;
  if (bound_ || closed_)
    return PP_ERROR_FAILED;
  if (TrackedCallback::IsPending(bind_callback_))
    return PP_ERROR_INPROGRESS;

  bind_callback_ = callback;

  // Send the request, the browser will call us back via BindReply.
  Call<PpapiPluginMsg_UDPSocket_BindReply>(
      BROWSER,
      PpapiHostMsg_UDPSocket_Bind(*addr),
      base::Bind(&UDPSocketResourceBase::OnPluginMsgBindReply,
                 base::Unretained(this)),
      callback);
  return PP_OK_COMPLETIONPENDING;
}

PP_Bool UDPSocketResourceBase::GetBoundAddressImpl(
    PP_NetAddress_Private* addr) {
  if (!addr || !bound_ || closed_)
    return PP_FALSE;

  *addr = bound_addr_;
  return PP_TRUE;
}

int32_t UDPSocketResourceBase::RecvFromImpl(
    char* buffer,
    int32_t num_bytes,
    PP_Resource* addr,
    scoped_refptr<TrackedCallback> callback) {
  if (!buffer || num_bytes <= 0)
    return PP_ERROR_BADARGUMENT;
  if (!bound_)
    return PP_ERROR_FAILED;
  if (TrackedCallback::IsPending(recvfrom_callback_))
    return PP_ERROR_INPROGRESS;

  if (recv_buffers_.empty()) {
    read_buffer_ = buffer;
    bytes_to_read_ = std::min(num_bytes, kMaxReadSize);
    recvfrom_addr_resource_ = addr;
    recvfrom_callback_ = callback;

    return PP_OK_COMPLETIONPENDING;
  } else {
    RecvBuffer& front = recv_buffers_.front();

    if (num_bytes < static_cast<int32_t>(front.data.size()))
      return PP_ERROR_MESSAGE_TOO_BIG;

    int32_t result = SetRecvFromOutput(front.result, front.data, front.addr,
                                       buffer, num_bytes, addr);

    recv_buffers_.pop();
    Post(BROWSER, PpapiHostMsg_UDPSocket_RecvSlotAvailable());

    return result;
  }
}

PP_Bool UDPSocketResourceBase::GetRecvFromAddressImpl(
    PP_NetAddress_Private* addr) {
  if (!addr)
    return PP_FALSE;
  *addr = recvfrom_addr_;
  return PP_TRUE;
}

int32_t UDPSocketResourceBase::SendToImpl(
    const char* buffer,
    int32_t num_bytes,
    const PP_NetAddress_Private* addr,
    scoped_refptr<TrackedCallback> callback) {
  if (!buffer || num_bytes <= 0 || !addr)
    return PP_ERROR_BADARGUMENT;
  if (!bound_)
    return PP_ERROR_FAILED;
  if (TrackedCallback::IsPending(sendto_callback_))
    return PP_ERROR_INPROGRESS;

  if (num_bytes > kMaxWriteSize)
    num_bytes = kMaxWriteSize;

  sendto_callback_ = callback;

  // Send the request, the browser will call us back via SendToReply.
  Call<PpapiPluginMsg_UDPSocket_SendToReply>(
      BROWSER,
      PpapiHostMsg_UDPSocket_SendTo(std::string(buffer, num_bytes), *addr),
      base::Bind(&UDPSocketResourceBase::OnPluginMsgSendToReply,
                 base::Unretained(this)),
      callback);
  return PP_OK_COMPLETIONPENDING;
}

void UDPSocketResourceBase::CloseImpl() {
  if(closed_)
    return;

  bound_ = false;
  closed_ = true;

  Post(BROWSER, PpapiHostMsg_UDPSocket_Close());

  PostAbortIfNecessary(&bind_callback_);
  PostAbortIfNecessary(&recvfrom_callback_);
  PostAbortIfNecessary(&sendto_callback_);

  read_buffer_ = NULL;
  bytes_to_read_ = -1;
}

void UDPSocketResourceBase::OnReplyReceived(
    const ResourceMessageReplyParams& params,
    const IPC::Message& msg) {
  PPAPI_BEGIN_MESSAGE_MAP(UDPSocketResourceBase, msg)
    PPAPI_DISPATCH_PLUGIN_RESOURCE_CALL(
        PpapiPluginMsg_UDPSocket_PushRecvResult,
        OnPluginMsgPushRecvResult)
    PPAPI_DISPATCH_PLUGIN_RESOURCE_CALL_UNHANDLED(
        PluginResource::OnReplyReceived(params, msg))
  PPAPI_END_MESSAGE_MAP()
}

void UDPSocketResourceBase::PostAbortIfNecessary(
    scoped_refptr<TrackedCallback>* callback) {
  if (TrackedCallback::IsPending(*callback))
    (*callback)->PostAbort();
}

void UDPSocketResourceBase::OnPluginMsgSetOptionReply(
    scoped_refptr<TrackedCallback> callback,
    const ResourceMessageReplyParams& params) {
  if (TrackedCallback::IsPending(callback))
    RunCallback(callback, params.result());
}

void UDPSocketResourceBase::OnPluginMsgBindReply(
    const ResourceMessageReplyParams& params,
    const PP_NetAddress_Private& bound_addr) {
  // It is possible that |bind_callback_| is pending while |closed_| is true:
  // CloseImpl() has been called, but a BindReply came earlier than the task to
  // abort |bind_callback_|. We don't want to update |bound_| or |bound_addr_|
  // in that case.
  if (!TrackedCallback::IsPending(bind_callback_) || closed_)
    return;

  if (params.result() == PP_OK)
    bound_ = true;
  bound_addr_ = bound_addr;
  RunCallback(bind_callback_, params.result());
}

void UDPSocketResourceBase::OnPluginMsgPushRecvResult(
    const ResourceMessageReplyParams& params,
    int32_t result,
    const std::string& data,
    const PP_NetAddress_Private& addr) {
  // TODO(yzshen): Support passing in a non-const string ref, so that we can
  // eliminate one copy when storing the data in the buffer.

  DCHECK_LT(recv_buffers_.size(), kPluginReceiveBufferSlots);

  if (!TrackedCallback::IsPending(recvfrom_callback_) || !read_buffer_) {
    recv_buffers_.push(RecvBuffer());
    RecvBuffer& back = recv_buffers_.back();
    back.result = result;
    back.data = data;
    back.addr = addr;

    return;
  }

  DCHECK_EQ(recv_buffers_.size(), 0u);

  if (bytes_to_read_ < static_cast<int32_t>(data.size())) {
    recv_buffers_.push(RecvBuffer());
    RecvBuffer& back = recv_buffers_.back();
    back.result = result;
    back.data = data;
    back.addr = addr;

    result = PP_ERROR_MESSAGE_TOO_BIG;
  } else {
    result = SetRecvFromOutput(result, data, addr, read_buffer_, bytes_to_read_,
                               recvfrom_addr_resource_);
    Post(BROWSER, PpapiHostMsg_UDPSocket_RecvSlotAvailable());
  }

  read_buffer_ = NULL;
  bytes_to_read_ = -1;
  recvfrom_addr_resource_ = NULL;

  RunCallback(recvfrom_callback_, result);
}

void UDPSocketResourceBase::OnPluginMsgSendToReply(
    const ResourceMessageReplyParams& params,
    int32_t bytes_written) {
  if (!TrackedCallback::IsPending(sendto_callback_))
    return;

  if (params.result() == PP_OK)
    RunCallback(sendto_callback_, bytes_written);
  else
    RunCallback(sendto_callback_, params.result());
}

void UDPSocketResourceBase::RunCallback(scoped_refptr<TrackedCallback> callback,
                                        int32_t pp_result) {
  callback->Run(ConvertNetworkAPIErrorForCompatibility(pp_result,
                                                       private_api_));
}

int32_t UDPSocketResourceBase::SetRecvFromOutput(
    int32_t browser_result,
    const std::string& data,
    const PP_NetAddress_Private& addr,
    char* output_buffer,
    int32_t num_bytes,
    PP_Resource* output_addr) {
  DCHECK_GE(num_bytes, static_cast<int32_t>(data.size()));

  int32_t result = browser_result;
  if (result == PP_OK && output_addr) {
    thunk::EnterResourceCreationNoLock enter(pp_instance());
    if (enter.succeeded()) {
      *output_addr = enter.functions()->CreateNetAddressFromNetAddressPrivate(
          pp_instance(), addr);
    } else {
      result = PP_ERROR_FAILED;
    }
  }

  if (result == PP_OK && !data.empty())
    memcpy(output_buffer, data.c_str(), data.size());

  recvfrom_addr_ = addr;

  return result == PP_OK ? static_cast<int32_t>(data.size()) : result;
}

}  // namespace proxy
}  // namespace ppapi