forked from appium/WebDriverAgent
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFBWebServer.m
More file actions
248 lines (208 loc) · 7.86 KB
/
Copy pathFBWebServer.m
File metadata and controls
248 lines (208 loc) · 7.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#import "FBWebServer.h"
#import "RoutingConnection.h"
#import "RoutingHTTPServer.h"
#import "FBCommandHandler.h"
#import "FBErrorBuilder.h"
#import "FBExceptionHandler.h"
#import "FBMjpegServer.h"
#import "FBRouteRequest.h"
#import "FBRuntimeUtils.h"
#import "FBSession.h"
#import "FBTCPSocket.h"
#import "FBUnknownCommands.h"
#import "FBConfiguration.h"
#import "FBLogger.h"
#import "XCUIDevice+FBHelpers.h"
static NSString *const FBServerURLBeginMarker = @"ServerURLHere->";
static NSString *const FBServerURLEndMarker = @"<-ServerURLHere";
@interface FBHTTPConnection : RoutingConnection
@end
@implementation FBHTTPConnection
- (void)handleResourceNotFound
{
[FBLogger logFmt:@"Received request for %@ which we do not handle", self.requestURI];
[super handleResourceNotFound];
}
@end
@interface FBWebServer ()
@property (nonatomic, strong) FBExceptionHandler *exceptionHandler;
@property (nonatomic, strong) RoutingHTTPServer *server;
@property (atomic, assign) BOOL keepAlive;
@property (nonatomic, nullable) FBTCPSocket *screenshotsBroadcaster;
@end
@implementation FBWebServer
+ (NSArray<Class<FBCommandHandler>> *)collectCommandHandlerClasses
{
NSArray *handlersClasses = FBClassesThatConformsToProtocol(@protocol(FBCommandHandler));
NSMutableArray *handlers = [NSMutableArray array];
for (Class aClass in handlersClasses) {
if ([aClass respondsToSelector:@selector(shouldRegisterAutomatically)]) {
if (![aClass shouldRegisterAutomatically]) {
continue;
}
}
[handlers addObject:aClass];
}
return handlers.copy;
}
- (void)startServing
{
[FBLogger logFmt:@"Built at %s %s", __DATE__, __TIME__];
self.exceptionHandler = [FBExceptionHandler new];
[self startHTTPServer];
[self initScreenshotsBroadcaster];
self.keepAlive = YES;
NSRunLoop *runLoop = [NSRunLoop mainRunLoop];
while (self.keepAlive &&
[runLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]);
}
- (void)startHTTPServer
{
self.server = [[RoutingHTTPServer alloc] init];
[self.server setRouteQueue:dispatch_get_main_queue()];
[self.server setDefaultHeader:@"Server" value:@"WebDriverAgent/1.0"];
[self.server setDefaultHeader:@"Access-Control-Allow-Origin" value:@"*"];
[self.server setDefaultHeader:@"Access-Control-Allow-Headers" value:@"Content-Type, X-Requested-With"];
[self.server setConnectionClass:[FBHTTPConnection self]];
[self registerRouteHandlers:[self.class collectCommandHandlerClasses]];
[self registerServerKeyRouteHandlers];
NSRange serverPortRange = FBConfiguration.bindingPortRange;
NSString *bindingIP = FBConfiguration.bindingIPAddress;
if (bindingIP != nil) {
[self.server setInterface:bindingIP];
[FBLogger logFmt:@"Using custom binding IP address: %@", bindingIP];
}
NSError *error;
BOOL serverStarted = NO;
for (NSUInteger index = 0; index < serverPortRange.length; index++) {
NSInteger port = serverPortRange.location + index;
[self.server setPort:(UInt16)port];
serverStarted = [self attemptToStartServer:self.server onPort:port withError:&error];
if (serverStarted) {
break;
}
[FBLogger logFmt:@"Failed to start web server on port %ld with error %@", (long)port, [error description]];
}
if (!serverStarted) {
[FBLogger logFmt:@"Last attempt to start web server failed with error %@", [error description]];
abort();
}
NSString *serverHost = bindingIP ?: ([XCUIDevice sharedDevice].fb_wifiIPAddress ?: @"127.0.0.1");
[FBLogger logFmt:@"%@http://%@:%d%@", FBServerURLBeginMarker, serverHost, [self.server port], FBServerURLEndMarker];
}
- (void)initScreenshotsBroadcaster
{
[self readMjpegSettingsFromEnv];
self.screenshotsBroadcaster = [[FBTCPSocket alloc]
initWithPort:(uint16_t)FBConfiguration.mjpegServerPort];
self.screenshotsBroadcaster.delegate = [[FBMjpegServer alloc] init];
NSError *error;
if (![self.screenshotsBroadcaster startWithError:&error]) {
[FBLogger logFmt:@"Cannot init screenshots broadcaster service on port %@. Original error: %@", @(FBConfiguration.mjpegServerPort), error.description];
self.screenshotsBroadcaster = nil;
}
}
- (void)stopScreenshotsBroadcaster
{
if (nil == self.screenshotsBroadcaster) {
return;
}
[self.screenshotsBroadcaster stop];
}
- (void)readMjpegSettingsFromEnv
{
NSDictionary *env = NSProcessInfo.processInfo.environment;
NSString *scalingFactor = [env objectForKey:@"MJPEG_SCALING_FACTOR"];
if (scalingFactor != nil && [scalingFactor length] > 0) {
[FBConfiguration setMjpegScalingFactor:[scalingFactor floatValue]];
}
NSString *screenshotQuality = [env objectForKey:@"MJPEG_SERVER_SCREENSHOT_QUALITY"];
if (screenshotQuality != nil && [screenshotQuality length] > 0) {
[FBConfiguration setMjpegServerScreenshotQuality:[screenshotQuality integerValue]];
}
}
- (void)stopServing
{
[FBSession.activeSession kill];
[self stopScreenshotsBroadcaster];
if (self.server.isRunning) {
[self.server stop:NO];
}
self.keepAlive = NO;
}
- (BOOL)attemptToStartServer:(RoutingHTTPServer *)server onPort:(NSInteger)port withError:(NSError **)error
{
server.port = (UInt16)port;
NSError *innerError = nil;
BOOL started = [server start:&innerError];
if (!started) {
if (!error) {
return NO;
}
NSString *description = @"Unknown Error when Starting server";
if ([innerError.domain isEqualToString:NSPOSIXErrorDomain] && innerError.code == EADDRINUSE) {
description = [NSString stringWithFormat:@"Unable to start web server on port %ld", (long)port];
}
return
[[[[FBErrorBuilder builder]
withDescription:description]
withInnerError:innerError]
buildError:error];
}
return YES;
}
- (void)registerRouteHandlers:(NSArray *)commandHandlerClasses
{
for (Class<FBCommandHandler> commandHandler in commandHandlerClasses) {
NSArray *routes = [commandHandler routes];
for (FBRoute *route in routes) {
[self.server handleMethod:route.verb withPath:route.path block:^(RouteRequest *request, RouteResponse *response) {
NSDictionary *arguments = [NSJSONSerialization JSONObjectWithData:request.body options:NSJSONReadingMutableContainers error:NULL];
FBRouteRequest *routeParams = [FBRouteRequest
routeRequestWithURL:request.url
parameters:request.params
arguments:arguments ?: @{}
];
[FBLogger verboseLog:routeParams.description];
@try {
[route mountRequest:routeParams intoResponse:response];
}
@catch (NSException *exception) {
[self handleException:exception forResponse:response];
}
}];
}
}
}
- (void)handleException:(NSException *)exception forResponse:(RouteResponse *)response
{
[self.exceptionHandler handleException:exception forResponse:response];
}
- (void)registerServerKeyRouteHandlers
{
[self.server get:@"/health" withBlock:^(RouteRequest *request, RouteResponse *response) {
[response respondWithString:@"<!DOCTYPE html><html><title>Health Check</title><body><p>I-AM-ALIVE</p></body></html>"];
}];
NSString *calibrationPage = @"<html>"
"<title>{\"x\":null,\"y\":null}</title>"
"<header>"
"<script>document.addEventListener(\"click\",function(e){document.title=JSON.stringify({x:e.clientX,y:e.clientY})})</script>"
"</header>"
"</html>";
[self.server get:@"/calibrate" withBlock:^(RouteRequest *request, RouteResponse *response) {
[response respondWithString:calibrationPage];
}];
[self.server get:@"/wda/shutdown" withBlock:^(RouteRequest *request, RouteResponse *response) {
[response respondWithString:@"Shutting down"];
[self.delegate webServerDidRequestShutdown:self];
}];
[self registerRouteHandlers:@[FBUnknownCommands.class]];
}
@end