summaryrefslogtreecommitdiffstats
path: root/toolkit/components/telemetry/pingsender/pingsender_win.cpp
blob: 6b7b7915377e6e405f9d6dbed3330449a037cf61 (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
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* 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 <string>

#include <direct.h>
#include <windows.h>
#include <wininet.h>

namespace PingSender {

using std::string;

/**
 * A helper to automatically close internet handles when they go out of scope
 */
class ScopedHInternet {
 public:
  explicit ScopedHInternet(HINTERNET handle) : mHandle(handle) {}

  ~ScopedHInternet() {
    if (mHandle) {
      InternetCloseHandle(mHandle);
    }
  }

  bool empty() { return (mHandle == nullptr); }
  HINTERNET get() { return mHandle; }

 private:
  HINTERNET mHandle;
};

const size_t kUrlComponentsSchemeLength = 256;
const size_t kUrlComponentsHostLength = 256;
const size_t kUrlComponentsPathLength = 256;

/**
 * Post the specified payload to a telemetry server
 *
 * @param url The URL of the telemetry server
 * @param payload The ping payload
 */
bool Post(const string& url, const string& payload) {
  char scheme[kUrlComponentsSchemeLength];
  char host[kUrlComponentsHostLength];
  char path[kUrlComponentsPathLength];

  URL_COMPONENTS components = {};
  components.dwStructSize = sizeof(components);
  components.lpszScheme = scheme;
  components.dwSchemeLength = kUrlComponentsSchemeLength;
  components.lpszHostName = host;
  components.dwHostNameLength = kUrlComponentsHostLength;
  components.lpszUrlPath = path;
  components.dwUrlPathLength = kUrlComponentsPathLength;

  if (!InternetCrackUrl(url.c_str(), url.size(), 0, &components)) {
    PINGSENDER_LOG("ERROR: Could not separate the URL components\n");
    return false;
  }

  if (!IsValidDestination(host)) {
    PINGSENDER_LOG("ERROR: Invalid destination host '%s'\n", host);
    return false;
  }

  ScopedHInternet internet(InternetOpen(kUserAgent,
                                        INTERNET_OPEN_TYPE_PRECONFIG,
                                        /* lpszProxyName */ NULL,
                                        /* lpszProxyBypass */ NULL,
                                        /* dwFlags */ 0));

  if (internet.empty()) {
    PINGSENDER_LOG("ERROR: Could not open wininet internet handle\n");
    return false;
  }

  DWORD timeout = static_cast<DWORD>(kConnectionTimeoutMs);
  bool rv = InternetSetOption(internet.get(), INTERNET_OPTION_CONNECT_TIMEOUT,
                              &timeout, sizeof(timeout));
  if (!rv) {
    PINGSENDER_LOG("ERROR: Could not set the connection timeout\n");
    return false;
  }

  ScopedHInternet connection(
      InternetConnect(internet.get(), host, components.nPort,
                      /* lpszUsername */ NULL,
                      /* lpszPassword */ NULL, INTERNET_SERVICE_HTTP,
                      /* dwFlags */ 0,
                      /* dwContext */ NULL));

  if (connection.empty()) {
    PINGSENDER_LOG("ERROR: Could not connect\n");
    return false;
  }

  DWORD flags = ((strcmp(scheme, "https") == 0) ? INTERNET_FLAG_SECURE : 0) |
                INTERNET_FLAG_NO_COOKIES;
  ScopedHInternet request(HttpOpenRequest(connection.get(), "POST", path,
                                          /* lpszVersion */ NULL,
                                          /* lpszReferer */ NULL,
                                          /* lplpszAcceptTypes */ NULL, flags,
                                          /* dwContext */ NULL));

  if (request.empty()) {
    PINGSENDER_LOG("ERROR: Could not open HTTP POST request\n");
    return false;
  }

  // Build a string containing all the headers.
  std::string headers = GenerateDateHeader() + "\r\n";
  headers += kCustomVersionHeader;
  headers += "\r\n";
  headers += kContentEncodingHeader;

  rv = HttpSendRequest(request.get(), headers.c_str(), -1L,
                       (LPVOID)payload.c_str(), payload.size());
  if (!rv) {
    PINGSENDER_LOG("ERROR: Could not execute HTTP POST request\n");
    return false;
  }

  // HttpSendRequest doesn't fail if we hit an HTTP error, so manually check
  // for errors. Please note that this is not needed on the Linux/MacOS version
  // of the pingsender, as libcurl already automatically fails on HTTP errors.
  DWORD statusCode = 0;
  DWORD bufferLength = sizeof(DWORD);
  rv = HttpQueryInfo(
      request.get(),
      /* dwInfoLevel */ HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER,
      /* lpvBuffer */ &statusCode,
      /* lpdwBufferLength */ &bufferLength,
      /* lpdwIndex */ NULL);
  if (!rv) {
    PINGSENDER_LOG("ERROR: Could not get the HTTP status code\n");
    return false;
  }

  if (statusCode != 200) {
    PINGSENDER_LOG("ERROR: Error submitting the HTTP request: code %lu\n",
                   statusCode);
    return false;
  }

  return rv;
}

void ChangeCurrentWorkingDirectory(const string& pingPath) {
  char fullPath[MAX_PATH + 1] = {};
  if (!_fullpath(fullPath, pingPath.c_str(), sizeof(fullPath))) {
    PINGSENDER_LOG("Could not build the full path to the ping\n");
    return;
  }

  char drive[_MAX_DRIVE] = {};
  char dir[_MAX_DIR] = {};
  if (_splitpath_s(fullPath, drive, sizeof(drive), dir, sizeof(dir), nullptr, 0,
                   nullptr, 0)) {
    PINGSENDER_LOG("Could not split the current path\n");
    return;
  }

  char cwd[MAX_PATH + 1] = {};
  if (_makepath_s(cwd, sizeof(cwd), drive, dir, nullptr, nullptr)) {
    PINGSENDER_LOG("Could not assemble the path for the new cwd\n");
    return;
  }

  if (_chdir(cwd) == -1) {
    PINGSENDER_LOG("Could not change the current working directory\n");
  }
}

}  // namespace PingSender