MultipartMessageHeader.m 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. //
  2. // MultipartMessagePart.m
  3. // HttpServer
  4. //
  5. // Created by Валерий Гаврилов on 29.03.12.
  6. // Copyright (c) 2012 LLC "Online Publishing Partners" (onlinepp.ru). All rights reserved.
  7. #import "MultipartMessageHeader.h"
  8. #import "MultipartMessageHeaderField.h"
  9. #import "HTTPLogging.h"
  10. //-----------------------------------------------------------------
  11. #pragma mark log level
  12. #ifdef DEBUG
  13. static const int httpLogLevel = HTTP_LOG_LEVEL_WARN;
  14. #else
  15. static const int httpLogLevel = HTTP_LOG_LEVEL_WARN;
  16. #endif
  17. //-----------------------------------------------------------------
  18. // implementation MultipartMessageHeader
  19. //-----------------------------------------------------------------
  20. @implementation MultipartMessageHeader
  21. @synthesize fields,encoding;
  22. - (id) initWithData:(NSData *)data formEncoding:(NSStringEncoding) formEncoding {
  23. if( nil == (self = [super init]) ) {
  24. return self;
  25. }
  26. fields = [[NSMutableDictionary alloc] initWithCapacity:1];
  27. // In case encoding is not mentioned,
  28. encoding = contentTransferEncoding_unknown;
  29. char* bytes = (char*)data.bytes;
  30. NSUInteger length = data.length;
  31. int offset = 0;
  32. // split header into header fields, separated by \r\n
  33. uint16_t fields_separator = 0x0A0D; // \r\n
  34. while( offset < length - 2 ) {
  35. // the !isspace condition is to support header unfolding
  36. if( (*(uint16_t*) (bytes+offset) == fields_separator) && ((offset == length - 2) || !(isspace(bytes[offset+2])) )) {
  37. NSData* fieldData = [NSData dataWithBytesNoCopy:bytes length:offset freeWhenDone:NO];
  38. MultipartMessageHeaderField* field = [[MultipartMessageHeaderField alloc] initWithData: fieldData contentEncoding:formEncoding];
  39. if( field ) {
  40. [fields setObject:field forKey:field.name];
  41. HTTPLogVerbose(@"MultipartFormDataParser: Processed Header field '%@'",field.name);
  42. }
  43. else {
  44. NSString* fieldStr = [[NSString alloc] initWithData:fieldData encoding:NSASCIIStringEncoding];
  45. HTTPLogWarn(@"MultipartFormDataParser: Failed to parse MIME header field. Input ASCII string:%@",fieldStr);
  46. }
  47. // move to the next header field
  48. bytes += offset + 2;
  49. length -= offset + 2;
  50. offset = 0;
  51. continue;
  52. }
  53. ++ offset;
  54. }
  55. if( !fields.count ) {
  56. // it was an empty header.
  57. // we have to set default values.
  58. // default header.
  59. [fields setObject:@"text/plain" forKey:@"Content-Type"];
  60. }
  61. return self;
  62. }
  63. - (NSString *)description {
  64. return [NSString stringWithFormat:@"%@",fields];
  65. }
  66. @end