GCDWebServer.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. /*
  2. Copyright (c) 2012-2014, Pierre-Olivier Latour
  3. All rights reserved.
  4. Redistribution and use in source and binary forms, with or without
  5. modification, are permitted provided that the following conditions are met:
  6. * Redistributions of source code must retain the above copyright
  7. notice, this list of conditions and the following disclaimer.
  8. * Redistributions in binary form must reproduce the above copyright
  9. notice, this list of conditions and the following disclaimer in the
  10. documentation and/or other materials provided with the distribution.
  11. * The name of Pierre-Olivier Latour may not be used to endorse
  12. or promote products derived from this software without specific
  13. prior written permission.
  14. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  15. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  16. WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  17. DISCLAIMED. IN NO EVENT SHALL PIERRE-OLIVIER LATOUR BE LIABLE FOR ANY
  18. DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  19. (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  20. LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  21. ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  22. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  23. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  24. */
  25. #import <TargetConditionals.h>
  26. #import "GCDWebServerRequest.h"
  27. #import "GCDWebServerResponse.h"
  28. /**
  29. * Log levels used by GCDWebServer.
  30. *
  31. * @warning kGCDWebServerLogLevel_Debug is only available if "NDEBUG" is not
  32. * defined when building.
  33. */
  34. typedef NS_ENUM(int, GCDWebServerLogLevel) {
  35. kGCDWebServerLogLevel_Debug = 0,
  36. kGCDWebServerLogLevel_Verbose,
  37. kGCDWebServerLogLevel_Info,
  38. kGCDWebServerLogLevel_Warning,
  39. kGCDWebServerLogLevel_Error,
  40. kGCDWebServerLogLevel_Exception,
  41. };
  42. /**
  43. * The GCDWebServerMatchBlock is called for every handler added to the
  44. * GCDWebServer whenever a new HTTP request has started (i.e. HTTP headers have
  45. * been received). The block is passed the basic info for the request (HTTP method,
  46. * URL, headers...) and must decide if it wants to handle it or not.
  47. *
  48. * If the handler can handle the request, the block must return a new
  49. * GCDWebServerRequest instance created with the same basic info.
  50. * Otherwise, it simply returns nil.
  51. */
  52. typedef GCDWebServerRequest* (^GCDWebServerMatchBlock)(NSString* requestMethod, NSURL* requestURL, NSDictionary* requestHeaders, NSString* urlPath, NSDictionary* urlQuery);
  53. /**
  54. * The GCDWebServerProcessBlock is called after the HTTP request has been fully
  55. * received (i.e. the entire HTTP body has been read). The block is passed the
  56. * GCDWebServerRequest created at the previous step by the GCDWebServerMatchBlock.
  57. *
  58. * The block must return a GCDWebServerResponse or nil on error, which will
  59. * result in a 500 HTTP status code returned to the client. It's however
  60. * recommended to return a GCDWebServerErrorResponse on error so more useful
  61. * information can be returned to the client.
  62. */
  63. typedef GCDWebServerResponse* (^GCDWebServerProcessBlock)(GCDWebServerRequest* request);
  64. /**
  65. * The port used by the GCDWebServer (NSNumber / NSUInteger).
  66. *
  67. * The default value is 0 i.e. let the OS pick a random port.
  68. */
  69. extern NSString* const GCDWebServerOption_Port;
  70. /**
  71. * The Bonjour name used by the GCDWebServer (NSString).
  72. *
  73. * The default value is an empty string i.e. use the computer / device name.
  74. */
  75. extern NSString* const GCDWebServerOption_BonjourName;
  76. /**
  77. * The Bonjour service type used by the GCDWebServer (NSString).
  78. *
  79. * The default value is "_http._tcp", standard HTTP web server.
  80. */
  81. extern NSString* const GCDWebServerOption_BonjourType;
  82. /**
  83. * The maximum number of incoming HTTP requests that can be queued waiting to
  84. * be handled before new ones are dropped (NSNumber / NSUInteger).
  85. *
  86. * The default value is 16.
  87. */
  88. extern NSString* const GCDWebServerOption_MaxPendingConnections;
  89. /**
  90. * The value for "Server" HTTP header used by the GCDWebServer (NSString).
  91. *
  92. * The default value is the GCDWebServer class name.
  93. */
  94. extern NSString* const GCDWebServerOption_ServerName;
  95. /**
  96. * The authentication method used by the GCDWebServer
  97. * (one of "GCDWebServerAuthenticationMethod_...").
  98. *
  99. * The default value is nil i.e. authentication is disabled.
  100. */
  101. extern NSString* const GCDWebServerOption_AuthenticationMethod;
  102. /**
  103. * The authentication realm used by the GCDWebServer (NSString).
  104. *
  105. * The default value is the same as the GCDWebServerOption_ServerName option.
  106. */
  107. extern NSString* const GCDWebServerOption_AuthenticationRealm;
  108. /**
  109. * The authentication accounts used by the GCDWebServer
  110. * (NSDictionary of username / password pairs).
  111. *
  112. * The default value is nil i.e. no accounts.
  113. */
  114. extern NSString* const GCDWebServerOption_AuthenticationAccounts;
  115. /**
  116. * The class used by the GCDWebServer when instantiating GCDWebServerConnection
  117. * (subclass of GCDWebServerConnection).
  118. *
  119. * The default value is the GCDWebServerConnection class.
  120. */
  121. extern NSString* const GCDWebServerOption_ConnectionClass;
  122. /**
  123. * Allow the GCDWebServer to pretend "HEAD" requests are actually "GET" ones
  124. * and automatically discard the HTTP body of the response (NSNumber / BOOL).
  125. *
  126. * The default value is YES.
  127. */
  128. extern NSString* const GCDWebServerOption_AutomaticallyMapHEADToGET;
  129. /**
  130. * The interval expressed in seconds used by the GCDWebServer to decide how to
  131. * coalesce calls to -webServerDidConnect: and -webServerDidDisconnect:
  132. * (NSNumber / double). Coalescing will be disabled if the interval is <= 0.0.
  133. *
  134. * The default value is 1.0 second.
  135. */
  136. extern NSString* const GCDWebServerOption_ConnectedStateCoalescingInterval;
  137. #if TARGET_OS_IPHONE
  138. /**
  139. * Enables the GCDWebServer to automatically suspend itself (as if -stop was
  140. * called) when the iOS app goes into the background and the last
  141. * GCDWebServerConnection is closed, then resume itself (as if -start was called)
  142. * when the iOS app comes back to the foreground (NSNumber / BOOL).
  143. *
  144. * See the README.md file for more information about this option.
  145. *
  146. * The default value is YES.
  147. *
  148. * @warning The running property will be NO while the GCDWebServer is suspended.
  149. */
  150. extern NSString* const GCDWebServerOption_AutomaticallySuspendInBackground;
  151. #endif
  152. /**
  153. * HTTP Basic Authentication scheme (see https://tools.ietf.org/html/rfc2617).
  154. *
  155. * @warning Use of this authentication scheme is not recommended as the
  156. * passwords are sent in clear.
  157. */
  158. extern NSString* const GCDWebServerAuthenticationMethod_Basic;
  159. /**
  160. * HTTP Digest Access Authentication scheme (see https://tools.ietf.org/html/rfc2617).
  161. */
  162. extern NSString* const GCDWebServerAuthenticationMethod_DigestAccess;
  163. @class GCDWebServer;
  164. /**
  165. * Delegate methods for GCDWebServer.
  166. *
  167. * @warning These methods are always called on the main thread in a serialized way.
  168. */
  169. @protocol GCDWebServerDelegate <NSObject>
  170. @optional
  171. /**
  172. * This method is called after the server has successfully started.
  173. */
  174. - (void)webServerDidStart:(GCDWebServer*)server;
  175. /**
  176. * This method is called after the Bonjour registration for the server has
  177. * successfully completed.
  178. */
  179. - (void)webServerDidCompleteBonjourRegistration:(GCDWebServer*)server;
  180. /**
  181. * This method is called when the first GCDWebServerConnection is opened by the
  182. * server to serve a series of HTTP requests.
  183. *
  184. * A series of HTTP requests is considered ongoing as long as new HTTP requests
  185. * keep coming (and new GCDWebServerConnection instances keep being opened),
  186. * until before the last HTTP request has been responded to (and the
  187. * corresponding last GCDWebServerConnection closed).
  188. */
  189. - (void)webServerDidConnect:(GCDWebServer*)server;
  190. /**
  191. * This method is called when the last GCDWebServerConnection is closed after
  192. * the server has served a series of HTTP requests.
  193. *
  194. * The GCDWebServerOption_ConnectedStateCoalescingInterval option can be used
  195. * to have the server wait some extra delay before considering that the series
  196. * of HTTP requests has ended (in case there some latency between consecutive
  197. * requests). This effectively coalesces the calls to -webServerDidConnect:
  198. * and -webServerDidDisconnect:.
  199. */
  200. - (void)webServerDidDisconnect:(GCDWebServer*)server;
  201. /**
  202. * This method is called after the server has stopped.
  203. */
  204. - (void)webServerDidStop:(GCDWebServer*)server;
  205. @end
  206. /**
  207. * The GCDWebServer class listens for incoming HTTP requests on a given port,
  208. * then passes each one to a "handler" capable of generating an HTTP response
  209. * for it, which is then sent back to the client.
  210. *
  211. * GCDWebServer instances can be created and used from any thread but it's
  212. * recommended to have the main thread's runloop be running so internal callbacks
  213. * can be handled e.g. for Bonjour registration.
  214. *
  215. * See the README.md file for more information about the architecture of GCDWebServer.
  216. */
  217. @interface GCDWebServer : NSObject
  218. /**
  219. * Sets the delegate for the server.
  220. */
  221. @property(nonatomic, assign) id<GCDWebServerDelegate> delegate;
  222. /**
  223. * Returns YES if the server is currently running.
  224. */
  225. @property(nonatomic, readonly, getter=isRunning) BOOL running;
  226. /**
  227. * Returns the port used by the server.
  228. *
  229. * @warning This property is only valid if the server is running.
  230. */
  231. @property(nonatomic, readonly) NSUInteger port;
  232. /**
  233. * Returns the Bonjour name used by the server.
  234. *
  235. * @warning This property is only valid if the server is running and Bonjour
  236. * registration has successfully completed, which can take up to a few seconds.
  237. */
  238. @property(nonatomic, readonly) NSString* bonjourName;
  239. /**
  240. * Returns the Bonjour service type used by the server.
  241. *
  242. * @warning This property is only valid if the server is running and Bonjour
  243. * registration has successfully completed, which can take up to a few seconds.
  244. */
  245. @property(nonatomic, readonly) NSString* bonjourType;
  246. /**
  247. * This method is the designated initializer for the class.
  248. */
  249. - (instancetype)init;
  250. /**
  251. * Adds a handler to the server to handle incoming HTTP requests.
  252. *
  253. * Handlers are called in a LIFO queue, so if multiple handlers can potentially
  254. * respond to a given request, the latest added one wins.
  255. *
  256. * @warning Addling handlers while the server is running is not allowed.
  257. */
  258. - (void)addHandlerWithMatchBlock:(GCDWebServerMatchBlock)matchBlock processBlock:(GCDWebServerProcessBlock)processBlock;
  259. /**
  260. * Removes all handlers previously added to the server.
  261. *
  262. * @warning Removing handlers while the server is running is not allowed.
  263. */
  264. - (void)removeAllHandlers;
  265. /**
  266. * Starts the server with explicit options. This method is the designated way
  267. * to start the server.
  268. *
  269. * Returns NO if the server failed to start and sets "error" argument if not NULL.
  270. */
  271. - (BOOL)startWithOptions:(NSDictionary*)options error:(NSError**)error;
  272. /**
  273. * Stops the server and prevents it to accepts new HTTP requests.
  274. *
  275. * @warning Stopping the server does not abort GCDWebServerConnection instances
  276. * currently handling already received HTTP requests. These connections will
  277. * continue to execute normally until completion.
  278. */
  279. - (void)stop;
  280. @end
  281. @interface GCDWebServer (Extensions)
  282. /**
  283. * Returns the server's URL.
  284. *
  285. * @warning This property is only valid if the server is running.
  286. */
  287. @property(nonatomic, readonly) NSURL* serverURL;
  288. /**
  289. * Returns the server's Bonjour URL.
  290. *
  291. * @warning This property is only valid if the server is running and Bonjour
  292. * registration has successfully completed, which can take up to a few seconds.
  293. */
  294. @property(nonatomic, readonly) NSURL* bonjourServerURL;
  295. /**
  296. * Starts the server on port 8080 (OS X & iOS Simulator) or port 80 (iOS)
  297. * using the computer / device name for as the Bonjour name.
  298. *
  299. * Returns NO if the server failed to start.
  300. */
  301. - (BOOL)start;
  302. /**
  303. * Starts the server on a given port and with a specific Bonjour name.
  304. * Pass a nil Bonjour name to disable Bonjour entirely or an empty string to
  305. * use the computer / device name.
  306. *
  307. * Returns NO if the server failed to start.
  308. */
  309. - (BOOL)startWithPort:(NSUInteger)port bonjourName:(NSString*)name;
  310. #if !TARGET_OS_IPHONE
  311. /**
  312. * Runs the server synchronously using -startWithPort:bonjourName: until a
  313. * SIGINT signal is received i.e. Ctrl-C. This method is intended to be used
  314. * by command line tools.
  315. *
  316. * Returns NO if the server failed to start.
  317. *
  318. * @warning This method must be used from the main thread only.
  319. */
  320. - (BOOL)runWithPort:(NSUInteger)port bonjourName:(NSString*)name;
  321. /**
  322. * Runs the server synchronously using -startWithOptions: until a SIGTERM or
  323. * SIGINT signal is received i.e. Ctrl-C in Terminal. This method is intended to
  324. * be used by command line tools.
  325. *
  326. * Returns NO if the server failed to start and sets "error" argument if not NULL.
  327. *
  328. * @warning This method must be used from the main thread only.
  329. */
  330. - (BOOL)runWithOptions:(NSDictionary*)options error:(NSError**)error;
  331. #endif
  332. @end
  333. @interface GCDWebServer (Handlers)
  334. /**
  335. * Adds a default handler to the server to handle all incoming HTTP requests
  336. * with a given HTTP method.
  337. */
  338. - (void)addDefaultHandlerForMethod:(NSString*)method requestClass:(Class)aClass processBlock:(GCDWebServerProcessBlock)block;
  339. /**
  340. * Adds a handler to the server to handle incoming HTTP requests with a given
  341. * HTTP method and a specific case-insensitive path.
  342. */
  343. - (void)addHandlerForMethod:(NSString*)method path:(NSString*)path requestClass:(Class)aClass processBlock:(GCDWebServerProcessBlock)block;
  344. /**
  345. * Adds a handler to the server to handle incoming HTTP requests with a given
  346. * HTTP method and a path matching a case-insensitive regular expression.
  347. */
  348. - (void)addHandlerForMethod:(NSString*)method pathRegex:(NSString*)regex requestClass:(Class)aClass processBlock:(GCDWebServerProcessBlock)block;
  349. @end
  350. @interface GCDWebServer (GETHandlers)
  351. /**
  352. * Adds a handler to the server to respond to incoming "GET" HTTP requests
  353. * with a specific case-insensitive path with in-memory data.
  354. */
  355. - (void)addGETHandlerForPath:(NSString*)path staticData:(NSData*)staticData contentType:(NSString*)contentType cacheAge:(NSUInteger)cacheAge;
  356. /**
  357. * Adds a handler to the server to respond to incoming "GET" HTTP requests
  358. * with a specific case-insensitive path with a file.
  359. */
  360. - (void)addGETHandlerForPath:(NSString*)path filePath:(NSString*)filePath isAttachment:(BOOL)isAttachment cacheAge:(NSUInteger)cacheAge allowRangeRequests:(BOOL)allowRangeRequests;
  361. /**
  362. * Adds a handler to the server to respond to incoming "GET" HTTP requests
  363. * with a case-insensitive path inside a base path with the corresponding file
  364. * inside a local directory. If no local file matches the request path, a 401
  365. * HTTP status code is returned to the client.
  366. *
  367. * The "indexFilename" argument allows to specify an "index" file name to use
  368. * when the request path corresponds to a directory.
  369. */
  370. - (void)addGETHandlerForBasePath:(NSString*)basePath directoryPath:(NSString*)directoryPath indexFilename:(NSString*)indexFilename cacheAge:(NSUInteger)cacheAge allowRangeRequests:(BOOL)allowRangeRequests;
  371. @end
  372. @interface GCDWebServer (Logging)
  373. #ifndef __GCDWEBSERVER_LOGGING_HEADER__
  374. /**
  375. * Sets the current log level below which logged messages are discarded.
  376. *
  377. * The default level is either DEBUG or INFO if "NDEBUG" is defined at build-time.
  378. * It can also be set at runtime with the "logLevel" environment variable.
  379. */
  380. + (void)setLogLevel:(GCDWebServerLogLevel)level;
  381. #endif
  382. /**
  383. * Logs a message with the kGCDWebServerLogLevel_Verbose level.
  384. */
  385. - (void)logVerbose:(NSString*)format, ... NS_FORMAT_FUNCTION(1,2);
  386. /**
  387. * Logs a message with the kGCDWebServerLogLevel_Info level.
  388. */
  389. - (void)logInfo:(NSString*)format, ... NS_FORMAT_FUNCTION(1,2);
  390. /**
  391. * Logs a message with the kGCDWebServerLogLevel_Warning level.
  392. */
  393. - (void)logWarning:(NSString*)format, ... NS_FORMAT_FUNCTION(1,2);
  394. /**
  395. * Logs a message with the kGCDWebServerLogLevel_Error level.
  396. */
  397. - (void)logError:(NSString*)format, ... NS_FORMAT_FUNCTION(1,2);
  398. /**
  399. * Logs an exception with the kGCDWebServerLogLevel_Exception level.
  400. */
  401. - (void)logException:(NSException*)exception;
  402. @end
  403. #ifdef __GCDWEBSERVER_ENABLE_TESTING__
  404. @interface GCDWebServer (Testing)
  405. /**
  406. * Activates recording of HTTP requests and responses which create files in the
  407. * current directory containing the raw data for all requests and responses.
  408. *
  409. * @warning The current directory must not contain any prior recording files.
  410. */
  411. @property(nonatomic, getter=isRecordingEnabled) BOOL recordingEnabled;
  412. /**
  413. * Runs tests by playing back pre-recorded HTTP requests in the given directory
  414. * and comparing the generated responses with the pre-recorded ones.
  415. *
  416. * Returns the number of failed tests or -1 if server failed to start.
  417. */
  418. - (NSInteger)runTestsWithOptions:(NSDictionary*)options inDirectory:(NSString*)path;
  419. @end
  420. #endif