1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 // Library functions related to the Financial Server ping.
7 #include "rlz/lib/financial_ping.h"
9 #include "base/basictypes.h"
10 #include "base/memory/scoped_ptr.h"
11 #include "base/strings/string_util.h"
12 #include "base/strings/stringprintf.h"
13 #include "base/strings/utf_string_conversions.h"
14 #include "rlz/lib/assert.h"
15 #include "rlz/lib/lib_values.h"
16 #include "rlz/lib/machine_id.h"
17 #include "rlz/lib/rlz_lib.h"
18 #include "rlz/lib/rlz_value_store.h"
19 #include "rlz/lib/string_utils.h"
22 #include "base/time.h"
25 #if defined(RLZ_NETWORK_IMPLEMENTATION_WIN_INET)
32 class InternetHandle
{
34 InternetHandle(HINTERNET handle
) { handle_
= handle
; }
35 ~InternetHandle() { if (handle_
) InternetCloseHandle(handle_
); }
36 operator HINTERNET() const { return handle_
; }
37 bool operator!() const { return (handle_
== NULL
); }
47 #include "base/bind.h"
48 #include "base/message_loop.h"
49 #include "base/run_loop.h"
50 #include "base/time.h"
51 #include "googleurl/src/gurl.h"
52 #include "net/base/load_flags.h"
53 #include "net/url_request/url_fetcher.h"
54 #include "net/url_request/url_fetcher_delegate.h"
55 #include "net/url_request/url_request_context.h"
56 #include "net/url_request/url_request_context_getter.h"
62 // Returns the time relative to a fixed point in the past in multiples of
63 // 100 ns stepts. The point in the past is arbitrary but can't change, as the
64 // result of this value is stored on disk.
65 int64
GetSystemTimeAsInt64() {
67 FILETIME now_as_file_time
;
68 // Relative to Jan 1, 1601 (UTC).
69 GetSystemTimeAsFileTime(&now_as_file_time
);
71 LARGE_INTEGER integer
;
72 integer
.HighPart
= now_as_file_time
.dwHighDateTime
;
73 integer
.LowPart
= now_as_file_time
.dwLowDateTime
;
74 return integer
.QuadPart
;
76 // Seconds since epoch (Jan 1, 1970).
77 double now_seconds
= base::Time::Now().ToDoubleT();
78 return static_cast<int64
>(now_seconds
* 1000 * 1000 * 10);
87 bool FinancialPing::FormRequest(Product product
,
88 const AccessPoint
* access_points
, const char* product_signature
,
89 const char* product_brand
, const char* product_id
,
90 const char* product_lang
, bool exclude_machine_id
,
91 std::string
* request
) {
93 ASSERT_STRING("FinancialPing::FormRequest: request is NULL");
99 ScopedRlzValueStoreLock lock
;
100 RlzValueStore
* store
= lock
.GetStore();
101 if (!store
|| !store
->HasAccess(RlzValueStore::kReadAccess
))
104 if (!access_points
) {
105 ASSERT_STRING("FinancialPing::FormRequest: access_points is NULL");
109 if (!product_signature
) {
110 ASSERT_STRING("FinancialPing::FormRequest: product_signature is NULL");
114 if (!SupplementaryBranding::GetBrand().empty()) {
115 if (SupplementaryBranding::GetBrand() != product_brand
) {
116 ASSERT_STRING("FinancialPing::FormRequest: supplementary branding bad");
121 base::StringAppendF(request
, "%s?", kFinancialPingPath
);
123 // Add the signature, brand, product id and language.
124 base::StringAppendF(request
, "%s=%s", kProductSignatureCgiVariable
,
127 base::StringAppendF(request
, "&%s=%s", kProductBrandCgiVariable
,
131 base::StringAppendF(request
, "&%s=%s", kProductIdCgiVariable
, product_id
);
134 base::StringAppendF(request
, "&%s=%s", kProductLanguageCgiVariable
,
137 // Add the product events.
138 char cgi
[kMaxCgiLength
+ 1];
140 bool has_events
= GetProductEventsAsCgi(product
, cgi
, arraysize(cgi
));
142 base::StringAppendF(request
, "&%s", cgi
);
144 // If we don't have any events, we should ping all the AP's on the system
145 // that we know about and have a current RLZ value, even if they are not
146 // used by this product.
147 AccessPoint all_points
[LAST_ACCESS_POINT
];
149 char rlz
[kMaxRlzLength
+ 1];
151 for (int ap
= NO_ACCESS_POINT
+ 1; ap
< LAST_ACCESS_POINT
; ap
++) {
153 AccessPoint point
= static_cast<AccessPoint
>(ap
);
154 if (GetAccessPointRlz(point
, rlz
, arraysize(rlz
)) &&
156 all_points
[idx
++] = point
;
158 all_points
[idx
] = NO_ACCESS_POINT
;
161 // Add the RLZ's and the DCC if needed. This is the same as get PingParams.
162 // This will also include the RLZ Exchange Protocol CGI Argument.
164 if (GetPingParams(product
, has_events
? access_points
: all_points
,
165 cgi
, arraysize(cgi
)))
166 base::StringAppendF(request
, "&%s", cgi
);
168 if (has_events
&& !exclude_machine_id
) {
169 std::string machine_id
;
170 if (GetMachineId(&machine_id
)) {
171 base::StringAppendF(request
, "&%s=%s", kMachineIdCgiVariable
,
179 #if defined(RLZ_NETWORK_IMPLEMENTATION_CHROME_NET)
180 // The URLRequestContextGetter used by FinancialPing::PingServer().
181 net::URLRequestContextGetter
* g_context
;
183 bool FinancialPing::SetURLRequestContext(
184 net::URLRequestContextGetter
* context
) {
191 class FinancialPingUrlFetcherDelegate
: public net::URLFetcherDelegate
{
193 FinancialPingUrlFetcherDelegate(const base::Closure
& callback
)
194 : callback_(callback
) {
196 virtual void OnURLFetchComplete(const net::URLFetcher
* source
) OVERRIDE
;
199 base::Closure callback_
;
202 void FinancialPingUrlFetcherDelegate::OnURLFetchComplete(
203 const net::URLFetcher
* source
) {
211 bool FinancialPing::PingServer(const char* request
, std::string
* response
) {
217 #if defined(RLZ_NETWORK_IMPLEMENTATION_WIN_INET)
218 // Initialize WinInet.
219 InternetHandle inet_handle
= InternetOpenA(kFinancialPingUserAgent
,
220 INTERNET_OPEN_TYPE_PRECONFIG
,
225 // Open network connection.
226 InternetHandle connection_handle
= InternetConnectA(inet_handle
,
227 kFinancialServer
, kFinancialPort
, "", "", INTERNET_SERVICE_HTTP
,
228 INTERNET_FLAG_NO_CACHE_WRITE
, 0);
229 if (!connection_handle
)
232 // Prepare the HTTP request.
233 InternetHandle http_handle
= HttpOpenRequestA(connection_handle
,
234 "GET", request
, NULL
, NULL
, kFinancialPingResponseObjects
,
235 INTERNET_FLAG_NO_CACHE_WRITE
| INTERNET_FLAG_NO_COOKIES
, NULL
);
239 // Timeouts are probably:
240 // INTERNET_OPTION_SEND_TIMEOUT, INTERNET_OPTION_RECEIVE_TIMEOUT
242 // Send the HTTP request. Note: Fails if user is working in off-line mode.
243 if (!HttpSendRequest(http_handle
, NULL
, 0, NULL
, 0))
246 // Check the response status.
248 DWORD status_size
= sizeof(status
);
249 if (!HttpQueryInfo(http_handle
, HTTP_QUERY_STATUS_CODE
|
250 HTTP_QUERY_FLAG_NUMBER
, &status
, &status_size
, NULL
) ||
254 // Get the response text.
255 scoped_ptr
<char[]> buffer(new char[kMaxPingResponseLength
]);
256 if (buffer
.get() == NULL
)
259 DWORD bytes_read
= 0;
260 while (InternetReadFile(http_handle
, buffer
.get(), kMaxPingResponseLength
,
261 &bytes_read
) && bytes_read
> 0) {
262 response
->append(buffer
.get(), bytes_read
);
268 // Browser shutdown will cause the context to be reset to NULL.
272 // Run a blocking event loop to match the win inet implementation.
273 scoped_ptr
<base::MessageLoop
> message_loop
;
274 // Ensure that we have a MessageLoop.
275 if (!base::MessageLoop::current())
276 message_loop
.reset(new base::MessageLoop
);
278 FinancialPingUrlFetcherDelegate
delegate(loop
.QuitClosure());
280 std::string url
= base::StringPrintf("http://%s:%d%s",
281 kFinancialServer
, kFinancialPort
,
284 scoped_ptr
<net::URLFetcher
> fetcher(net::URLFetcher::Create(
285 GURL(url
), net::URLFetcher::GET
, &delegate
));
287 fetcher
->SetLoadFlags(net::LOAD_DISABLE_CACHE
|
288 net::LOAD_DO_NOT_SEND_AUTH_DATA
|
289 net::LOAD_DO_NOT_PROMPT_FOR_LOGIN
|
290 net::LOAD_DO_NOT_SEND_COOKIES
|
291 net::LOAD_DO_NOT_SAVE_COOKIES
);
293 // Ensure rlz_lib::SetURLRequestContext() has been called before sending
295 fetcher
->SetRequestContext(g_context
);
297 const base::TimeDelta kTimeout
= base::TimeDelta::FromMinutes(5);
298 base::MessageLoop::ScopedNestableTaskAllower
allow_nested(
299 base::MessageLoop::current());
300 base::MessageLoop::current()->PostTask(
302 base::Bind(&net::URLFetcher::Start
, base::Unretained(fetcher
.get())));
303 base::MessageLoop::current()->PostDelayedTask(
304 FROM_HERE
, loop
.QuitClosure(), kTimeout
);
308 if (fetcher
->GetResponseCode() != 200)
311 return fetcher
->GetResponseAsString(response
);
315 bool FinancialPing::IsPingTime(Product product
, bool no_delay
) {
316 ScopedRlzValueStoreLock lock
;
317 RlzValueStore
* store
= lock
.GetStore();
318 if (!store
|| !store
->HasAccess(RlzValueStore::kReadAccess
))
322 if (!store
->ReadPingTime(product
, &last_ping
))
325 uint64 now
= GetSystemTimeAsInt64();
326 int64 interval
= now
- last_ping
;
328 // If interval is negative, clock was probably reset. So ping.
332 // Check if this product has any unreported events.
333 char cgi
[kMaxCgiLength
+ 1];
335 bool has_events
= GetProductEventsAsCgi(product
, cgi
, arraysize(cgi
));
336 if (no_delay
&& has_events
)
339 return interval
>= (has_events
? kEventsPingInterval
: kNoEventsPingInterval
);
343 bool FinancialPing::UpdateLastPingTime(Product product
) {
344 ScopedRlzValueStoreLock lock
;
345 RlzValueStore
* store
= lock
.GetStore();
346 if (!store
|| !store
->HasAccess(RlzValueStore::kWriteAccess
))
349 uint64 now
= GetSystemTimeAsInt64();
350 return store
->WritePingTime(product
, now
);
354 bool FinancialPing::ClearLastPingTime(Product product
) {
355 ScopedRlzValueStoreLock lock
;
356 RlzValueStore
* store
= lock
.GetStore();
357 if (!store
|| !store
->HasAccess(RlzValueStore::kWriteAccess
))
359 return store
->ClearPingTime(product
);