summaryrefslogtreecommitdiffstats
path: root/ios/chrome/browser/crash_report/crash_report_background_uploader.mm
blob: 77384d952a9cd3d500ef07858c5c56b45957e16f (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
354
355
356
357
358
359
360
361
362
// 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.

#import "ios/chrome/browser/crash_report/crash_report_background_uploader.h"

#import <UIKit/UIKit.h>

#include "base/logging.h"
#include "base/mac/scoped_block.h"
#include "base/mac/scoped_nsobject.h"
#include "base/metrics/histogram.h"
#include "base/metrics/user_metrics_action.h"
#include "base/time/time.h"
#import "breakpad/src/client/ios/BreakpadController.h"
#include "ios/chrome/browser/experimental_flags.h"
#include "ios/web/public/user_metrics.h"

using base::UserMetricsAction;

namespace {

NSString* const kBackgroundReportUploader =
    @"com.google.chrome.breakpad.backgroundupload";
const char* const kUMAMobileCrashBackgroundUploadDelay =
    "CrashReport.CrashBackgroundUploadDelay";
const char* const kUMAMobilePendingReportsOnBackgroundWakeUp =
    "CrashReport.PendingReportsOnBackgroundWakeUp";
NSString* const kUploadedInBackground = @"uploaded_in_background";
NSString* const kReportsUploadedInBackground = @"ReportsUploadedInBackground";

NSString* CreateSessionIdentifierFromTask(NSURLSessionTask* task) {
  return [NSString stringWithFormat:@"%@.%ld", kBackgroundReportUploader,
                                    (unsigned long)[task taskIdentifier]];
}

}  // namespace

@interface UrlSessionDelegate : NSObject<NSURLSessionDelegate,
                                         NSURLSessionTaskDelegate,
                                         NSURLSessionDataDelegate>
+ (instancetype)sharedInstance;

// Sets the completion handler for the URL session current tasks. The
// |completionHandler| cannot be nil.
- (void)setSessionCompletionHandler:(ProceduralBlock)completionHandler;

@end

@implementation UrlSessionDelegate {
  // The completion handler to call when all tasks are completed.
  base::mac::ScopedBlock<ProceduralBlock> _sessionCompletionHandler;
  // The number of tasks in progress for the session.
  int _tasks;
  // Flag to indicate that URLSessionDidFinishEventsForBackgroundURLSession
  // has been called, so that no new task will be launched for this session.
  // It is safe to call completion handler when the pending tasks are completed.
  BOOL _didFinishEventsCalled;
}

+ (instancetype)sharedInstance {
  static UrlSessionDelegate* instance = [[UrlSessionDelegate alloc] init];
  return instance;
}

- (void)setSessionCompletionHandler:(ProceduralBlock)completionHandler {
  DCHECK(completionHandler);
  _sessionCompletionHandler.reset(completionHandler,
                                  base::scoped_policy::RETAIN);
  _didFinishEventsCalled = NO;
}

- (void)URLSession:(NSURLSession*)session
                   task:(NSURLSessionTask*)dataTask
    didReceiveChallenge:(NSURLAuthenticationChallenge*)challenge
      completionHandler:
          (void (^)(NSURLSessionAuthChallengeDisposition disposition,
                    NSURLCredential* credential))completionHandler {
  if (![challenge.protectionSpace.authenticationMethod
          isEqualToString:NSURLAuthenticationMethodServerTrust]) {
    completionHandler(NSURLSessionAuthChallengeUseCredential, nil);
    return;
  }
  NSString* identifier = CreateSessionIdentifierFromTask(dataTask);

  NSDictionary* configuration =
      [[NSUserDefaults standardUserDefaults] dictionaryForKey:identifier];
  NSString* host =
      [[NSURL URLWithString:[configuration objectForKey:@BREAKPAD_URL]] host];
  if ([challenge.protectionSpace.host isEqualToString:host]) {
    NSURLCredential* credential = [NSURLCredential
        credentialForTrust:challenge.protectionSpace.serverTrust];
    completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
    return;
  }
  completionHandler(NSURLSessionAuthChallengeUseCredential, nil);
}

- (void)URLSessionDidFinishEventsForBackgroundURLSession:
        (NSURLSession*)session {
  _didFinishEventsCalled = YES;
  [[NSOperationQueue mainQueue] addOperationWithBlock:^{
    [self callCompletionHandler];
  }];
}

- (void)taskFinished {
  DCHECK_GT(_tasks, 0);
  _tasks--;
  [[NSOperationQueue mainQueue] addOperationWithBlock:^{
    [self callCompletionHandler];
  }];
}

- (void)callCompletionHandler {
  if (_tasks > 0 || !_didFinishEventsCalled)
    return;
  if (_sessionCompletionHandler) {
    void (^completionHandler)() = _sessionCompletionHandler.get();
    completionHandler();
    _sessionCompletionHandler.reset();
  }
}

- (void)URLSession:(NSURLSession*)session
              dataTask:(NSURLSessionDataTask*)dataTask
    didReceiveResponse:(NSURLResponse*)response
     completionHandler:
         (void (^)(NSURLSessionResponseDisposition disposition))handler {
  handler(NSURLSessionResponseAllow);
}

- (void)URLSession:(NSURLSession*)session
          dataTask:(NSURLSessionDataTask*)dataTask
    didReceiveData:(NSData*)data {
  NSString* identifier = CreateSessionIdentifierFromTask(dataTask);

  NSDictionary* configuration =
      [[NSUserDefaults standardUserDefaults] dictionaryForKey:identifier];
  [[NSUserDefaults standardUserDefaults] removeObjectForKey:identifier];
  _tasks++;

  if (experimental_flags::IsAlertOnBackgroundUploadEnabled()) {
    base::scoped_nsobject<UILocalNotification> localNotification(
        [[UILocalNotification alloc] init]);
    localNotification.get().fireDate = [NSDate date];
    base::scoped_nsobject<NSString> reportId(
        [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    localNotification.get().alertBody = [NSString
        stringWithFormat:@"Crash report uploaded: %@", reportId.get()];
    [[UIApplication sharedApplication]
        scheduleLocalNotification:localNotification];
  }

  [[BreakpadController sharedInstance] withBreakpadRef:^(BreakpadRef ref) {
    BreakpadHandleNetworkResponse(ref, configuration, data, nil);
    dispatch_async(dispatch_get_main_queue(), ^{
      [self taskFinished];
    });
  }];
}

@end

@implementation CrashReportBackgroundUploader

@synthesize hasPendingCrashReportsToUploadAtStartup;

+ (instancetype)sharedInstance {
  static CrashReportBackgroundUploader* instance =
      [[CrashReportBackgroundUploader alloc] init];
  return instance;
}

+ (NSURLSession*)BreakpadBackgroundURLSessionWithCompletionHandler:
        (ProceduralBlock)completionHandler {
  static NSURLSession* session = nil;
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    NSURLSessionConfiguration* sessionConfig = [NSURLSessionConfiguration
        backgroundSessionConfigurationWithIdentifier:kBackgroundReportUploader];
    session = [NSURLSession
        sessionWithConfiguration:sessionConfig
                        delegate:[UrlSessionDelegate sharedInstance]
                   delegateQueue:[NSOperationQueue mainQueue]];
  });
  DCHECK(session);
  if (completionHandler) {
    [[UrlSessionDelegate sharedInstance]
        setSessionCompletionHandler:completionHandler];
  }
  return session;
}

+ (BOOL)sendNextReport:(NSDictionary*)nextReport
       withBreakpadRef:(BreakpadRef)ref {
  NSString* uploadURL =
      [NSString stringWithString:[nextReport valueForKey:@BREAKPAD_URL]];
  NSString* tmpDir = NSTemporaryDirectory();
  NSString* tmpFile = [tmpDir
      stringByAppendingPathComponent:
          [NSString
              stringWithFormat:@"%.0f.%@",
                               [NSDate timeIntervalSinceReferenceDate] * 1000.0,
                               @"txt"]];
  NSURL* fileURL = [NSURL fileURLWithPath:tmpFile];
  [nextReport setValue:[fileURL absoluteString] forKey:@BREAKPAD_URL];

#ifndef NDEBUG
  NSString* BreakpadMinidumpLocation = [NSHomeDirectory()
      stringByAppendingPathComponent:@"Library/Caches/Breakpad"];
  [nextReport setValue:BreakpadMinidumpLocation
                forKey:@kReporterMinidumpDirectoryKey];
  [nextReport setValue:BreakpadMinidumpLocation
                forKey:@BREAKPAD_DUMP_DIRECTORY];
#endif

  [[BreakpadController sharedInstance]
      threadUnsafeSendReportWithConfiguration:nextReport
                              withBreakpadRef:ref];

  NSFileManager* fileManager = [NSFileManager defaultManager];
  if (![fileManager fileExistsAtPath:tmpFile]) {
    return NO;
  }

  NSError* error;
  NSString* fileString =
      [NSString stringWithContentsOfFile:tmpFile
                                encoding:NSISOLatin1StringEncoding
                                   error:&error];

  // The HTTP content is a MIME multipart. The delimiter of the mime body must
  // be added to the HTTP headers.
  // A mime body is of the form
  // --{delimiter}
  // content 1
  // --{delimiter}
  // content 2
  // --{delimiter}--
  // The delimiter can be read on the first line of the file.
  NSString* delimiter =
      [[fileString componentsSeparatedByCharactersInSet:
                       [NSCharacterSet newlineCharacterSet]] firstObject];
  if (![delimiter hasPrefix:@"--"]) {
    [fileManager removeItemAtPath:tmpFile error:&error];
    return NO;
  }
  delimiter = [[delimiter
      stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]]
      substringFromIndex:2];

  NSMutableURLRequest* request =
      [NSMutableURLRequest requestWithURL:[NSURL URLWithString:uploadURL]];
  [request setHTTPMethod:@"POST"];
  [request setValue:[NSString
                        stringWithFormat:@"multipart/form-data; boundary=%@",
                                         delimiter]
      forHTTPHeaderField:@"Content-type"];
  [request setHTTPBody:[NSData dataWithContentsOfFile:tmpFile]];

  NSURLSession* session = [CrashReportBackgroundUploader
      BreakpadBackgroundURLSessionWithCompletionHandler:nil];
  NSURLSessionDataTask* dataTask =
      [session uploadTaskWithRequest:request fromFile:fileURL];

  NSString* identifier = CreateSessionIdentifierFromTask(dataTask);
  [[NSUserDefaults standardUserDefaults] setObject:nextReport
                                            forKey:identifier];

  [dataTask resume];
  return YES;
}

