You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

976 lines
39 KiB

6 years ago
  1. /* Copyright 2014 Google Inc. All rights reserved.
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. #if !defined(__has_feature) || !__has_feature(objc_arc)
  16. #error "This file requires ARC support."
  17. #endif
  18. #include <sys/stat.h>
  19. #include <unistd.h>
  20. #import "GTMSessionFetcherLogging.h"
  21. #ifndef STRIP_GTM_FETCH_LOGGING
  22. #error GTMSessionFetcher headers should have defaulted this if it wasn't already defined.
  23. #endif
  24. #if !STRIP_GTM_FETCH_LOGGING
  25. // Sensitive credential strings are replaced in logs with _snip_
  26. //
  27. // Apps that must see the contents of sensitive tokens can set this to 1
  28. #ifndef SKIP_GTM_FETCH_LOGGING_SNIPPING
  29. #define SKIP_GTM_FETCH_LOGGING_SNIPPING 0
  30. #endif
  31. // If GTMReadMonitorInputStream is available, it can be used for
  32. // capturing uploaded streams of data
  33. //
  34. // We locally declare methods of GTMReadMonitorInputStream so we
  35. // do not need to import the header, as some projects may not have it available
  36. #if !GTMSESSION_BUILD_COMBINED_SOURCES
  37. @interface GTMReadMonitorInputStream : NSInputStream
  38. + (instancetype)inputStreamWithStream:(NSInputStream *)input;
  39. @property (assign) id readDelegate;
  40. @property (assign) SEL readSelector;
  41. @end
  42. #else
  43. @class GTMReadMonitorInputStream;
  44. #endif // !GTMSESSION_BUILD_COMBINED_SOURCES
  45. @interface GTMSessionFetcher (GTMHTTPFetcherLoggingUtilities)
  46. + (NSString *)headersStringForDictionary:(NSDictionary *)dict;
  47. + (NSString *)snipSubstringOfString:(NSString *)originalStr
  48. betweenStartString:(NSString *)startStr
  49. endString:(NSString *)endStr;
  50. - (void)inputStream:(GTMReadMonitorInputStream *)stream
  51. readIntoBuffer:(void *)buffer
  52. length:(int64_t)length;
  53. @end
  54. @implementation GTMSessionFetcher (GTMSessionFetcherLogging)
  55. // fetchers come and fetchers go, but statics are forever
  56. static BOOL gIsLoggingEnabled = NO;
  57. static BOOL gIsLoggingToFile = YES;
  58. static NSString *gLoggingDirectoryPath = nil;
  59. static NSString *gLogDirectoryForCurrentRun = nil;
  60. static NSString *gLoggingDateStamp = nil;
  61. static NSString *gLoggingProcessName = nil;
  62. + (void)setLoggingDirectory:(NSString *)path {
  63. gLoggingDirectoryPath = [path copy];
  64. }
  65. + (NSString *)loggingDirectory {
  66. if (!gLoggingDirectoryPath) {
  67. NSArray *paths = nil;
  68. #if TARGET_IPHONE_SIMULATOR
  69. // default to a directory called GTMHTTPDebugLogs into a sandbox-safe
  70. // directory that a developer can find easily, the application home
  71. paths = @[ NSHomeDirectory() ];
  72. #elif TARGET_OS_IPHONE
  73. // Neither ~/Desktop nor ~/Home is writable on an actual iOS, watchOS, or tvOS device.
  74. // Put it in ~/Documents.
  75. paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  76. #else
  77. // default to a directory called GTMHTTPDebugLogs in the desktop folder
  78. paths = NSSearchPathForDirectoriesInDomains(NSDesktopDirectory, NSUserDomainMask, YES);
  79. #endif
  80. NSString *desktopPath = paths.firstObject;
  81. if (desktopPath) {
  82. NSString *const kGTMLogFolderName = @"GTMHTTPDebugLogs";
  83. NSString *logsFolderPath = [desktopPath stringByAppendingPathComponent:kGTMLogFolderName];
  84. NSFileManager *fileMgr = [NSFileManager defaultManager];
  85. BOOL isDir;
  86. BOOL doesFolderExist = [fileMgr fileExistsAtPath:logsFolderPath isDirectory:&isDir];
  87. if (!doesFolderExist) {
  88. // make the directory
  89. doesFolderExist = [fileMgr createDirectoryAtPath:logsFolderPath
  90. withIntermediateDirectories:YES
  91. attributes:nil
  92. error:NULL];
  93. }
  94. if (doesFolderExist) {
  95. // it's there; store it in the global
  96. gLoggingDirectoryPath = [logsFolderPath copy];
  97. }
  98. }
  99. }
  100. return gLoggingDirectoryPath;
  101. }
  102. + (void)setLogDirectoryForCurrentRun:(NSString *)logDirectoryForCurrentRun {
  103. // Set the path for this run's logs.
  104. gLogDirectoryForCurrentRun = [logDirectoryForCurrentRun copy];
  105. }
  106. + (NSString *)logDirectoryForCurrentRun {
  107. // make a directory for this run's logs, like SyncProto_logs_10-16_01-56-58PM
  108. if (gLogDirectoryForCurrentRun) return gLogDirectoryForCurrentRun;
  109. NSString *parentDir = [self loggingDirectory];
  110. NSString *logNamePrefix = [self processNameLogPrefix];
  111. NSString *dateStamp = [self loggingDateStamp];
  112. NSString *dirName = [NSString stringWithFormat:@"%@%@", logNamePrefix, dateStamp];
  113. NSString *logDirectory = [parentDir stringByAppendingPathComponent:dirName];
  114. if (gIsLoggingToFile) {
  115. NSFileManager *fileMgr = [NSFileManager defaultManager];
  116. // Be sure that the first time this app runs, it's not writing to a preexisting folder
  117. static BOOL gShouldReuseFolder = NO;
  118. if (!gShouldReuseFolder) {
  119. gShouldReuseFolder = YES;
  120. NSString *origLogDir = logDirectory;
  121. for (int ctr = 2; ctr < 20; ++ctr) {
  122. if (![fileMgr fileExistsAtPath:logDirectory]) break;
  123. // append a digit
  124. logDirectory = [origLogDir stringByAppendingFormat:@"_%d", ctr];
  125. }
  126. }
  127. if (![fileMgr createDirectoryAtPath:logDirectory
  128. withIntermediateDirectories:YES
  129. attributes:nil
  130. error:NULL]) return nil;
  131. }
  132. gLogDirectoryForCurrentRun = logDirectory;
  133. return gLogDirectoryForCurrentRun;
  134. }
  135. + (void)setLoggingEnabled:(BOOL)isLoggingEnabled {
  136. gIsLoggingEnabled = isLoggingEnabled;
  137. }
  138. + (BOOL)isLoggingEnabled {
  139. return gIsLoggingEnabled;
  140. }
  141. + (void)setLoggingToFileEnabled:(BOOL)isLoggingToFileEnabled {
  142. gIsLoggingToFile = isLoggingToFileEnabled;
  143. }
  144. + (BOOL)isLoggingToFileEnabled {
  145. return gIsLoggingToFile;
  146. }
  147. + (void)setLoggingProcessName:(NSString *)processName {
  148. gLoggingProcessName = [processName copy];
  149. }
  150. + (NSString *)loggingProcessName {
  151. // get the process name (once per run) replacing spaces with underscores
  152. if (!gLoggingProcessName) {
  153. NSString *procName = [[NSProcessInfo processInfo] processName];
  154. gLoggingProcessName = [procName stringByReplacingOccurrencesOfString:@" " withString:@"_"];
  155. }
  156. return gLoggingProcessName;
  157. }
  158. + (void)setLoggingDateStamp:(NSString *)dateStamp {
  159. gLoggingDateStamp = [dateStamp copy];
  160. }
  161. + (NSString *)loggingDateStamp {
  162. // We'll pick one date stamp per run, so a run that starts at a later second
  163. // will get a unique results html file
  164. if (!gLoggingDateStamp) {
  165. // produce a string like 08-21_01-41-23PM
  166. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  167. [formatter setFormatterBehavior:NSDateFormatterBehavior10_4];
  168. [formatter setDateFormat:@"M-dd_hh-mm-ssa"];
  169. gLoggingDateStamp = [formatter stringFromDate:[NSDate date]];
  170. }
  171. return gLoggingDateStamp;
  172. }
  173. + (NSString *)processNameLogPrefix {
  174. static NSString *gPrefix = nil;
  175. if (!gPrefix) {
  176. NSString *processName = [self loggingProcessName];
  177. gPrefix = [[NSString alloc] initWithFormat:@"%@_log_", processName];
  178. }
  179. return gPrefix;
  180. }
  181. + (NSString *)symlinkNameSuffix {
  182. return @"_log_newest.html";
  183. }
  184. + (NSString *)htmlFileName {
  185. return @"aperçu_http_log.html";
  186. }
  187. + (void)deleteLogDirectoriesOlderThanDate:(NSDate *)cutoffDate {
  188. NSFileManager *fileMgr = [NSFileManager defaultManager];
  189. NSURL *parentDir = [NSURL fileURLWithPath:[[self class] loggingDirectory]];
  190. NSURL *logDirectoryForCurrentRun =
  191. [NSURL fileURLWithPath:[[self class] logDirectoryForCurrentRun]];
  192. NSError *error;
  193. NSArray *contents = [fileMgr contentsOfDirectoryAtURL:parentDir
  194. includingPropertiesForKeys:@[ NSURLContentModificationDateKey ]
  195. options:0
  196. error:&error];
  197. for (NSURL *itemURL in contents) {
  198. if ([itemURL isEqual:logDirectoryForCurrentRun]) continue;
  199. NSDate *modDate;
  200. if ([itemURL getResourceValue:&modDate
  201. forKey:NSURLContentModificationDateKey
  202. error:&error]) {
  203. if ([modDate compare:cutoffDate] == NSOrderedAscending) {
  204. if (![fileMgr removeItemAtURL:itemURL error:&error]) {
  205. NSLog(@"deleteLogDirectoriesOlderThanDate failed to delete %@: %@",
  206. itemURL.path, error);
  207. }
  208. }
  209. } else {
  210. NSLog(@"deleteLogDirectoriesOlderThanDate failed to get mod date of %@: %@",
  211. itemURL.path, error);
  212. }
  213. }
  214. }
  215. // formattedStringFromData returns a prettyprinted string for XML or JSON input,
  216. // and a plain string for other input data
  217. - (NSString *)formattedStringFromData:(NSData *)inputData
  218. contentType:(NSString *)contentType
  219. JSON:(NSDictionary **)outJSON {
  220. if (!inputData) return nil;
  221. // if the content type is JSON and we have the parsing class available, use that
  222. if ([contentType hasPrefix:@"application/json"] && inputData.length > 5) {
  223. // convert from JSON string to NSObjects and back to a formatted string
  224. NSMutableDictionary *obj = [NSJSONSerialization JSONObjectWithData:inputData
  225. options:NSJSONReadingMutableContainers
  226. error:NULL];
  227. if (obj) {
  228. if (outJSON) *outJSON = obj;
  229. if ([obj isKindOfClass:[NSMutableDictionary class]]) {
  230. // for security and privacy, omit OAuth 2 response access and refresh tokens
  231. if ([obj valueForKey:@"refresh_token"] != nil) {
  232. [obj setObject:@"_snip_" forKey:@"refresh_token"];
  233. }
  234. if ([obj valueForKey:@"access_token"] != nil) {
  235. [obj setObject:@"_snip_" forKey:@"access_token"];
  236. }
  237. }
  238. NSData *data = [NSJSONSerialization dataWithJSONObject:obj
  239. options:NSJSONWritingPrettyPrinted
  240. error:NULL];
  241. if (data) {
  242. NSString *jsonStr = [[NSString alloc] initWithData:data
  243. encoding:NSUTF8StringEncoding];
  244. return jsonStr;
  245. }
  246. }
  247. }
  248. #if !TARGET_OS_IPHONE && !GTM_SKIP_LOG_XMLFORMAT
  249. // verify that this data starts with the bytes indicating XML
  250. NSString *const kXMLLintPath = @"/usr/bin/xmllint";
  251. static BOOL gHasCheckedAvailability = NO;
  252. static BOOL gIsXMLLintAvailable = NO;
  253. if (!gHasCheckedAvailability) {
  254. gIsXMLLintAvailable = [[NSFileManager defaultManager] fileExistsAtPath:kXMLLintPath];
  255. gHasCheckedAvailability = YES;
  256. }
  257. if (gIsXMLLintAvailable
  258. && inputData.length > 5
  259. && strncmp(inputData.bytes, "<?xml", 5) == 0) {
  260. // call xmllint to format the data
  261. NSTask *task = [[NSTask alloc] init];
  262. [task setLaunchPath:kXMLLintPath];
  263. // use the dash argument to specify stdin as the source file
  264. [task setArguments:@[ @"--format", @"-" ]];
  265. [task setEnvironment:@{}];
  266. NSPipe *inputPipe = [NSPipe pipe];
  267. NSPipe *outputPipe = [NSPipe pipe];
  268. [task setStandardInput:inputPipe];
  269. [task setStandardOutput:outputPipe];
  270. [task launch];
  271. [[inputPipe fileHandleForWriting] writeData:inputData];
  272. [[inputPipe fileHandleForWriting] closeFile];
  273. // drain the stdout before waiting for the task to exit
  274. NSData *formattedData = [[outputPipe fileHandleForReading] readDataToEndOfFile];
  275. [task waitUntilExit];
  276. int status = [task terminationStatus];
  277. if (status == 0 && formattedData.length > 0) {
  278. // success
  279. inputData = formattedData;
  280. }
  281. }
  282. #else
  283. // we can't call external tasks on the iPhone; leave the XML unformatted
  284. #endif
  285. NSString *dataStr = [[NSString alloc] initWithData:inputData
  286. encoding:NSUTF8StringEncoding];
  287. return dataStr;
  288. }
  289. // stringFromStreamData creates a string given the supplied data
  290. //
  291. // If NSString can create a UTF-8 string from the data, then that is returned.
  292. //
  293. // Otherwise, this routine tries to find a MIME boundary at the beginning of the data block, and
  294. // uses that to break up the data into parts. Each part will be used to try to make a UTF-8 string.
  295. // For parts that fail, a replacement string showing the part header and <<n bytes>> is supplied
  296. // in place of the binary data.
  297. - (NSString *)stringFromStreamData:(NSData *)data
  298. contentType:(NSString *)contentType {
  299. if (!data) return nil;
  300. // optimistically, see if the whole data block is UTF-8
  301. NSString *streamDataStr = [self formattedStringFromData:data
  302. contentType:contentType
  303. JSON:NULL];
  304. if (streamDataStr) return streamDataStr;
  305. // Munge a buffer by replacing non-ASCII bytes with underscores, and turn that munged buffer an
  306. // NSString. That gives us a string we can use with NSScanner.
  307. NSMutableData *mutableData = [NSMutableData dataWithData:data];
  308. unsigned char *bytes = (unsigned char *)mutableData.mutableBytes;
  309. for (unsigned int idx = 0; idx < mutableData.length; ++idx) {
  310. if (bytes[idx] > 0x7F || bytes[idx] == 0) {
  311. bytes[idx] = '_';
  312. }
  313. }
  314. NSString *mungedStr = [[NSString alloc] initWithData:mutableData
  315. encoding:NSUTF8StringEncoding];
  316. if (mungedStr) {
  317. // scan for the boundary string
  318. NSString *boundary = nil;
  319. NSScanner *scanner = [NSScanner scannerWithString:mungedStr];
  320. if ([scanner scanUpToString:@"\r\n" intoString:&boundary]
  321. && [boundary hasPrefix:@"--"]) {
  322. // we found a boundary string; use it to divide the string into parts
  323. NSArray *mungedParts = [mungedStr componentsSeparatedByString:boundary];
  324. // look at each munged part in the original string, and try to convert those into UTF-8
  325. NSMutableArray *origParts = [NSMutableArray array];
  326. NSUInteger offset = 0;
  327. for (NSString *mungedPart in mungedParts) {
  328. NSUInteger partSize = mungedPart.length;
  329. NSData *origPartData = [data subdataWithRange:NSMakeRange(offset, partSize)];
  330. NSString *origPartStr = [[NSString alloc] initWithData:origPartData
  331. encoding:NSUTF8StringEncoding];
  332. if (origPartStr) {
  333. // we could make this original part into UTF-8; use the string
  334. [origParts addObject:origPartStr];
  335. } else {
  336. // this part can't be made into UTF-8; scan the header, if we can
  337. NSString *header = nil;
  338. NSScanner *headerScanner = [NSScanner scannerWithString:mungedPart];
  339. if (![headerScanner scanUpToString:@"\r\n\r\n" intoString:&header]) {
  340. // we couldn't find a header
  341. header = @"";
  342. }
  343. // make a part string with the header and <<n bytes>>
  344. NSString *binStr = [NSString stringWithFormat:@"\r%@\r<<%lu bytes>>\r",
  345. header, (long)(partSize - header.length)];
  346. [origParts addObject:binStr];
  347. }
  348. offset += partSize + boundary.length;
  349. }
  350. // rejoin the original parts
  351. streamDataStr = [origParts componentsJoinedByString:boundary];
  352. }
  353. }
  354. if (!streamDataStr) {
  355. // give up; just make a string showing the uploaded bytes
  356. streamDataStr = [NSString stringWithFormat:@"<<%u bytes>>", (unsigned int)data.length];
  357. }
  358. return streamDataStr;
  359. }
  360. // logFetchWithError is called following a successful or failed fetch attempt
  361. //
  362. // This method does all the work for appending to and creating log files
  363. - (void)logFetchWithError:(NSError *)error {
  364. if (![[self class] isLoggingEnabled]) return;
  365. NSString *logDirectory = [[self class] logDirectoryForCurrentRun];
  366. if (!logDirectory) return;
  367. NSString *processName = [[self class] loggingProcessName];
  368. // TODO: add Javascript to display response data formatted in hex
  369. // each response's NSData goes into its own xml or txt file, though all responses for this run of
  370. // the app share a main html file. This counter tracks all fetch responses for this app run.
  371. //
  372. // we'll use a local variable since this routine may be reentered while waiting for XML formatting
  373. // to be completed by an external task
  374. static int gResponseCounter = 0;
  375. int responseCounter = ++gResponseCounter;
  376. NSURLResponse *response = [self response];
  377. NSDictionary *responseHeaders = [self responseHeaders];
  378. NSString *responseDataStr = nil;
  379. NSDictionary *responseJSON = nil;
  380. // if there's response data, decide what kind of file to put it in based on the first bytes of the
  381. // file or on the mime type supplied by the server
  382. NSString *responseMIMEType = [response MIMEType];
  383. BOOL isResponseImage = NO;
  384. // file name for an image data file
  385. NSString *responseDataFileName = nil;
  386. int64_t responseDataLength = self.downloadedLength;
  387. if (responseDataLength > 0) {
  388. NSData *downloadedData = self.downloadedData;
  389. if (downloadedData == nil
  390. && responseDataLength > 0
  391. && responseDataLength < 20000
  392. && self.destinationFileURL) {
  393. // There's a download file that's not too big, so get the data to display from the downloaded
  394. // file.
  395. NSURL *destinationURL = self.destinationFileURL;
  396. downloadedData = [NSData dataWithContentsOfURL:destinationURL];
  397. }
  398. NSString *responseType = [responseHeaders valueForKey:@"Content-Type"];
  399. responseDataStr = [self formattedStringFromData:downloadedData
  400. contentType:responseType
  401. JSON:&responseJSON];
  402. NSString *responseDataExtn = nil;
  403. NSData *dataToWrite = nil;
  404. if (responseDataStr) {
  405. // we were able to make a UTF-8 string from the response data
  406. if ([responseMIMEType isEqual:@"application/atom+xml"]
  407. || [responseMIMEType hasSuffix:@"/xml"]) {
  408. responseDataExtn = @"xml";
  409. dataToWrite = [responseDataStr dataUsingEncoding:NSUTF8StringEncoding];
  410. }
  411. } else if ([responseMIMEType isEqual:@"image/jpeg"]) {
  412. responseDataExtn = @"jpg";
  413. dataToWrite = downloadedData;
  414. isResponseImage = YES;
  415. } else if ([responseMIMEType isEqual:@"image/gif"]) {
  416. responseDataExtn = @"gif";
  417. dataToWrite = downloadedData;
  418. isResponseImage = YES;
  419. } else if ([responseMIMEType isEqual:@"image/png"]) {
  420. responseDataExtn = @"png";
  421. dataToWrite = downloadedData;
  422. isResponseImage = YES;
  423. } else {
  424. // add more non-text types here
  425. }
  426. // if we have an extension, save the raw data in a file with that extension
  427. if (responseDataExtn && dataToWrite) {
  428. // generate a response file base name like
  429. NSString *responseBaseName = [NSString stringWithFormat:@"fetch_%d_response", responseCounter];
  430. responseDataFileName = [responseBaseName stringByAppendingPathExtension:responseDataExtn];
  431. NSString *responseDataFilePath = [logDirectory stringByAppendingPathComponent:responseDataFileName];
  432. NSError *downloadedError = nil;
  433. if (gIsLoggingToFile && ![dataToWrite writeToFile:responseDataFilePath
  434. options:0
  435. error:&downloadedError]) {
  436. NSLog(@"%@ logging write error:%@ (%@)", [self class], downloadedError, responseDataFileName);
  437. }
  438. }
  439. }
  440. // we'll have one main html file per run of the app
  441. NSString *htmlName = [[self class] htmlFileName];
  442. NSString *htmlPath =[logDirectory stringByAppendingPathComponent:htmlName];
  443. // if the html file exists (from logging previous fetches) we don't need
  444. // to re-write the header or the scripts
  445. NSFileManager *fileMgr = [NSFileManager defaultManager];
  446. BOOL didFileExist = [fileMgr fileExistsAtPath:htmlPath];
  447. NSMutableString* outputHTML = [NSMutableString string];
  448. // we need a header to say we'll have UTF-8 text
  449. if (!didFileExist) {
  450. [outputHTML appendFormat:@"<html><head><meta http-equiv=\"content-type\" "
  451. "content=\"text/html; charset=UTF-8\"><title>%@ HTTP fetch log %@</title>",
  452. processName, [[self class] loggingDateStamp]];
  453. }
  454. // now write the visible html elements
  455. NSString *copyableFileName = [NSString stringWithFormat:@"fetch_%d.txt", responseCounter];
  456. NSDate *now = [NSDate date];
  457. // write the date & time, the comment, and the link to the plain-text (copyable) log
  458. [outputHTML appendFormat:@"<b>%@ &nbsp;&nbsp;&nbsp;&nbsp; ", now];
  459. NSString *comment = [self comment];
  460. if (comment.length > 0) {
  461. [outputHTML appendFormat:@"%@ &nbsp;&nbsp;&nbsp;&nbsp; ", comment];
  462. }
  463. [outputHTML appendFormat:@"</b><a href='%@'><i>request/response log</i></a><br>", copyableFileName];
  464. NSTimeInterval elapsed = -self.initialBeginFetchDate.timeIntervalSinceNow;
  465. [outputHTML appendFormat:@"elapsed: %5.3fsec<br>", elapsed];
  466. // write the request URL
  467. NSURLRequest *request = self.request;
  468. NSString *requestMethod = request.HTTPMethod;
  469. NSURL *requestURL = request.URL;
  470. // Save the request URL for next time in case this redirects.
  471. NSString *redirectedFromURLString = [self.redirectedFromURL absoluteString];
  472. self.redirectedFromURL = [requestURL copy];
  473. if (redirectedFromURLString) {
  474. [outputHTML appendFormat:@"<FONT COLOR='#990066'><i>redirected from %@</i></FONT><br>",
  475. redirectedFromURLString];
  476. }
  477. [outputHTML appendFormat:@"<b>request:</b> %@ <code>%@</code><br>\n", requestMethod, requestURL];
  478. // write the request headers
  479. NSDictionary *requestHeaders = request.allHTTPHeaderFields;
  480. NSUInteger numberOfRequestHeaders = requestHeaders.count;
  481. if (numberOfRequestHeaders > 0) {
  482. // Indicate if the request is authorized; warn if the request is authorized but non-SSL
  483. NSString *auth = [requestHeaders objectForKey:@"Authorization"];
  484. NSString *headerDetails = @"";
  485. if (auth) {
  486. BOOL isInsecure = [[requestURL scheme] isEqual:@"http"];
  487. if (isInsecure) {
  488. // 26A0 =
  489. headerDetails =
  490. @"&nbsp;&nbsp;&nbsp;<i>authorized, non-SSL</i><FONT COLOR='#FF00FF'> &#x26A0;</FONT> ";
  491. } else {
  492. headerDetails = @"&nbsp;&nbsp;&nbsp;<i>authorized</i>";
  493. }
  494. }
  495. NSString *cookiesHdr = [requestHeaders objectForKey:@"Cookie"];
  496. if (cookiesHdr) {
  497. headerDetails = [headerDetails stringByAppendingString:@"&nbsp;&nbsp;&nbsp;<i>cookies</i>"];
  498. }
  499. NSString *matchHdr = [requestHeaders objectForKey:@"If-Match"];
  500. if (matchHdr) {
  501. headerDetails = [headerDetails stringByAppendingString:@"&nbsp;&nbsp;&nbsp;<i>if-match</i>"];
  502. }
  503. matchHdr = [requestHeaders objectForKey:@"If-None-Match"];
  504. if (matchHdr) {
  505. headerDetails = [headerDetails stringByAppendingString:@"&nbsp;&nbsp;&nbsp;<i>if-none-match</i>"];
  506. }
  507. [outputHTML appendFormat:@"&nbsp;&nbsp; headers: %d %@<br>",
  508. (int)numberOfRequestHeaders, headerDetails];
  509. } else {
  510. [outputHTML appendFormat:@"&nbsp;&nbsp; headers: none<br>"];
  511. }
  512. // write the request post data
  513. NSData *bodyData = nil;
  514. NSData *loggedStreamData = self.loggedStreamData;
  515. if (loggedStreamData) {
  516. bodyData = loggedStreamData;
  517. } else {
  518. bodyData = self.bodyData;
  519. if (bodyData == nil) {
  520. bodyData = self.request.HTTPBody;
  521. }
  522. }
  523. uint64_t bodyDataLength = bodyData.length;
  524. if (bodyData.length == 0) {
  525. // If the data is in a body upload file URL, read that in if it's not huge.
  526. NSURL *bodyFileURL = self.bodyFileURL;
  527. if (bodyFileURL) {
  528. NSNumber *fileSizeNum = nil;
  529. NSError *fileSizeError = nil;
  530. if ([bodyFileURL getResourceValue:&fileSizeNum
  531. forKey:NSURLFileSizeKey
  532. error:&fileSizeError]) {
  533. bodyDataLength = [fileSizeNum unsignedLongLongValue];
  534. if (bodyDataLength > 0 && bodyDataLength < 50000) {
  535. bodyData = [NSData dataWithContentsOfURL:bodyFileURL
  536. options:NSDataReadingUncached
  537. error:&fileSizeError];
  538. }
  539. }
  540. }
  541. }
  542. NSString *bodyDataStr = nil;
  543. NSString *postType = [requestHeaders valueForKey:@"Content-Type"];
  544. if (bodyDataLength > 0) {
  545. [outputHTML appendFormat:@"&nbsp;&nbsp; data: %llu bytes, <code>%@</code><br>\n",
  546. bodyDataLength, postType ? postType : @"(no type)"];
  547. NSString *logRequestBody = self.logRequestBody;
  548. if (logRequestBody) {
  549. bodyDataStr = [logRequestBody copy];
  550. self.logRequestBody = nil;
  551. } else {
  552. bodyDataStr = [self stringFromStreamData:bodyData
  553. contentType:postType];
  554. if (bodyDataStr) {
  555. // remove OAuth 2 client secret and refresh token
  556. bodyDataStr = [[self class] snipSubstringOfString:bodyDataStr
  557. betweenStartString:@"client_secret="
  558. endString:@"&"];
  559. bodyDataStr = [[self class] snipSubstringOfString:bodyDataStr
  560. betweenStartString:@"refresh_token="
  561. endString:@"&"];
  562. // remove ClientLogin password
  563. bodyDataStr = [[self class] snipSubstringOfString:bodyDataStr
  564. betweenStartString:@"&Passwd="
  565. endString:@"&"];
  566. }
  567. }
  568. } else {
  569. // no post data
  570. }
  571. // write the response status, MIME type, URL
  572. NSInteger status = [self statusCode];
  573. if (response) {
  574. NSString *statusString = @"";
  575. if (status != 0) {
  576. if (status == 200 || status == 201) {
  577. statusString = [NSString stringWithFormat:@"%ld", (long)status];
  578. // report any JSON-RPC error
  579. if ([responseJSON isKindOfClass:[NSDictionary class]]) {
  580. NSDictionary *jsonError = [responseJSON objectForKey:@"error"];
  581. if ([jsonError isKindOfClass:[NSDictionary class]]) {
  582. NSString *jsonCode = [[jsonError valueForKey:@"code"] description];
  583. NSString *jsonMessage = [jsonError valueForKey:@"message"];
  584. if (jsonCode || jsonMessage) {
  585. // 2691 =
  586. NSString *const jsonErrFmt =
  587. @"&nbsp;&nbsp;&nbsp;<i>JSON error:</i> <FONT COLOR='#FF00FF'>%@ %@ &nbsp;&#x2691;</FONT>";
  588. statusString = [statusString stringByAppendingFormat:jsonErrFmt,
  589. jsonCode ? jsonCode : @"",
  590. jsonMessage ? jsonMessage : @""];
  591. }
  592. }
  593. }
  594. } else {
  595. // purple for anything other than 200 or 201
  596. NSString *flag = status >= 400 ? @"&nbsp;&#x2691;" : @""; // 2691 =
  597. NSString *explanation = [NSHTTPURLResponse localizedStringForStatusCode:status];
  598. NSString *const statusFormat = @"<FONT COLOR='#FF00FF'>%ld %@ %@</FONT>";
  599. statusString = [NSString stringWithFormat:statusFormat, (long)status, explanation, flag];
  600. }
  601. }
  602. // show the response URL only if it's different from the request URL
  603. NSString *responseURLStr = @"";
  604. NSURL *responseURL = response.URL;
  605. if (responseURL && ![responseURL isEqual:request.URL]) {
  606. NSString *const responseURLFormat =
  607. @"<FONT COLOR='#FF00FF'>response URL:</FONT> <code>%@</code><br>\n";
  608. responseURLStr = [NSString stringWithFormat:responseURLFormat, [responseURL absoluteString]];
  609. }
  610. [outputHTML appendFormat:@"<b>response:</b>&nbsp;&nbsp;status %@<br>\n%@",
  611. statusString, responseURLStr];
  612. // Write the response headers
  613. NSUInteger numberOfResponseHeaders = responseHeaders.count;
  614. if (numberOfResponseHeaders > 0) {
  615. // Indicate if the server is setting cookies
  616. NSString *cookiesSet = [responseHeaders valueForKey:@"Set-Cookie"];
  617. NSString *cookiesStr =
  618. cookiesSet ? @"&nbsp;&nbsp;<FONT COLOR='#990066'><i>sets cookies</i></FONT>" : @"";
  619. // Indicate if the server is redirecting
  620. NSString *location = [responseHeaders valueForKey:@"Location"];
  621. BOOL isRedirect = status >= 300 && status <= 399 && location != nil;
  622. NSString *redirectsStr =
  623. isRedirect ? @"&nbsp;&nbsp;<FONT COLOR='#990066'><i>redirects</i></FONT>" : @"";
  624. [outputHTML appendFormat:@"&nbsp;&nbsp; headers: %d %@ %@<br>\n",
  625. (int)numberOfResponseHeaders, cookiesStr, redirectsStr];
  626. } else {
  627. [outputHTML appendString:@"&nbsp;&nbsp; headers: none<br>\n"];
  628. }
  629. }
  630. // error
  631. if (error) {
  632. [outputHTML appendFormat:@"<b>Error:</b> %@ <br>\n", error.description];
  633. }
  634. // Write the response data
  635. if (responseDataFileName) {
  636. if (isResponseImage) {
  637. // Make a small inline image that links to the full image file
  638. [outputHTML appendFormat:@"&nbsp;&nbsp; data: %lld bytes, <code>%@</code><br>",
  639. responseDataLength, responseMIMEType];
  640. NSString *const fmt =
  641. @"<a href=\"%@\"><img src='%@' alt='image' style='border:solid thin;max-height:32'></a>\n";
  642. [outputHTML appendFormat:fmt, responseDataFileName, responseDataFileName];
  643. } else {
  644. // The response data was XML; link to the xml file
  645. NSString *const fmt =
  646. @"&nbsp;&nbsp; data: %lld bytes, <code>%@</code>&nbsp;&nbsp;&nbsp;<i><a href=\"%@\">%@</a></i>\n";
  647. [outputHTML appendFormat:fmt, responseDataLength, responseMIMEType,
  648. responseDataFileName, [responseDataFileName pathExtension]];
  649. }
  650. } else {
  651. // The response data was not an image; just show the length and MIME type
  652. [outputHTML appendFormat:@"&nbsp;&nbsp; data: %lld bytes, <code>%@</code>\n",
  653. responseDataLength, responseMIMEType ? responseMIMEType : @"(no response type)"];
  654. }
  655. // Make a single string of the request and response, suitable for copying
  656. // to the clipboard and pasting into a bug report
  657. NSMutableString *copyable = [NSMutableString string];
  658. if (comment) {
  659. [copyable appendFormat:@"%@\n\n", comment];
  660. }
  661. [copyable appendFormat:@"%@ elapsed: %5.3fsec\n", now, elapsed];
  662. if (redirectedFromURLString) {
  663. [copyable appendFormat:@"Redirected from %@\n", redirectedFromURLString];
  664. }
  665. [copyable appendFormat:@"Request: %@ %@\n", requestMethod, requestURL];
  666. if (requestHeaders.count > 0) {
  667. [copyable appendFormat:@"Request headers:\n%@\n",
  668. [[self class] headersStringForDictionary:requestHeaders]];
  669. }
  670. if (bodyDataLength > 0) {
  671. [copyable appendFormat:@"Request body: (%llu bytes)\n", bodyDataLength];
  672. if (bodyDataStr) {
  673. [copyable appendFormat:@"%@\n", bodyDataStr];
  674. }
  675. [copyable appendString:@"\n"];
  676. }
  677. if (response) {
  678. [copyable appendFormat:@"Response: status %d\n", (int) status];
  679. [copyable appendFormat:@"Response headers:\n%@\n",
  680. [[self class] headersStringForDictionary:responseHeaders]];
  681. [copyable appendFormat:@"Response body: (%lld bytes)\n", responseDataLength];
  682. if (responseDataLength > 0) {
  683. NSString *logResponseBody = self.logResponseBody;
  684. if (logResponseBody) {
  685. // The user has provided the response body text.
  686. responseDataStr = [logResponseBody copy];
  687. self.logResponseBody = nil;
  688. }
  689. if (responseDataStr != nil) {
  690. [copyable appendFormat:@"%@\n", responseDataStr];
  691. } else {
  692. // Even though it's redundant, we'll put in text to indicate that all the bytes are binary.
  693. if (self.destinationFileURL) {
  694. [copyable appendFormat:@"<<%lld bytes>> to file %@\n",
  695. responseDataLength, self.destinationFileURL.path];
  696. } else {
  697. [copyable appendFormat:@"<<%lld bytes>>\n", responseDataLength];
  698. }
  699. }
  700. }
  701. }
  702. if (error) {
  703. [copyable appendFormat:@"Error: %@\n", error];
  704. }
  705. // Save to log property before adding the separator
  706. self.log = copyable;
  707. [copyable appendString:@"-----------------------------------------------------------\n"];
  708. // Write the copyable version to another file (linked to at the top of the html file, above)
  709. //
  710. // Ideally, something to just copy this to the clipboard like
  711. // <span onCopy='window.event.clipboardData.setData(\"Text\",
  712. // \"copyable stuff\");return false;'>Copy here.</span>"
  713. // would work everywhere, but it only works in Safari as of 8/2010
  714. if (gIsLoggingToFile) {
  715. NSString *parentDir = [[self class] loggingDirectory];
  716. NSString *copyablePath = [logDirectory stringByAppendingPathComponent:copyableFileName];
  717. NSError *copyableError = nil;
  718. if (![copyable writeToFile:copyablePath
  719. atomically:NO
  720. encoding:NSUTF8StringEncoding
  721. error:&copyableError]) {
  722. // Error writing to file
  723. NSLog(@"%@ logging write error:%@ (%@)", [self class], copyableError, copyablePath);
  724. }
  725. [outputHTML appendString:@"<br><hr><p>"];
  726. // Append the HTML to the main output file
  727. const char* htmlBytes = outputHTML.UTF8String;
  728. NSOutputStream *stream = [NSOutputStream outputStreamToFileAtPath:htmlPath
  729. append:YES];
  730. [stream open];
  731. [stream write:(const uint8_t *) htmlBytes maxLength:strlen(htmlBytes)];
  732. [stream close];
  733. // Make a symlink to the latest html
  734. NSString *const symlinkNameSuffix = [[self class] symlinkNameSuffix];
  735. NSString *symlinkName = [processName stringByAppendingString:symlinkNameSuffix];
  736. NSString *symlinkPath = [parentDir stringByAppendingPathComponent:symlinkName];
  737. [fileMgr removeItemAtPath:symlinkPath error:NULL];
  738. [fileMgr createSymbolicLinkAtPath:symlinkPath
  739. withDestinationPath:htmlPath
  740. error:NULL];
  741. #if TARGET_OS_IPHONE
  742. static BOOL gReportedLoggingPath = NO;
  743. if (!gReportedLoggingPath) {
  744. gReportedLoggingPath = YES;
  745. NSLog(@"GTMSessionFetcher logging to \"%@\"", parentDir);
  746. }
  747. #endif
  748. }
  749. }
  750. - (NSInputStream *)loggedInputStreamForInputStream:(NSInputStream *)inputStream {
  751. if (!inputStream) return nil;
  752. if (![GTMSessionFetcher isLoggingEnabled]) return inputStream;
  753. [self clearLoggedStreamData]; // Clear any previous data.
  754. Class monitorClass = NSClassFromString(@"GTMReadMonitorInputStream");
  755. if (!monitorClass) {
  756. NSString const *str = @"<<Uploaded stream log unavailable without GTMReadMonitorInputStream>>";
  757. NSData *stringData = [str dataUsingEncoding:NSUTF8StringEncoding];
  758. [self appendLoggedStreamData:stringData];
  759. return inputStream;
  760. }
  761. inputStream = [monitorClass inputStreamWithStream:inputStream];
  762. GTMReadMonitorInputStream *readMonitorInputStream = (GTMReadMonitorInputStream *)inputStream;
  763. [readMonitorInputStream setReadDelegate:self];
  764. SEL readSel = @selector(inputStream:readIntoBuffer:length:);
  765. [readMonitorInputStream setReadSelector:readSel];
  766. return inputStream;
  767. }
  768. - (GTMSessionFetcherBodyStreamProvider)loggedStreamProviderForStreamProvider:
  769. (GTMSessionFetcherBodyStreamProvider)streamProvider {
  770. if (!streamProvider) return nil;
  771. if (![GTMSessionFetcher isLoggingEnabled]) return streamProvider;
  772. [self clearLoggedStreamData]; // Clear any previous data.
  773. Class monitorClass = NSClassFromString(@"GTMReadMonitorInputStream");
  774. if (!monitorClass) {
  775. NSString const *str = @"<<Uploaded stream log unavailable without GTMReadMonitorInputStream>>";
  776. NSData *stringData = [str dataUsingEncoding:NSUTF8StringEncoding];
  777. [self appendLoggedStreamData:stringData];
  778. return streamProvider;
  779. }
  780. GTMSessionFetcherBodyStreamProvider loggedStreamProvider =
  781. ^(GTMSessionFetcherBodyStreamProviderResponse response) {
  782. streamProvider(^(NSInputStream *bodyStream) {
  783. bodyStream = [self loggedInputStreamForInputStream:bodyStream];
  784. response(bodyStream);
  785. });
  786. };
  787. return loggedStreamProvider;
  788. }
  789. @end
  790. @implementation GTMSessionFetcher (GTMSessionFetcherLoggingUtilities)
  791. - (void)inputStream:(GTMReadMonitorInputStream *)stream
  792. readIntoBuffer:(void *)buffer
  793. length:(int64_t)length {
  794. // append the captured data
  795. NSData *data = [NSData dataWithBytesNoCopy:buffer
  796. length:(NSUInteger)length
  797. freeWhenDone:NO];
  798. [self appendLoggedStreamData:data];
  799. }
  800. #pragma mark Fomatting Utilities
  801. + (NSString *)snipSubstringOfString:(NSString *)originalStr
  802. betweenStartString:(NSString *)startStr
  803. endString:(NSString *)endStr {
  804. #if SKIP_GTM_FETCH_LOGGING_SNIPPING
  805. return originalStr;
  806. #else
  807. if (!originalStr) return nil;
  808. // Find the start string, and replace everything between it
  809. // and the end string (or the end of the original string) with "_snip_"
  810. NSRange startRange = [originalStr rangeOfString:startStr];
  811. if (startRange.location == NSNotFound) return originalStr;
  812. // We found the start string
  813. NSUInteger originalLength = originalStr.length;
  814. NSUInteger startOfTarget = NSMaxRange(startRange);
  815. NSRange targetAndRest = NSMakeRange(startOfTarget, originalLength - startOfTarget);
  816. NSRange endRange = [originalStr rangeOfString:endStr
  817. options:0
  818. range:targetAndRest];
  819. NSRange replaceRange;
  820. if (endRange.location == NSNotFound) {
  821. // Found no end marker so replace to end of string
  822. replaceRange = targetAndRest;
  823. } else {
  824. // Replace up to the endStr
  825. replaceRange = NSMakeRange(startOfTarget, endRange.location - startOfTarget);
  826. }
  827. NSString *result = [originalStr stringByReplacingCharactersInRange:replaceRange
  828. withString:@"_snip_"];
  829. return result;
  830. #endif // SKIP_GTM_FETCH_LOGGING_SNIPPING
  831. }
  832. + (NSString *)headersStringForDictionary:(NSDictionary *)dict {
  833. // Format the dictionary in http header style, like
  834. // Accept: application/json
  835. // Cache-Control: no-cache
  836. // Content-Type: application/json; charset=utf-8
  837. //
  838. // Pad the key names, but not beyond 16 chars, since long custom header
  839. // keys just create too much whitespace
  840. NSArray *keys = [dict.allKeys sortedArrayUsingSelector:@selector(compare:)];
  841. NSMutableString *str = [NSMutableString string];
  842. for (NSString *key in keys) {
  843. NSString *value = [dict valueForKey:key];
  844. if ([key isEqual:@"Authorization"]) {
  845. // Remove OAuth 1 token
  846. value = [[self class] snipSubstringOfString:value
  847. betweenStartString:@"oauth_token=\""
  848. endString:@"\""];
  849. // Remove OAuth 2 bearer token (draft 16, and older form)
  850. value = [[self class] snipSubstringOfString:value
  851. betweenStartString:@"Bearer "
  852. endString:@"\n"];
  853. value = [[self class] snipSubstringOfString:value
  854. betweenStartString:@"OAuth "
  855. endString:@"\n"];
  856. // Remove Google ClientLogin
  857. value = [[self class] snipSubstringOfString:value
  858. betweenStartString:@"GoogleLogin auth="
  859. endString:@"\n"];
  860. }
  861. [str appendFormat:@" %@: %@\n", key, value];
  862. }
  863. return str;
  864. }
  865. @end
  866. #endif // !STRIP_GTM_FETCH_LOGGING