summaryrefslogtreecommitdiff
path: root/chromium/google_apis/gcm/engine/unregistration_request.cc
blob: e9fab18f9c6421915f33b7afc76c46b71d5bdcfc (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
// 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/unregistration_request.h"

#include "base/bind.h"
#include "base/message_loop/message_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_piece.h"
#include "base/values.h"
#include "google_apis/gcm/base/gcm_util.h"
#include "google_apis/gcm/monitoring/gcm_stats_recorder.h"
#include "net/base/escape.h"
#include "net/base/load_flags.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"

namespace gcm {

namespace {

const char kRequestContentType[] = "application/x-www-form-urlencoded";

// Request constants.
const char kAppIdKey[] = "app";
const char kDeleteKey[] = "delete";
const char kDeleteValue[] = "true";
const char kDeviceIdKey[] = "device";
const char kLoginHeader[] = "AidLogin";

}  // namespace

UnregistrationRequest::RequestInfo::RequestInfo(
    uint64 android_id,
    uint64 security_token,
    const std::string& app_id)
    : android_id(android_id),
      security_token(security_token),
      app_id(app_id) {
  DCHECK(android_id != 0UL);
  DCHECK(security_token != 0UL);
}

UnregistrationRequest::RequestInfo::~RequestInfo() {}

UnregistrationRequest::CustomRequestHandler::CustomRequestHandler() {}

UnregistrationRequest::CustomRequestHandler::~CustomRequestHandler() {}

UnregistrationRequest::UnregistrationRequest(
    const GURL& registration_url,
    const RequestInfo& request_info,
    scoped_ptr<CustomRequestHandler> custom_request_handler,
    const net::BackoffEntry::Policy& backoff_policy,
    const UnregistrationCallback& callback,
    int max_retry_count,
    scoped_refptr<net::URLRequestContextGetter> request_context_getter,
    GCMStatsRecorder* recorder,
    const std::string& source_to_record)
    : callback_(callback),
      request_info_(request_info),
      custom_request_handler_(custom_request_handler.Pass()),
      registration_url_(registration_url),
      backoff_entry_(&backoff_policy),
      request_context_getter_(request_context_getter),
      retries_left_(max_retry_count),
      recorder_(recorder),
      source_to_record_(source_to_record),
      weak_ptr_factory_(this) {
  DCHECK_GE(max_retry_count, 0);
}

UnregistrationRequest::~UnregistrationRequest() {}

void UnregistrationRequest::Start() {
  DCHECK(!callback_.is_null());
  DCHECK(!url_fetcher_.get());

  url_fetcher_ =
      net::URLFetcher::Create(registration_url_, net::URLFetcher::POST, this);
  url_fetcher_->SetRequestContext(request_context_getter_.get());
  url_fetcher_->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES |
                             net::LOAD_DO_NOT_SAVE_COOKIES);

  std::string extra_headers;
  BuildRequestHeaders(&extra_headers);
  url_fetcher_->SetExtraRequestHeaders(extra_headers);

  std::string body;
  BuildRequestBody(&body);

  DVLOG(1) << "Unregistration request: " << body;
  url_fetcher_->SetUploadData(kRequestContentType, body);

  DVLOG(1) << "Performing unregistration for: " << request_info_.app_id;
  recorder_->RecordUnregistrationSent(request_info_.app_id, source_to_record_);
  request_start_time_ = base::TimeTicks::Now();
  url_fetcher_->Start();
}

void UnregistrationRequest::BuildRequestHeaders(std::string* extra_headers) {
  net::HttpRequestHeaders headers;
  headers.SetHeader(
      net::HttpRequestHeaders::kAuthorization,
      std::string(kLoginHeader) + " " +
          base::Uint64ToString(request_info_.android_id) + ":" +
          base::Uint64ToString(request_info_.security_token));
  headers.SetHeader(kAppIdKey, request_info_.app_id);
  *extra_headers = headers.ToString();
}

void UnregistrationRequest::BuildRequestBody(std::string* body) {
  BuildFormEncoding(kAppIdKey, request_info_.app_id, body);
  BuildFormEncoding(kDeviceIdKey,
                    base::Uint64ToString(request_info_.android_id),
                    body);
  BuildFormEncoding(kDeleteKey, kDeleteValue, body);

  DCHECK(custom_request_handler_.get());
  custom_request_handler_->BuildRequestBody(body);
}

UnregistrationRequest::Status UnregistrationRequest::ParseResponse(
    const net::URLFetcher* source) {
  if (!source->GetStatus().is_success()) {
    DVLOG(1) << "Fetcher failed";
    return URL_FETCHING_FAILED;
  }

  net::HttpStatusCode response_status = static_cast<net::HttpStatusCode>(
      source->GetResponseCode());
  if (response_status != net::HTTP_OK) {
    DVLOG(1) << "HTTP Status code is not OK, but: " << response_status;
    if (response_status == net::HTTP_SERVICE_UNAVAILABLE)
      return SERVICE_UNAVAILABLE;
    if (response_status == net::HTTP_INTERNAL_SERVER_ERROR)
      return INTERNAL_SERVER_ERROR;
    return HTTP_NOT_OK;
  }

  DCHECK(custom_request_handler_.get());
  return custom_request_handler_->ParseResponse(source);
}

void UnregistrationRequest::RetryWithBackoff(bool update_backoff) {
  if (update_backoff) {
    DCHECK_GT(retries_left_, 0);
    --retries_left_;
    url_fetcher_.reset();
    backoff_entry_.InformOfRequest(false);
  }

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

  Start();
}

void UnregistrationRequest::OnURLFetchComplete(const net::URLFetcher* source) {
  UnregistrationRequest::Status status = ParseResponse(source);

  DVLOG(1) << "UnregistrationRequestStauts: " << status;

  DCHECK(custom_request_handler_.get());
  custom_request_handler_->ReportUMAs(
      status,
      backoff_entry_.failure_count(),
      base::TimeTicks::Now() - request_start_time_);

  recorder_->RecordUnregistrationResponse(
      request_info_.app_id, source_to_record_, status);

  if (status == URL_FETCHING_FAILED ||
      status == HTTP_NOT_OK ||
      status == NO_RESPONSE_BODY ||
      status == SERVICE_UNAVAILABLE ||
      status == INTERNAL_SERVER_ERROR ||
      status == INCORRECT_APP_ID ||
      status == RESPONSE_PARSING_FAILED) {
    if (retries_left_ > 0) {
      RetryWithBackoff(true);
      return;
    }

    status = REACHED_MAX_RETRIES;
    recorder_->RecordUnregistrationResponse(
        request_info_.app_id, source_to_record_, status);

    // Only REACHED_MAX_RETRIES is reported because the function will skip
    // reporting count and time when status is not SUCCESS.
    DCHECK(custom_request_handler_.get());
    custom_request_handler_->ReportUMAs(status, 0, base::TimeDelta());
  }

  // status == SUCCESS || INVALID_PARAMETERS || UNKNOWN_ERROR ||
  //           REACHED_MAX_RETRIES

  callback_.Run(status);
}

}  // namespace gcm