GTMSessionFetcherLogging.m 36 KB

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