+ (void)performFetchWithCompletionHandler:
        (BackgroundFetchCompletionBlock)completionHandler {
  [[BreakpadController sharedInstance] stop];
  [[BreakpadController sharedInstance] setParametersToAddAtUploadTime:@{
    kUploadedInBackground : @"yes"
  }];
  [[BreakpadController sharedInstance] start:YES];
  [[BreakpadController sharedInstance] withBreakpadRef:^(BreakpadRef ref) {
    // Note that this processing will be done before |sendNextCrashReport|
    // starts uploading the crashes. The ordering is ensured here because both
    // the crash report processing and the upload enabling are handled by
    // posting blocks to a single |dispath_queue_t| in BreakpadController.
    [[BreakpadController sharedInstance] setUploadingEnabled:YES];
    [[BreakpadController sharedInstance]
        getNextReportConfigurationOrSendDelay:^(NSDictionary* nextReport,
                                                int delay) {
          BOOL reportToSend = NO;
          BOOL uploaded = NO;
          UMA_HISTOGRAM_COUNTS_100(kUMAMobilePendingReportsOnBackgroundWakeUp,
                                   BreakpadGetCrashReportCount(ref));
          if (delay == 0 && nextReport) {
            reportToSend = YES;
            NSNumber* crashTimeNum =
                [nextReport valueForKey:@BREAKPAD_PROCESS_CRASH_TIME];
            base::Time crashTime =
                base::Time::FromTimeT([crashTimeNum intValue]);
            base::Time now = base::Time::Now();
            UMA_HISTOGRAM_LONG_TIMES_100(kUMAMobileCrashBackgroundUploadDelay,
                                         now - crashTime);
            uploaded = [self sendNextReport:nextReport withBreakpadRef:ref];
          }
          int pendingReports = BreakpadGetCrashReportCount(ref);
          [[BreakpadController sharedInstance] setUploadingEnabled:NO];
          dispatch_async(dispatch_get_main_queue(), ^{
            if (reportToSend) {
              if (uploaded) {
                NSUserDefaults* defaults =
                    [NSUserDefaults standardUserDefaults];
                NSInteger uploadedCrashes =
                    [defaults integerForKey:kReportsUploadedInBackground];
                [defaults setInteger:(uploadedCrashes + 1)
                              forKey:kReportsUploadedInBackground];
                web::RecordAction(
                    UserMetricsAction("BackgroundUploadReportSucceeded"));

              } else {
                web::RecordAction(
                    UserMetricsAction("BackgroundUploadReportAborted"));
              }
            }
            if (uploaded && pendingReports) {
              completionHandler(UIBackgroundFetchResultNewData);
            } else if (pendingReports) {
              completionHandler(UIBackgroundFetchResultFailed);
            } else {
              [[UIApplication sharedApplication]
                  setMinimumBackgroundFetchInterval:
                      UIApplicationBackgroundFetchIntervalNever];
              completionHandler(UIBackgroundFetchResultNoData);
            }
          });
        }];
  }];
}

+ (BOOL)canHandleBackgroundURLSession:(NSString*)identifier {
  return [identifier isEqualToString:kBackgroundReportUploader];
}

+ (void)handleEventsForBackgroundURLSession:(NSString*)identifier
                          completionHandler:(ProceduralBlock)completionHandler {
  [CrashReportBackgroundUploader
      BreakpadBackgroundURLSessionWithCompletionHandler:completionHandler];
}

+ (BOOL)hasUploadedCrashReportsInBackground {
  NSInteger uploadedCrashReportsInBackgroundCount =
      [[NSUserDefaults standardUserDefaults]
          integerForKey:kReportsUploadedInBackground];
  return uploadedCrashReportsInBackgroundCount > 0;
}

+ (void)resetReportsUploadedInBackgroundCount {
  [[NSUserDefaults standardUserDefaults]
      removeObjectForKey:kReportsUploadedInBackground];
}

@end