-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathWordPressOrgXMLRPCValidator.swift
More file actions
362 lines (322 loc) · 18.1 KB
/
Copy pathWordPressOrgXMLRPCValidator.swift
File metadata and controls
362 lines (322 loc) · 18.1 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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
import Foundation
@objc public enum WordPressOrgXMLRPCValidatorError: Int, Error {
case emptyURL // The URL provided was nil, empty or just whitespaces
case invalidURL // The URL provided was an invalid URL
case invalidScheme // The URL provided was an invalid scheme, only HTTP and HTTPS supported
case notWordPressError // That's a XML-RPC endpoint but doesn't look like WordPress
case mobilePluginRedirectedError // There's some "mobile" plugin redirecting everything to their site
case forbidden = 403 // Server returned a 403 error while reading xmlrpc file
case blocked = 405 // Server returned a 405 error while reading xmlrpc file
case invalid // Doesn't look to be valid XMLRPC Endpoint.
case xmlrpc_missing // site contains RSD link but XML-RPC information is missing
public var localizedDescription: String {
switch self {
case .emptyURL:
return NSLocalizedString("Empty URL", comment: "Message to show to user when he tries to add a self-hosted site that is an empty URL.")
case .invalidURL:
return NSLocalizedString("Invalid URL, please check if you wrote a valid site address.", comment: "Message to show to user when he tries to add a self-hosted site that isn't a valid URL.")
case .invalidScheme:
return NSLocalizedString("Invalid URL scheme inserted, only HTTP and HTTPS are supported.", comment: "Message to show to user when he tries to add a self-hosted site that isn't HTTP or HTTPS.")
case .notWordPressError:
return NSLocalizedString("That doesn't look like a WordPress site.", comment: "Message to show to user when he tries to add a self-hosted site that isn't a WordPress site.")
case .mobilePluginRedirectedError:
return NSLocalizedString(
"You seem to have installed a mobile plugin from DudaMobile which is preventing the app to connect to your blog",
comment: "Error messaged show when a mobile plugin is redirecting traffict to their site, DudaMobile in particular"
)
case .invalid:
return NSLocalizedString("Couldn't connect to the WordPress site. There is no valid WordPress site at this address. Check the site address (URL) you entered.", comment: "Error message shown a URL points to a valid site but not a WordPress site.")
case .blocked:
return NSLocalizedString("Couldn't connect. Your host is blocking POST requests, and the app needs that in order to communicate with your site. Please contact your hosting provider to solve this problem.", comment: "Message to show to user when he tries to add a self-hosted site but the host returned a 405 error, meaning that the host is blocking POST requests on /xmlrpc.php file.")
case .forbidden:
return NSLocalizedString("Couldn't connect. We received a 403 error when trying to access your site's XMLRPC endpoint. The app needs that in order to communicate with your site. Please contact your hosting provider to solve this problem.", comment: "Message to show to user when he tries to add a self-hosted site but the host returned a 403 error, meaning that the access to the /xmlrpc.php file is forbidden.")
case .xmlrpc_missing:
return NSLocalizedString("Couldn't connect. Required XML-RPC methods are missing on the server. Please contact your hosting provider to solve this problem.", comment: "Message to show to user when he tries to add a self-hosted site with RSD link present, but xmlrpc is missing.")
}
}
}
extension WordPressOrgXMLRPCValidatorError: LocalizedError {
public var errorDescription: String? {
localizedDescription
}
}
/// An WordPressOrgXMLRPCValidator is able to validate and check if user provided site urls are
/// WordPress XMLRPC sites.
open class WordPressOrgXMLRPCValidator: NSObject {
// The documentation for NSURLErrorHTTPTooManyRedirects says that 16
// is the default threshold for allowable redirects.
private let redirectLimit = 16
private let appTransportSecuritySettings: AppTransportSecuritySettings
override public init() {
appTransportSecuritySettings = AppTransportSecuritySettings()
super.init()
}
init(_ appTransportSecuritySettings: AppTransportSecuritySettings) {
self.appTransportSecuritySettings = appTransportSecuritySettings
super.init()
}
/**
Validates and check if user provided site urls are WordPress XMLRPC sites and returns the API endpoint.
- parameter site: the user provided site URL
- parameter userAgent: user agent for anonymous .com API to check if a site is a Jetpack site
- parameter success: completion handler that is invoked when the site is considered valid,
the xmlrpcURL argument is the endpoint
- parameter failure: completion handler that is invoked when the site is considered invalid,
the error object provides details why the endpoint is invalid
*/
@objc open func guessXMLRPCURLForSite(_ site: String,
userAgent: String,
success: @escaping (_ xmlrpcURL: URL) -> Void,
failure: @escaping (_ error: NSError) -> Void) {
var sitesToTry = [String]()
let secureAccessOnly: Bool = {
if let url = URL(string: site) {
return appTransportSecuritySettings.secureAccessOnly(for: url)
}
return true
}()
if site.hasPrefix("http://") {
if !secureAccessOnly {
sitesToTry.append(site)
}
sitesToTry.append(site.replacingOccurrences(of: "http://", with: "https://"))
} else if site.hasPrefix("https://") {
sitesToTry.append(site)
if !secureAccessOnly {
sitesToTry.append(site.replacingOccurrences(of: "https://", with: "http://"))
}
} else {
failure(WordPressOrgXMLRPCValidatorError.invalidScheme as NSError)
return
}
tryGuessXMLRPCURLForSites(sitesToTry, userAgent: userAgent, success: success, failure: failure)
}
/// Helper for `guessXMLRPCURLForSite(_:userAgent:success:failure)`
/// Tries to guess the XMLRPC url for all the sites string given in the sites array
/// If all of them fail, it will call `failure` with the error in the last url string.
///
private func tryGuessXMLRPCURLForSites(_ sites: [String],
userAgent: String,
success: @escaping (_ xmlrpcURL: URL) -> Void,
failure: @escaping (_ error: NSError) -> Void) {
guard sites.isEmpty == false else {
failure(WordPressOrgXMLRPCValidatorError.invalid as NSError)
return
}
var mutableSites = sites
let nextSite = mutableSites.removeFirst()
func errorHandler(_ error: NSError) {
if mutableSites.isEmpty {
failure(error)
} else {
tryGuessXMLRPCURLForSites(mutableSites, userAgent: userAgent, success: success, failure: failure)
}
}
let originalXMLRPCURL: URL
let xmlrpcURL: URL
do {
xmlrpcURL = try urlForXMLRPCFromURLString(nextSite, addXMLRPC: true)
originalXMLRPCURL = try urlForXMLRPCFromURLString(nextSite, addXMLRPC: false)
} catch let error as NSError {
// WPKitLogError(error.localizedDescription)
errorHandler(error)
return
}
validateXMLRPCURL(xmlrpcURL, success: success, failure: { (error) in
// WPKitLogError(error.localizedDescription)
if (error.domain == NSURLErrorDomain && error.code == NSURLErrorUserCancelledAuthentication) ||
(error.domain == NSURLErrorDomain && error.code == NSURLErrorCannotFindHost) ||
(error.domain == NSURLErrorDomain && error.code == NSURLErrorNetworkConnectionLost) ||
(error.domain == String(reflecting: WordPressOrgXMLRPCValidatorError.self) && error.code == WordPressOrgXMLRPCValidatorError.mobilePluginRedirectedError.rawValue) {
errorHandler(error)
return
}
// Try the original given url as an XML-RPC endpoint
// WPKitLogError("Try the original given url as an XML-RPC endpoint: \(originalXMLRPCURL)")
self.validateXMLRPCURL(originalXMLRPCURL, success: success, failure: { (error) in
// WPKitLogError(error.localizedDescription)
// Fetch the original url and look for the RSD link
self.guessXMLRPCURLFromHTMLURL(originalXMLRPCURL, success: success, failure: { (error) in
// WPKitLogError(error.localizedDescription)
errorHandler(error)
})
})
})
}
private func urlForXMLRPCFromURLString(_ urlString: String, addXMLRPC: Bool) throws -> URL {
var resultURLString = urlString
// Is an empty url? Sorry, no psychic powers yet
resultURLString = urlString.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
if resultURLString.isEmpty {
throw WordPressOrgXMLRPCValidatorError.emptyURL
}
// Check if it's a valid URL
// Not a valid URL. Could be a bad protocol (htpp://), syntax error (http//), ...
// See https://github.com/koke/NSURL-Guess for extra help cleaning user typed URLs
guard let baseURL = URL(string: resultURLString) else {
throw WordPressOrgXMLRPCValidatorError.invalidURL
}
// Let's see if a scheme is provided and it's HTTP or HTTPS
var scheme = baseURL.scheme!.lowercased()
if scheme.isEmpty {
resultURLString = "http://\(resultURLString)"
scheme = "http"
}
guard scheme == "http" || scheme == "https" else {
throw WordPressOrgXMLRPCValidatorError.invalidScheme
}
if baseURL.lastPathComponent != "xmlrpc.php" && addXMLRPC {
// Assume the given url is the home page and XML-RPC sits at /xmlrpc.php
// WPKitLogInfo("Assume the given url is the home page and XML-RPC sits at /xmlrpc.php")
resultURLString = "\(resultURLString)/xmlrpc.php"
}
guard let url = URL(string: resultURLString) else {
throw WordPressOrgXMLRPCValidatorError.invalid
}
return url
}
private func validateXMLRPCURL(_ url: URL,
redirectCount: Int = 0,
success: @escaping (_ xmlrpcURL: URL) -> Void,
failure: @escaping (_ error: NSError) -> Void) {
guard redirectCount < redirectLimit else {
let error = NSError(domain: URLError.errorDomain,
code: URLError.httpTooManyRedirects.rawValue,
userInfo: nil)
failure(error)
return
}
let api = WordPressOrgXMLRPCApi(endpoint: url)
api.callMethod("system.listMethods", parameters: nil, success: { (responseObject, httpResponse) in
guard let methods = responseObject as? [String], methods.contains("wp.getUsersBlogs") else {
failure(WordPressOrgXMLRPCValidatorError.notWordPressError as NSError)
return
}
if let finalURL = httpResponse?.url {
success(finalURL)
} else {
failure(WordPressOrgXMLRPCValidatorError.invalid as NSError)
}
}, failure: { (error, httpResponse) in
if httpResponse?.url != url {
// we where redirected, let's check the answer content
if let data = (error as NSError).userInfo[WordPressOrgXMLRPCApi.WordPressOrgXMLRPCApiErrorKeyData as String] as? Data,
let responseString = String(data: data, encoding: String.Encoding.utf8), responseString.range(of: "<meta name=\"GENERATOR\" content=\"www.dudamobile.com\">") != nil
|| responseString.range(of: "dm404Container") != nil {
failure(WordPressOrgXMLRPCValidatorError.mobilePluginRedirectedError as NSError)
return
}
// If it's a redirect to the same host
// and the response is a '405 Method Not Allowed'
if let responseUrl = httpResponse?.url,
responseUrl.host == url.host
&& httpResponse?.statusCode == 405 {
// Then it's likely a good redirect, but the POST
// turned into a GET.
// Let's retry the request at the new URL.
self.validateXMLRPCURL(responseUrl, redirectCount: redirectCount + 1, success: success, failure: failure)
return
}
}
switch httpResponse?.statusCode {
case .some(WordPressOrgXMLRPCValidatorError.forbidden.rawValue):
failure(WordPressOrgXMLRPCValidatorError.forbidden as NSError)
case .some(WordPressOrgXMLRPCValidatorError.blocked.rawValue):
failure(WordPressOrgXMLRPCValidatorError.blocked as NSError)
default:
failure(error as NSError)
}
})
}
private func guessXMLRPCURLFromHTMLURL(_ htmlURL: URL,
success: @escaping (_ xmlrpcURL: URL) -> Void,
failure: @escaping (_ error: NSError) -> Void) {
// WPKitLogInfo("Fetch the original url and look for the RSD link by using RegExp")
var isWpSite = false
let session = URLSession(configuration: URLSessionConfiguration.ephemeral)
let dataTask = session.dataTask(with: htmlURL, completionHandler: { (data, _, error) in
if let error {
failure(error as NSError)
return
}
guard let data,
let responseString = String(data: data, encoding: String.Encoding.utf8),
let rsdURL = self.extractRSDURLFromHTML(responseString)
else {
failure(WordPressOrgXMLRPCValidatorError.invalid as NSError)
return
}
// If the site contains RSD link, it is WP.org site
isWpSite = true
// Try removing "?rsd" from the url, it should point to the XML-RPC endpoint
let xmlrpc = rsdURL.replacingOccurrences(of: "?rsd", with: "")
if xmlrpc != rsdURL {
guard let newURL = URL(string: xmlrpc) else {
failure(WordPressOrgXMLRPCValidatorError.invalid as NSError)
return
}
self.validateXMLRPCURL(newURL, success: success, failure: { (error) in
// Try to validate by using the RSD file directly
if error.code == 403 || error.code == 405, let xmlrpcValidatorError = error as? WordPressOrgXMLRPCValidatorError {
failure(xmlrpcValidatorError as NSError)
} else {
let validatorError = isWpSite ? WordPressOrgXMLRPCValidatorError.xmlrpc_missing :
WordPressOrgXMLRPCValidatorError.invalid
failure(validatorError as NSError)
}
})
} else {
// Try to validate by using the RSD file directly
self.guessXMLRPCURLFromRSD(rsdURL, success: success, failure: failure)
}
})
dataTask.resume()
}
private func extractRSDURLFromHTML(_ html: String) -> String? {
guard let rsdURLRegExp = try? NSRegularExpression(pattern: "<link\\s+rel=\"EditURI\"\\s+type=\"application/rsd\\+xml\"\\s+title=\"RSD\"\\s+href=\"([^\"]*)\"[^/]*/>",
options: [.caseInsensitive])
else {
return nil
}
let matches = rsdURLRegExp.matches(in: html,
options: NSRegularExpression.MatchingOptions(),
range: NSRange(location: 0, length: html.utf16.count))
if matches.count <= 0 {
return nil
}
let rsdURLRange = matches[0].range(at: 1)
if rsdURLRange.location == NSNotFound {
return nil
}
let rsdURL = (html as NSString).substring(with: rsdURLRange)
return rsdURL
}
private func guessXMLRPCURLFromRSD(_ rsd: String,
success: @escaping (_ xmlrpcURL: URL) -> Void,
failure: @escaping (_ error: NSError) -> Void) {
// WPKitLogInfo("Parse the RSD document at the following URL: \(rsd)")
guard let rsdURL = URL(string: rsd) else {
failure(WordPressOrgXMLRPCValidatorError.invalid as NSError)
return
}
let session = URLSession(configuration: URLSessionConfiguration.ephemeral)
let dataTask = session.dataTask(with: rsdURL, completionHandler: { (data, _, error) in
if let error {
failure(error as NSError)
return
}
guard let data,
let responseString = String(data: data, encoding: String.Encoding.utf8),
let parser = WordPressRSDParser(xmlString: responseString),
let xmlrpc = try? parser.parsedEndpoint(),
let xmlrpcURL = URL(string: xmlrpc)
else {
failure(WordPressOrgXMLRPCValidatorError.invalid as NSError)
return
}
// WPKitLogInfo("Bingo! We found the WordPress XML-RPC element: \(xmlrpcURL)")
self.validateXMLRPCURL(xmlrpcURL, success: success, failure: failure)
})
dataTask.resume()
}
}