summaryrefslogtreecommitdiffstats
path: root/google_apis/gcm/engine/registration_request.cc
blob: 81c581787aa48c741ad96f950a7a561dfa953fde (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
// Copyright 2014 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 "google_apis/gcm/engine/registration_request.h"

#include "base/bind.h"
#include "base/message_loop/message_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/values.h"
#include "net/base/escape.h"
#include "net/http/http_request_headers.h"
#include "net/http/http_status_code.h"
#include "net/url_request/url_fetcher.h"
#include "net/url_request/url_request_context_getter.h"
#include "net/url_request/url_request_status.h"
#include "url/gurl.h"

namespace gcm {

namespace {

const char kRegistrationURL[] =
    "https://android.clients.google.com/c2dm/register3";
const char kRegistrationRequestContentType[] =
    "application/x-www-form-urlencoded";

// Request constants.
const char kAppIdKey[] = "app";
const char kCertKey[] = "cert";
const char kDeviceIdKey[] = "device";
const char kLoginHeader[] = "AidLogin";
const char kSenderKey[] = "sender";
const char kUserAndroidIdKey[] = "X-GOOG.USER_AID";
const char kUserSerialNumberKey[] = "device_user_id";

// Request validation constants.
const size_t kMaxSenders = 100;

// Response constants.
const char kErrorPrefix[] = "Error=";
const char kTokenPrefix[] = "token=";
const char kDeviceRegistrationError[] = "PHONE_REGISTRATION_ERROR";
const char kAuthenticationFailed[] = "AUTHENTICATION_FAILED";
const char kInvalidSender[] = "INVALID_SENDER";
const char kInvalidParameters[] = "INVALID_PARAMETERS";

void BuildFormEncoding(const std::string& key,
                       const std::string& value,
                       std::string* out) {
  if (!out->empty())
    out->append("&");
  out->append(key + "=" + net::EscapeUrlEncodedData(value, true));
}

// Gets correct status from the error message.
RegistrationRequest::Status GetStatusFromError(const std::string& error) {
  if (error == kDeviceRegistrationError)
    return RegistrationRequest::DEVICE_REGISTRATION_ERROR;
  if (error == kAuthenticationFailed)
    return RegistrationRequest::AUTHENTICATION_FAILED;
  if (error == kInvalidSender)
    return RegistrationRequest::INVALID_SENDER;
  if (error == kInvalidParameters)
    return RegistrationRequest::INVALID_PARAMETERS;
  return RegistrationRequest::UNKNOWN_ERROR;
}

// Indicates whether a retry attempt should be made based on the status of the
// last request.
bool ShouldRetryWithStatus(RegistrationRequest::Status status) {
  return status == RegistrationRequest::UNKNOWN_ERROR ||
         status == RegistrationRequest::AUTHENTICATION_FAILED ||
         status == RegistrationRequest::DEVICE_REGISTRATION_ERROR;
}

}  // namespace

RegistrationRequest::RequestInfo::RequestInfo(
    uint64 android_id,
    uint64 security_token,
    uint64 user_android_id,
    int64 user_serial_number,
    const std::string& app_id,
    const std::string& cert,
    const std::vector<std::string>& sender_ids)
    : android_id(android_id),
      security_token(security_token),
      user_android_id(user_android_id),
      user_serial_number(user_serial_number),
      app_id(app_id),
      cert(cert),
      sender_ids(sender_ids) {
}

RegistrationRequest::RequestInfo::~RequestInfo() {}

RegistrationRequest::RegistrationRequest(
    const RequestInfo& request_info,
    const net::BackoffEntry::Policy& backoff_policy,
    const RegistrationCallback& callback,
    scoped_refptr<net::URLRequestContextGetter> request_context_getter)
    : callback_(callback),
      request_info_(request_info),
      backoff_entry_(&backoff_policy),
      request_context_getter_(request_context_getter),
      weak_ptr_factory_(this) {
}

RegistrationRequest::~RegistrationRequest() {}

void RegistrationRequest::Start() {
  DCHECK(!callback_.is_null());
  DCHECK(request_info_.android_id != 0UL);
  DCHECK(request_info_.security_token != 0UL);
  DCHECK(!request_info_.cert.empty());
  DCHECK(0 < request_info_.sender_ids.size() &&
         request_info_.sender_ids.size() <= kMaxSenders);

  DCHECK(!url_fetcher_.get());
  url_fetcher_.reset(net::URLFetcher::Create(
      GURL(kRegistrationURL), net::URLFetcher::POST, this));
  url_fetcher_->SetRequestContext(request_context_getter_);

  std::string android_id = base::Uint64ToString(request_info_.android_id);
  std::string auth_header =
      std::string(net::HttpRequestHeaders::kAuthorization) + ": " +
      kLoginHeader + " " + android_id + ":" +
      base::Uint64ToString(request_info_.security_token);
  url_fetcher_->SetExtraRequestHeaders(auth_header);

  std::string body;
  BuildFormEncoding(kAppIdKey, request_info_.app_id, &body);
  BuildFormEncoding(kCertKey, request_info_.cert, &body);
  BuildFormEncoding(kDeviceIdKey, android_id, &body);

  std::string senders;
  for (std::vector<std::string>::const_iterator iter =
           request_info_.sender_ids.begin();
       iter != request_info_.sender_ids.end();
       ++iter) {
    DCHECK(!iter->empty());
    if (!senders.empty())
      senders.append(",");
    senders.append(*iter);
  }
  BuildFormEncoding(kSenderKey, senders, &body);

  if (request_info_.user_serial_number != 0) {
    DCHECK(request_info_.user_android_id != 0);
    BuildFormEncoding(kUserSerialNumberKey,
                      base::Int64ToString(request_info_.user_serial_number),
                      &body);
    BuildFormEncoding(kUserAndroidIdKey,
                      base::Uint64ToString(request_info_.user_android_id),
                      &body);
  }

  DVLOG(1) << "Performing registration for: " << request_info_.app_id;
  DVLOG(1) << "Registration request: " << body;
  url_fetcher_->SetUploadData(kRegistrationRequestContentType, body);
  url_fetcher_->Start();
}

void RegistrationRequest::RetryWithBackoff(bool update_backoff) {
  if (update_backoff) {
    url_fetcher_.reset();
    backoff_entry_.InformOfRequest(false);
  }

  if (backoff_entry_.ShouldRejectRequest()) {
    DVLOG(1) << "Delaying GCM registration of app: "
             << request_info_.app_id << ", for "
             << backoff_entry_.GetTimeUntilRelease().InMilliseconds()
             << " milliseconds.";
    base::MessageLoop::current()->PostDelayedTask(
        FROM_HERE,
        base::Bind(&RegistrationRequest::RetryWithBackoff,
                   weak_ptr_factory_.GetWeakPtr(),
                   false),
        backoff_entry_.GetTimeUntilRelease());
    return;
  }

  Start();
}

void RegistrationRequest::OnURLFetchComplete(const net::URLFetcher* source) {
  std::string response;
  if (!source->GetStatus().is_success() ||
      source->GetResponseCode() != net::HTTP_OK ||
      !source->GetResponseAsString(&response)) {
    LOG(ERROR) << "Failed to get registration response: "
               << source->GetStatus().is_success() << " "
               << source->GetResponseCode();
    RetryWithBackoff(true);
    return;
  }

  DVLOG(1) << "Parsing registration response: " << response;
  size_t token_pos = response.find(kTokenPrefix);
  if (token_pos != std::string::npos) {
    std::string token =
        response.substr(token_pos + arraysize(kTokenPrefix) - 1);
    callback_.Run(SUCCESS, token);
    return;
  }

  size_t error_pos = response.find(kErrorPrefix);
  Status status = UNKNOWN_ERROR;
  if (error_pos != std::string::npos) {
    std::string error =
        response.substr(error_pos + arraysize(kErrorPrefix) - 1);
    status = GetStatusFromError(error);
  }

  if (ShouldRetryWithStatus(status)) {
    RetryWithBackoff(true);
    return;
  }

  callback_.Run(status, std::string());
}

}  // namespace gcm