Merge branch 'android'

This commit is contained in:
Andrew Stephan
2014-03-31 17:40:08 -04:00
19 changed files with 4108 additions and 320 deletions
+53 -47
View File
@@ -4,79 +4,85 @@
id="com.synconset.cordovaHTTP"
version="1.0.0">
<name>SSL Pinning</name>
<description>
Cordova / Phonegap plugin for communicating with HTTP servers using SSL pinning
<name>SSL Pinning</name>
<description>
Cordova / Phonegap plugin for communicating with HTTP servers using SSL pinning
</description>
<engines>
<engine name="cordova" version=">=3.0.0" />
</engines>
<dependency id="org.apache.cordova.file" commit="r0.2.5" />
<engines>
<engine name="cordova" version=">=3.0.0" />
</engines>
<js-module src="www/cordovaHTTP.js" name="CordovaHTTPPlugin">
<clobbers target="plugins.cordovaHTTP" />
</js-module>
<dependency id="org.apache.cordova.file" commit="r0.2.5" />
<!-- ios -->
<platform name="ios">
<config-file target="config.xml" parent="/*">
<feature name="CordovaHTTP">
<param name="ios-package" value="CordovaHTTP"/>
</feature>
</config-file>
<header-file src="src/ios/CordovaHTTP.h" />
<source-file src="src/ios/CordovaHTTP.m" />
<js-module src="www/CordovaHTTP.js" name="CordovaHttpPlugin">
<clobbers target="plugins.CordovaHttpPlugin" />
</js-module>
<!-- ios -->
<platform name="ios">
<config-file target="config.xml" parent="/*">
<feature name="CordovaHttpPlugin">
<param name="ios-package" value="CordovaHttpPlugin"/>
</feature>
</config-file>
<header-file src="src/ios/CordovaHttpPlugin.h" />
<source-file src="src/ios/CordovaHttpPlugin.m" />
<header-file src="src/ios/HTTPManager.h" />
<source-file src="src/ios/HTTPManager.m" />
<header-file src="src/ios/HttpManager.h" />
<source-file src="src/ios/HttpManager.m" />
<header-file src="src/ios/TextResponseSerializer.h" />
<source-file src="src/ios/TextResponseSerializer.m" />
<header-file src="src/ios/AFNetworking/AFHTTPRequestOperation.h" />
<source-file src="src/ios/AFNetworking/AFHTTPRequestOperation.m" />
<header-file src="src/ios/AFNetworking/AFHTTPRequestOperationManager.h" />
<header-file src="src/ios/AFNetworking/AFHTTPRequestOperation.h" />
<source-file src="src/ios/AFNetworking/AFHTTPRequestOperation.m" />
<header-file src="src/ios/AFNetworking/AFHTTPRequestOperationManager.h" />
<source-file src="src/ios/AFNetworking/AFHTTPRequestOperationManager.m" />
<header-file src="src/ios/AFNetworking/AFHTTPSessionManager.h" />
<source-file src="src/ios/AFNetworking/AFHTTPSessionManager.m" />
<header-file src="src/ios/AFNetworking/AFNetworking.h" />
<header-file src="src/ios/AFNetworking/AFNetworkReachabilityManager.h" />
<source-file src="src/ios/AFNetworking/AFNetworkReachabilityManager.m" />
<header-file src="src/ios/AFNetworking/AFSecurityPolicy.h" />
<source-file src="src/ios/AFNetworking/AFSecurityPolicy.m" />
<header-file src="src/ios/AFNetworking/AFURLConnectionOperation.h" />
<source-file src="src/ios/AFNetworking/AFURLConnectionOperation.m" />
<header-file src="src/ios/AFNetworking/AFURLRequestSerialization.h" />
<source-file src="src/ios/AFNetworking/AFURLRequestSerialization.m" />
<header-file src="src/ios/AFNetworking/AFURLResponseSerialization.h" />
<source-file src="src/ios/AFNetworking/AFURLResponseSerialization.m" />
<header-file src="src/ios/AFNetworking/AFURLSessionManager.h" />
<source-file src="src/ios/AFNetworking/AFURLSessionManager.m" />
<framework src="Security.framework" />
</platform>
<!-- android -->
<!--<platform name="android">-->
<!-- <config-file target="res/xml/config.xml" parent="/*">-->
<!-- <feature name="ImageResizePlugin">-->
<!-- <param name="android-package" value="com.synconset.ImageResizePlugin"/>-->
<!-- </feature>-->
<!-- </config-file>-->
<framework src="Security.framework" />
</platform>
<!-- <source-file src="src/Android/com/synconset/ImageResizer/ImageResizePlugin.java" target-dir="src/com/synconset" />-->
<!--</platform>-->
<!--android -->
<platform name="android">
<config-file target="res/xml/config.xml" parent="/*">
<feature name="CordovaHttpPlugin">
<param name="android-package" value="com.synconset.CordovaHttpPlugin"/>
</feature>
</config-file>
<source-file src="src/Android/com/synconset/CordovaHTTP/CordovaHttp.java" target-dir="src/com/synconset" />
<source-file src="src/Android/com/synconset/CordovaHTTP/CordovaHttpGet.java" target-dir="src/com/synconset" />
<source-file src="src/Android/com/synconset/CordovaHTTP/CordovaHttpPost.java" target-dir="src/com/synconset" />
<source-file src="src/Android/com/synconset/CordovaHTTP/CordovaHttpUpload.java" target-dir="src/com/synconset" />
<source-file src="src/Android/com/synconset/CordovaHTTP/CordovaHttpDownload.java" target-dir="src/com/synconset" />
<source-file src="src/Android/com/synconset/CordovaHTTP/CordovaHttpPlugin.java" target-dir="src/com/synconset" />
<source-file src="src/Android/com/synconset/CordovaHTTP/HttpRequest.java" target-dir="src/com/github/kevinsawicki/http" />
</platform>
</plugin>
@@ -0,0 +1,115 @@
/**
* A HTTP plugin for Cordova / Phonegap
*/
package com.synconset;
import org.apache.cordova.CallbackContext;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.util.Map;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.HostnameVerifier;
import java.util.Iterator;
import android.util.Log;
import com.github.kevinsawicki.http.HttpRequest;
public abstract class CordovaHttp {
protected static final String TAG = "CordovaHTTP";
protected static final String CHARSET = "UTF-8";
private static boolean sslPinning;
private static boolean acceptAllCerts;
private String urlString;
private Map<?, ?> params;
private Map<String, String> headers;
private CallbackContext callbackContext;
public CordovaHttp(String urlString, Map<?, ?> params, Map<String, String> headers, CallbackContext callbackContext) {
this.urlString = urlString;
this.params = params;
this.headers = headers;
this.sslPinning = sslPinning;
this.acceptAllCerts = acceptAllCerts;
this.callbackContext = callbackContext;
}
public static void enableSSLPinning(boolean enable) {
sslPinning = enable;
if (sslPinning) {
acceptAllCerts = false;
}
}
public static void acceptAllCerts(boolean accept) {
acceptAllCerts = accept;
if (acceptAllCerts) {
sslPinning = false;
}
}
protected String getUrlString() {
return this.urlString;
}
protected void setUrlString(String urlString) {
this.urlString = urlString;
}
protected Map<?, ?> getParams() {
return this.params;
}
protected void setParams(Map<?, ?> params) {
this.params = params;
}
protected Map<String, String> getHeaders() {
return this.headers;
}
protected void setHeaders(Map<String, String> headers) {
this.headers = headers;
}
protected CallbackContext getCallbackContext() {
return this.callbackContext;
}
protected HttpRequest setupSecurity(HttpRequest request) {
if (acceptAllCerts) {
request.trustAllCerts();
request.trustAllHosts();
}
if (sslPinning) {
request.pinToCerts();
}
return request;
}
protected void respondWithError(String msg) {
try {
JSONObject response = new JSONObject();
response.put("status", 500);
response.put("error", msg);
this.callbackContext.error(response);
} catch (JSONException e) {
this.callbackContext.error(msg);
}
}
}
@@ -0,0 +1,61 @@
/**
* A HTTP plugin for Cordova / Phonegap
*/
package com.synconset;
import android.util.Log;
import com.github.kevinsawicki.http.HttpRequest;
import com.github.kevinsawicki.http.HttpRequest.HttpRequestException;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.file.FileUtils;
import org.json.JSONException;
import org.json.JSONObject;
public class CordovaHttpDownload extends CordovaHttp implements Runnable {
private String filePath;
public CordovaHttpDownload(String urlString, Map<?, ?> params, Map<String, String> headers, CallbackContext callbackContext, String filePath) {
super(urlString, params, headers, callbackContext);
this.filePath = filePath;
}
@Override
public void run() {
try {
HttpRequest request = HttpRequest.get(this.getUrlString(), this.getParams(), true);
this.setupSecurity(request);
request.acceptCharset(CHARSET);
request.headers(this.getHeaders());
int code = request.code();
JSONObject response = new JSONObject();
response.put("status", code);
if (code >= 200 && code < 300) {
URI uri = new URI(filePath);
File file = new File(uri);
request.receive(file);
JSONObject fileEntry = FileUtils.getEntry(file);
response.put("file", fileEntry);
this.getCallbackContext().success(response);
} else {
response.put("error", "There was an error downloading the file");
this.getCallbackContext().error(response);
}
} catch(URISyntaxException e) {
this.respondWithError("There was an error with the given filePath");
} catch (JSONException e) {
this.respondWithError("There was an error generating the response");
} catch (HttpRequestException e) {
Log.d(TAG, e.getMessage());
this.respondWithError("There was an error with the request");
}
}
}
@@ -0,0 +1,55 @@
/**
* A HTTP plugin for Cordova / Phonegap
*/
package com.synconset;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.HostnameVerifier;
import org.apache.cordova.CallbackContext;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import com.github.kevinsawicki.http.HttpRequest;
import com.github.kevinsawicki.http.HttpRequest.HttpRequestException;
public class CordovaHttpGet extends CordovaHttp implements Runnable {
public CordovaHttpGet(String urlString, Map<?, ?> params, Map<String, String> headers, CallbackContext callbackContext) {
super(urlString, params, headers, callbackContext);
}
@Override
public void run() {
try {
HttpRequest request = HttpRequest.get(this.getUrlString(), this.getParams(), true);
this.setupSecurity(request);
request.acceptCharset(CHARSET);
request.headers(this.getHeaders());
int code = request.code();
String body = request.body(CHARSET);
JSONObject response = new JSONObject();
response.put("status", code);
if (code >= 200 && code < 300) {
response.put("data", body);
this.getCallbackContext().success(response);
} else {
response.put("error", body);
this.getCallbackContext().error(response);
}
} catch (JSONException e) {
this.respondWithError("There was an error generating the response");
} catch (HttpRequestException e) {
Log.d(TAG, e.getMessage());
this.respondWithError("There was an error with the request");
}
}
}
@@ -0,0 +1,174 @@
/**
* A HTTP plugin for Cordova / Phonegap
*/
package com.synconset;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Iterator;
import java.util.ArrayList;
import java.util.HashMap;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.HostnameVerifier;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.res.AssetManager;
import android.util.Base64;
import android.util.Log;
import com.github.kevinsawicki.http.HttpRequest;
public class CordovaHttpPlugin extends CordovaPlugin {
private static final String TAG = "CordovaHTTP";
private HashMap<String, String> globalHeaders;
@Override
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
this.globalHeaders = new HashMap<String, String>();
}
@Override
public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException {
if (action.equals("get")) {
String urlString = args.getString(0);
JSONObject params = args.getJSONObject(1);
JSONObject headers = args.getJSONObject(2);
HashMap<?, ?> paramsMap = this.getMapFromJSONObject(params);
HashMap<String, String> headersMap = this.addToMap(this.globalHeaders, headers);
CordovaHttpGet get = new CordovaHttpGet(urlString, paramsMap, headersMap, callbackContext);
cordova.getThreadPool().execute(get);
} else if (action.equals("post")) {
String urlString = args.getString(0);
JSONObject params = args.getJSONObject(1);
JSONObject headers = args.getJSONObject(2);
HashMap<?, ?> paramsMap = this.getMapFromJSONObject(params);
HashMap<String, String> headersMap = this.addToMap(this.globalHeaders, headers);
CordovaHttpPost post = new CordovaHttpPost(urlString, paramsMap, headersMap, callbackContext);
cordova.getThreadPool().execute(post);
} else if (action.equals("useBasicAuth")) {
String username = args.getString(0);
String password = args.getString(1);
this.useBasicAuth(username, password);
callbackContext.success();
} else if (action.equals("enableSSLPinning")) {
try {
boolean enable = args.getBoolean(0);
this.enableSSLPinning(enable);
callbackContext.success();
} catch(Exception e) {
e.printStackTrace();
Log.d(TAG, e.getMessage());
callbackContext.error("There was an error setting up ssl pinning");
}
} else if (action.equals("acceptAllCerts")) {
boolean accept = args.getBoolean(0);
CordovaHttp.acceptAllCerts(accept);
} else if (action.equals("setHeader")) {
String header = args.getString(0);
String value = args.getString(1);
this.setHeader(header, value);
callbackContext.success();
} else if (action.equals("uploadFile")) {
String urlString = args.getString(0);
JSONObject params = args.getJSONObject(1);
JSONObject headers = args.getJSONObject(2);
HashMap<?, ?> paramsMap = this.getMapFromJSONObject(params);
HashMap<String, String> headersMap = this.addToMap(this.globalHeaders, headers);
String filePath = args.getString(3);
String name = args.getString(4);
CordovaHttpUpload upload = new CordovaHttpUpload(urlString, paramsMap, headersMap, callbackContext, filePath, name);
cordova.getThreadPool().execute(upload);
} else if (action.equals("downloadFile")) {
String urlString = args.getString(0);
JSONObject params = args.getJSONObject(1);
JSONObject headers = args.getJSONObject(2);
HashMap<?, ?> paramsMap = this.getMapFromJSONObject(params);
HashMap<String, String> headersMap = this.addToMap(this.globalHeaders, headers);
String filePath = args.getString(3);
CordovaHttpDownload download = new CordovaHttpDownload(urlString, paramsMap, headersMap, callbackContext, filePath);
cordova.getThreadPool().execute(download);
} else {
return false;
}
return true;
}
private void useBasicAuth(String username, String password) {
String loginInfo = username + ":" + password;
loginInfo = "Basic " + Base64.encodeToString(loginInfo.getBytes(), Base64.NO_WRAP);
this.globalHeaders.put("Authorization", loginInfo);
}
private void setHeader(String header, String value) {
this.globalHeaders.put(header, value);
}
private void enableSSLPinning(boolean enable) throws GeneralSecurityException, IOException {
if (enable) {
AssetManager assetManager = cordova.getActivity().getAssets();
String[] files = assetManager.list("");
int index;
ArrayList<String> cerFiles = new ArrayList<String>();
for (int i = 0; i < files.length; i++) {
index = files[i].lastIndexOf('.');
if (index != -1) {
if (files[i].substring(index).equals(".cer")) {
cerFiles.add(files[i]);
}
}
}
for (int i = 0; i < cerFiles.size(); i++) {
InputStream in = cordova.getActivity().getAssets().open(cerFiles.get(i));
InputStream caInput = new BufferedInputStream(in);
HttpRequest.addCert(caInput);
}
CordovaHttp.enableSSLPinning(true);
} else {
CordovaHttp.enableSSLPinning(false);
}
}
private HashMap<String, String> addToMap(HashMap<String, String> map, JSONObject object) throws JSONException {
HashMap<String, String> newMap = (HashMap<String, String>)map.clone();
Iterator<?> i = object.keys();
while (i.hasNext()) {
String key = (String)i.next();
newMap.put(key, object.getString(key));
}
return newMap;
}
private HashMap<String, Object> getMapFromJSONObject(JSONObject object) throws JSONException {
HashMap<String, Object> map = new HashMap<String, Object>();
Iterator<?> i = object.keys();
while(i.hasNext()) {
String key = (String)i.next();
map.put(key, object.get(key));
}
return map;
}
}
@@ -0,0 +1,49 @@
/**
* A HTTP plugin for Cordova / Phonegap
*/
package com.synconset;
import java.util.Map;
import org.apache.cordova.CallbackContext;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import com.github.kevinsawicki.http.HttpRequest;
import com.github.kevinsawicki.http.HttpRequest.HttpRequestException;
public class CordovaHttpPost extends CordovaHttp implements Runnable {
public CordovaHttpPost(String urlString, Map<?, ?> params, Map<String, String> headers, CallbackContext callbackContext) {
super(urlString, params, headers, callbackContext);
}
@Override
public void run() {
try {
HttpRequest request = HttpRequest.post(this.getUrlString());
this.setupSecurity(request);
request.acceptCharset(CHARSET);
request.headers(this.getHeaders());
request.form(this.getParams());
int code = request.code();
String body = request.body(CHARSET);
JSONObject response = new JSONObject();
response.put("status", code);
if (code >= 200 && code < 300) {
response.put("data", body);
this.getCallbackContext().success(response);
} else {
response.put("error", body);
this.getCallbackContext().error(response);
}
} catch (JSONException e) {
Log.d(TAG, e.getMessage());
this.respondWithError("There was an error generating the response");
} catch (HttpRequestException e) {
Log.d(TAG, e.getMessage());
this.respondWithError("There was an error with the request");
}
}
}
@@ -0,0 +1,86 @@
/**
* A HTTP plugin for Cordova / Phonegap
*/
package com.synconset;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.cordova.CallbackContext;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import android.webkit.MimeTypeMap;
import com.github.kevinsawicki.http.HttpRequest;
import com.github.kevinsawicki.http.HttpRequest.HttpRequestException;
public class CordovaHttpUpload extends CordovaHttp implements Runnable {
private String filePath;
private String name;
public CordovaHttpUpload(String urlString, Map<?, ?> params, Map<String, String> headers, CallbackContext callbackContext, String filePath, String name) {
super(urlString, params, headers, callbackContext);
this.filePath = filePath;
this.name = name;
}
@Override
public void run() {
try {
HttpRequest request = HttpRequest.post(this.getUrlString());
this.setupSecurity(request);
request.acceptCharset(CHARSET);
request.headers(this.getHeaders());
URI uri = new URI(filePath);
int index = filePath.lastIndexOf('/');
String filename = filePath.substring(index + 1);
index = filePath.lastIndexOf('.');
String ext = filePath.substring(index + 1);
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
String mimeType = mimeTypeMap.getMimeTypeFromExtension(ext);
request.part(this.name, filename, mimeType, new File(uri));
Set<?> set = (Set<?>)this.getParams().entrySet();
Iterator<?> i = set.iterator();
while (i.hasNext()) {
Entry<?, ?> e = (Entry<?, ?>)i.next();
String key = (String)e.getKey();
Object value = e.getValue();
if (value instanceof Number) {
request.part(key, (Number)value);
} else if (value instanceof String) {
request.part(key, (String)value);
} else {
this.respondWithError("All parameters must be Numbers or Strings");
return;
}
}
int code = request.code();
String body = request.body(CHARSET);
JSONObject response = new JSONObject();
response.put("status", code);
if (code >= 200 && code < 300) {
response.put("data", body);
this.getCallbackContext().success(response);
} else {
response.put("error", body);
this.getCallbackContext().error(response);
}
} catch (URISyntaxException e) {
this.respondWithError("There was an error loading the file");
} catch (JSONException e) {
this.respondWithError("There was an error generating the response");
} catch (HttpRequestException e) {
this.respondWithError("There was an error with the request");
}
}
}
File diff suppressed because it is too large Load Diff
+55 -79
View File
@@ -25,16 +25,16 @@
#if !defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
static NSData * AFSecKeyGetData(SecKeyRef key) {
CFDataRef data = NULL;
#if defined(NS_BLOCK_ASSERTIONS)
SecItemExport(key, kSecFormatUnknown, kSecItemPemArmour, NULL, &data);
#else
OSStatus status = SecItemExport(key, kSecFormatUnknown, kSecItemPemArmour, NULL, &data);
NSCAssert(status == errSecSuccess, @"SecItemExport error: %ld", (long int)status);
#endif
NSCParameterAssert(data);
return (__bridge_transfer NSData *)data;
}
#endif
@@ -50,10 +50,10 @@ static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) {
static id AFPublicKeyForCertificate(NSData *certificate) {
SecCertificateRef allowedCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificate);
NSCParameterAssert(allowedCertificate);
SecCertificateRef allowedCertificates[] = {allowedCertificate};
CFArrayRef tempCertificates = CFArrayCreate(NULL, (const void **)allowedCertificates, 1, NULL);
SecPolicyRef policy = SecPolicyCreateBasicX509();
SecTrustRef allowedTrust = NULL;
#if defined(NS_BLOCK_ASSERTIONS)
@@ -62,49 +62,49 @@ static id AFPublicKeyForCertificate(NSData *certificate) {
OSStatus status = SecTrustCreateWithCertificates(tempCertificates, policy, &allowedTrust);
NSCAssert(status == errSecSuccess, @"SecTrustCreateWithCertificates error: %ld", (long int)status);
#endif
SecTrustResultType result = 0;
#if defined(NS_BLOCK_ASSERTIONS)
SecTrustEvaluate(allowedTrust, &result);
#else
status = SecTrustEvaluate(allowedTrust, &result);
NSCAssert(status == errSecSuccess, @"SecTrustEvaluate error: %ld", (long int)status);
#endif
SecKeyRef allowedPublicKey = SecTrustCopyPublicKey(allowedTrust);
NSCParameterAssert(allowedPublicKey);
CFRelease(allowedTrust);
CFRelease(policy);
CFRelease(tempCertificates);
CFRelease(allowedCertificate);
return (__bridge_transfer id)allowedPublicKey;
}
static BOOL AFServerTrustIsValid(SecTrustRef serverTrust) {
SecTrustResultType result = 0;
#if defined(NS_BLOCK_ASSERTIONS)
SecTrustEvaluate(serverTrust, &result);
#else
OSStatus status = SecTrustEvaluate(serverTrust, &result);
NSCAssert(status == errSecSuccess, @"SecTrustEvaluate error: %ld", (long int)status);
#endif
return (result == kSecTrustResultUnspecified || result == kSecTrustResultProceed);
}
static NSArray * AFCertificateTrustChainForServerTrust(SecTrustRef serverTrust) {
CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust);
NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount];
for (CFIndex i = 0; i < certificateCount; i++) {
SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i);
[trustChain addObject:(__bridge_transfer NSData *)SecCertificateCopyData(certificate)];
}
return [NSArray arrayWithArray:trustChain];
}
@@ -114,68 +114,36 @@ static NSArray * AFPublicKeyTrustChainForServerTrust(SecTrustRef serverTrust) {
NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount];
for (CFIndex i = 0; i < certificateCount; i++) {
SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i);
SecCertificateRef someCertificates[] = {certificate};
CFArrayRef certificates = CFArrayCreate(NULL, (const void **)someCertificates, 1, NULL);
SecTrustRef trust = NULL;
#if defined(NS_BLOCK_ASSERTIONS)
SecTrustCreateWithCertificates(certificates, policy, &trust);
SecTrustResultType result;
SecTrustEvaluate(trust, &result);
#else
OSStatus status = SecTrustCreateWithCertificates(certificates, policy, &trust);
NSCAssert(status == errSecSuccess, @"SecTrustCreateWithCertificates error: %ld", (long int)status);
SecTrustResultType result;
status = SecTrustEvaluate(trust, &result);
NSCAssert(status == errSecSuccess, @"SecTrustEvaluate error: %ld", (long int)status);
#endif
[trustChain addObject:(__bridge_transfer id)SecTrustCopyPublicKey(trust)];
CFRelease(trust);
CFRelease(certificates);
}
CFRelease(policy);
return [NSArray arrayWithArray:trustChain];
}
static NSComparisonResult AFDomainComponentCompare(NSString *component1, NSString *component2) {
if ([component1 isEqualToString:@"*"] || [component2 isEqualToString:@"*"]) {
return NSOrderedSame;
}
return [component1 compare:component2];
}
static BOOL AFCertificateHostMatchesDomain(NSString *certificateHost, NSString *domain) {
certificateHost = [certificateHost lowercaseString];
domain = [domain lowercaseString];
if ([certificateHost isEqualToString:domain]) {
return YES;
}
NSArray *certificateHostComponents = [certificateHost componentsSeparatedByString:@"."];
NSArray *domainComponents = [domain componentsSeparatedByString:@"."];
if ([certificateHostComponents count] != [domainComponents count]) {
return NO;
}
BOOL certificateHostMatchesDomain = ([certificateHostComponents indexOfObjectPassingTest:^BOOL(NSString *certificateHostComponent, NSUInteger idx, __unused BOOL *stop) {
NSString *domainComponent = [domainComponents objectAtIndex:idx];
return AFDomainComponentCompare(certificateHostComponent, domainComponent) != NSOrderedSame;
}] == NSNotFound);
return certificateHostMatchesDomain;
}
#pragma mark -
@interface AFSecurityPolicy()
@@ -190,23 +158,23 @@ static BOOL AFCertificateHostMatchesDomain(NSString *certificateHost, NSString *
dispatch_once(&onceToken, ^{
NSBundle *bundle = [NSBundle bundleForClass:[self class]];
NSArray *paths = [bundle pathsForResourcesOfType:@"cer" inDirectory:@"."];
NSMutableArray *certificates = [NSMutableArray arrayWithCapacity:[paths count]];
for (NSString *path in paths) {
NSData *certificateData = [NSData dataWithContentsOfFile:path];
[certificates addObject:certificateData];
}
_defaultPinnedCertificates = [[NSArray alloc] initWithArray:certificates];
});
return _defaultPinnedCertificates;
}
+ (instancetype)defaultPolicy {
AFSecurityPolicy *securityPolicy = [[self alloc] init];
securityPolicy.SSLPinningMode = AFSSLPinningModeNone;
return securityPolicy;
}
@@ -215,7 +183,7 @@ static BOOL AFCertificateHostMatchesDomain(NSString *certificateHost, NSString *
securityPolicy.SSLPinningMode = pinningMode;
securityPolicy.validatesDomainName = YES;
[securityPolicy setPinnedCertificates:[self defaultPinnedCertificates]];
return securityPolicy;
}
@@ -234,7 +202,7 @@ static BOOL AFCertificateHostMatchesDomain(NSString *certificateHost, NSString *
- (void)setPinnedCertificates:(NSArray *)pinnedCertificates {
_pinnedCertificates = pinnedCertificates;
if (self.pinnedCertificates) {
NSMutableArray *mutablePinnedPublicKeys = [NSMutableArray arrayWithCapacity:[self.pinnedCertificates count]];
for (NSData *certificate in self.pinnedCertificates) {
@@ -255,12 +223,15 @@ static BOOL AFCertificateHostMatchesDomain(NSString *certificateHost, NSString *
- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust
forDomain:(NSString *)domain
{
BOOL shouldTrustServer = NO;
if (self.SSLPinningMode == AFSSLPinningModeNone && self.allowInvalidCertificates) {
return YES;
NSMutableArray *policies = [NSMutableArray array];
if (self.validatesDomainName) {
[policies addObject:(__bridge_transfer id)SecPolicyCreateSSL(true, (__bridge CFStringRef)domain)];
} else {
[policies addObject:(__bridge_transfer id)SecPolicyCreateBasicX509()];
}
SecTrustSetPolicies(serverTrust, (__bridge CFArrayRef)policies);
if (!AFServerTrustIsValid(serverTrust) && !self.allowInvalidCertificates) {
return NO;
}
@@ -270,6 +241,20 @@ static BOOL AFCertificateHostMatchesDomain(NSString *certificateHost, NSString *
case AFSSLPinningModeNone:
return YES;
case AFSSLPinningModeCertificate: {
NSMutableArray *pinnedCertificates = [NSMutableArray array];
for (NSData *certificateData in self.pinnedCertificates) {
[pinnedCertificates addObject:(__bridge_transfer id)SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificateData)];
}
SecTrustSetAnchorCertificates(serverTrust, (__bridge CFArrayRef)pinnedCertificates);
if (!AFServerTrustIsValid(serverTrust)) {
return NO;
}
if (!self.validatesCertificateChain) {
return YES;
}
NSUInteger trustedCertificateCount = 0;
for (NSData *trustChainCertificate in serverCertificates) {
if ([self.pinnedCertificates containsObject:trustChainCertificate]) {
@@ -277,12 +262,14 @@ static BOOL AFCertificateHostMatchesDomain(NSString *certificateHost, NSString *
}
}
shouldTrustServer = trustedCertificateCount > 0 && ((self.validatesCertificateChain && trustedCertificateCount == [serverCertificates count]) || (!self.validatesCertificateChain && trustedCertificateCount >= 1));
return trustedCertificateCount == [serverCertificates count];
}
break;
case AFSSLPinningModePublicKey: {
NSUInteger trustedPublicKeyCount = 0;
NSArray *publicKeys = AFPublicKeyTrustChainForServerTrust(serverTrust);
if (!self.validatesCertificateChain && [publicKeys count] > 0) {
publicKeys = @[[publicKeys firstObject]];
}
for (id trustChainPublicKey in publicKeys) {
for (id pinnedPublicKey in self.pinnedPublicKeys) {
@@ -292,22 +279,11 @@ static BOOL AFCertificateHostMatchesDomain(NSString *certificateHost, NSString *
}
}
shouldTrustServer = trustedPublicKeyCount > 0 && ((self.validatesCertificateChain && trustedPublicKeyCount == [serverCertificates count]) || (!self.validatesCertificateChain && trustedPublicKeyCount >= 1));
return trustedPublicKeyCount > 0 && ((self.validatesCertificateChain && trustedPublicKeyCount == [serverCertificates count]) || (!self.validatesCertificateChain && trustedPublicKeyCount >= 1));
}
break;
}
if (shouldTrustServer && domain && self.validatesDomainName) {
NSData *serverCertificate = [serverCertificates firstObject];
SecCertificateRef matchingCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)serverCertificate);
NSParameterAssert(matchingCertificate);
shouldTrustServer = AFCertificateHostMatchesDomain((__bridge_transfer NSString *)SecCertificateCopySubjectSummary(matchingCertificate), domain);
CFRelease(matchingCertificate);
}
return shouldTrustServer;
return NO;
}
#pragma mark - NSKeyValueObserving
@@ -191,7 +191,7 @@ forHTTPHeaderField:(NSString *)field;
*/
- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
URLString:(NSString *)URLString
parameters:(NSDictionary *)parameters DEPRECATED_ATTRIBUTE;
parameters:(id)parameters DEPRECATED_ATTRIBUTE;
/**
Creates an `NSMutableURLRequest` object with the specified HTTP method and URL string.
@@ -207,7 +207,7 @@ forHTTPHeaderField:(NSString *)field;
*/
- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
URLString:(NSString *)URLString
parameters:(NSDictionary *)parameters
parameters:(id)parameters
error:(NSError * __autoreleasing *)error;
/**
@@ -212,8 +212,9 @@ NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value) {
if (userAgent) {
if (![userAgent canBeConvertedToEncoding:NSASCIIStringEncoding]) {
NSMutableString *mutableUserAgent = [userAgent mutableCopy];
CFStringTransform((__bridge CFMutableStringRef)(mutableUserAgent), NULL, (__bridge CFStringRef)@"Any-Latin; Latin-ASCII; [:^ASCII:] Remove", false);
userAgent = mutableUserAgent;
if (CFStringTransform((__bridge CFMutableStringRef)(mutableUserAgent), NULL, (__bridge CFStringRef)@"Any-Latin; Latin-ASCII; [:^ASCII:] Remove", false)) {
userAgent = mutableUserAgent;
}
}
[self setValue:userAgent forHTTPHeaderField:@"User-Agent"];
}
@@ -262,14 +263,14 @@ NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value) {
- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
URLString:(NSString *)URLString
parameters:(NSDictionary *)parameters
parameters:(id)parameters
{
return [self requestWithMethod:method URLString:URLString parameters:parameters error:nil];
}
- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
URLString:(NSString *)URLString
parameters:(NSDictionary *)parameters
parameters:(id)parameters
error:(NSError *__autoreleasing *)error
{
NSParameterAssert(method);
@@ -101,20 +101,11 @@ static BOOL AFErrorOrUnderlyingErrorHasCode(NSError *error, NSInteger code) {
}
if (self.acceptableStatusCodes && ![self.acceptableStatusCodes containsIndex:(NSUInteger)response.statusCode]) {
NSStringEncoding stringEncoding = self.stringEncoding;
if (response.textEncodingName) {
CFStringEncoding encoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)response.textEncodingName);
if (encoding != kCFStringEncodingInvalidId) {
stringEncoding = CFStringConvertEncodingToNSStringEncoding(encoding);
}
}
NSString *responseString = [[NSString alloc] initWithData:data encoding:stringEncoding];
NSDictionary *userInfo = @{
NSLocalizedDescriptionKey: responseString,
NSURLErrorFailingURLErrorKey:[response URL],
AFNetworkingOperationFailingURLResponseErrorKey: response
};
NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: %@ (%lu)", @"AFNetworking", nil), [NSHTTPURLResponse localizedStringForStatusCode:response.statusCode], (unsigned long)response.statusCode],
NSURLErrorFailingURLErrorKey:[response URL],
AFNetworkingOperationFailingURLResponseErrorKey: response
};
validationError = AFErrorWithUnderlyingError([NSError errorWithDomain:AFNetworkingErrorDomain code:NSURLErrorBadServerResponse userInfo:userInfo], validationError);
@@ -220,33 +211,35 @@ static BOOL AFErrorOrUnderlyingErrorHasCode(NSError *error, NSInteger code) {
}
id responseObject = nil;
NSString *responseString = [[NSString alloc] initWithData:data encoding:stringEncoding];
if (responseString && ![responseString isEqualToString:@" "]) {
// Workaround for a bug in NSJSONSerialization when Unicode character escape codes are used instead of the actual character
// See http://stackoverflow.com/a/12843465/157142
data = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSError *serializationError = nil;
@autoreleasepool {
NSString *responseString = [[NSString alloc] initWithData:data encoding:stringEncoding];
if (responseString && ![responseString isEqualToString:@" "]) {
// Workaround for a bug in NSJSONSerialization when Unicode character escape codes are used instead of the actual character
// See http://stackoverflow.com/a/12843465/157142
data = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSError *serializationError = nil;
if (data) {
if ([data length] > 0) {
responseObject = [NSJSONSerialization JSONObjectWithData:data options:self.readingOptions error:&serializationError];
if (data) {
if ([data length] > 0) {
responseObject = [NSJSONSerialization JSONObjectWithData:data options:self.readingOptions error:&serializationError];
} else {
return nil;
}
} else {
return nil;
NSDictionary *userInfo = @{
NSLocalizedDescriptionKey: NSLocalizedStringFromTable(@"Data failed decoding as a UTF-8 string", nil, @"AFNetworking"),
NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Could not decode string: %@", nil, @"AFNetworking"), responseString]
};
serializationError = [NSError errorWithDomain:AFNetworkingErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo];
}
} else {
NSDictionary *userInfo = @{
NSLocalizedDescriptionKey: NSLocalizedStringFromTable(@"Data failed decoding as a UTF-8 string", nil, @"AFNetworking"),
NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Could not decode string: %@", nil, @"AFNetworking"), responseString]
};
serializationError = [NSError errorWithDomain:AFNetworkingErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo];
}
if (error) {
*error = AFErrorWithUnderlyingError(serializationError, *error);
}
}
if (error) {
*error = AFErrorWithUnderlyingError(serializationError, *error);;
}
return responseObject;
}
-21
View File
@@ -1,21 +0,0 @@
#import <Foundation/Foundation.h>
#import <Cordova/CDVPlugin.h>
#import <Cordova/CDVJSON.h>
@interface CordovaHTTP : CDVPlugin
- (void)setAuthorizationHeaderWithUsernameAndPassword:(CDVInvokedUrlCommand*)command;
- (void)setHeader:(CDVInvokedUrlCommand*)command;
- (void)setSSLPinningMode:(CDVInvokedUrlCommand*)command;
- (void)validateEntireCertificateChain:(CDVInvokedUrlCommand*)command;
- (void)allowInvalidCertificates:(CDVInvokedUrlCommand*)command;
- (void)acceptText:(CDVInvokedUrlCommand*)command;
- (void)acceptData:(CDVInvokedUrlCommand*)command;
- (void)setAcceptableContentTypes:(CDVInvokedUrlCommand*)command;
- (void)post:(CDVInvokedUrlCommand*)command;
- (void)get:(CDVInvokedUrlCommand*)command;
- (void)uploadFile:(CDVInvokedUrlCommand*)command;
- (void)downloadFile:(CDVInvokedUrlCommand*)command;
@end
+17
View File
@@ -0,0 +1,17 @@
#import <Foundation/Foundation.h>
#import <Cordova/CDVPlugin.h>
#import <Cordova/CDVJSON.h>
@interface CordovaHttpPlugin : CDVPlugin
- (void)useBasicAuth:(CDVInvokedUrlCommand*)command;
- (void)setHeader:(CDVInvokedUrlCommand*)command;
- (void)enableSSLPinning:(CDVInvokedUrlCommand*)command;
- (void)acceptAllCerts:(CDVInvokedUrlCommand*)command;
- (void)post:(CDVInvokedUrlCommand*)command;
- (void)get:(CDVInvokedUrlCommand*)command;
- (void)uploadFile:(CDVInvokedUrlCommand*)command;
- (void)downloadFile:(CDVInvokedUrlCommand*)command;
@end
@@ -1,99 +1,85 @@
#import "CordovaHTTP.h"
#import "CordovaHttpPlugin.h"
#import "CDVFile.h"
#import "TextResponseSerializer.h"
#import "HTTPManager.h"
#import "HttpManager.h"
@implementation CordovaHTTP
@interface CordovaHttpPlugin()
- (void) setAuthorizationHeaderWithUsernameAndPassword:(CDVInvokedUrlCommand*)command {
- (void)setRequestHeaders:(NSDictionary*)headers;
@end
@implementation CordovaHttpPlugin {
AFHTTPRequestSerializer *requestSerializer;
}
- (void)pluginInitialize {
requestSerializer = [AFHTTPRequestSerializer serializer];
}
- (void)setRequestHeaders:(NSDictionary*)headers {
[HttpManager sharedClient].requestSerializer = [AFHTTPRequestSerializer serializer];
[requestSerializer.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
[[HttpManager sharedClient].requestSerializer setValue:obj forHTTPHeaderField:key];
}];
[headers enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
[[HttpManager sharedClient].requestSerializer setValue:obj forHTTPHeaderField:key];
}];
}
- (void)useBasicAuth:(CDVInvokedUrlCommand*)command {
NSString *username = [command.arguments objectAtIndex:0];
NSString *password = [command.arguments objectAtIndex:1];
[[HTTPManager sharedClient].requestSerializer setAuthorizationHeaderFieldWithUsername:username password:password];
[requestSerializer setAuthorizationHeaderFieldWithUsername:username password:password];
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
- (void) setHeader:(CDVInvokedUrlCommand*)command {
- (void)setHeader:(CDVInvokedUrlCommand*)command {
NSString *header = [command.arguments objectAtIndex:0];
NSString *value = [command.arguments objectAtIndex:1];
[[HTTPManager sharedClient].requestSerializer setValue:value forHTTPHeaderField: header];
[requestSerializer setValue:value forHTTPHeaderField: header];
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
- (void) setSSLPinningMode:(CDVInvokedUrlCommand*)command {
CDVPluginResult* pluginResult = nil;
int pinningMode = [[command.arguments objectAtIndex:0] integerValue];
if (pinningMode == 0) {
[HTTPManager sharedClient].securityPolicy.SSLPinningMode = AFSSLPinningModeNone;
} else if (pinningMode == 1) {
[HTTPManager sharedClient].securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
} else if (pinningMode == 2) {
[HTTPManager sharedClient].securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModePublicKey];
- (void)enableSSLPinning:(CDVInvokedUrlCommand*)command {
bool enable = [[command.arguments objectAtIndex:0] boolValue];
if (enable) {
[HttpManager sharedClient].securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
[HttpManager sharedClient].securityPolicy.validatesCertificateChain = NO;
} else {
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Requested SSL Pinning Mode is Unknown"];
}
if (pluginResult == nil) {
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
[HttpManager sharedClient].securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
}
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
- (void)validateEntireCertificateChain:(CDVInvokedUrlCommand*)command {
CDVPluginResult* pluginResult = nil;
bool validate = [[command.arguments objectAtIndex:0] boolValue];
[HTTPManager sharedClient].securityPolicy.validatesCertificateChain = validate;
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
- (void)allowInvalidCertificates:(CDVInvokedUrlCommand*)command {
- (void)acceptAllCerts:(CDVInvokedUrlCommand*)command {
CDVPluginResult* pluginResult = nil;
bool allow = [[command.arguments objectAtIndex:0] boolValue];
[HTTPManager sharedClient].securityPolicy.allowInvalidCertificates = allow;
[HttpManager sharedClient].securityPolicy.allowInvalidCertificates = allow;
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
- (void)acceptText:(CDVInvokedUrlCommand*)command {
[HTTPManager sharedClient].responseSerializer = [TextResponseSerializer serializer];
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
- (void)acceptData:(CDVInvokedUrlCommand*)command {
[HTTPManager sharedClient].responseSerializer = [AFHTTPResponseSerializer serializer];
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
- (void)setAcceptableContentTypes:(CDVInvokedUrlCommand*)command {
[HTTPManager sharedClient].responseSerializer.acceptableContentTypes = [NSSet setWithArray: command.arguments];
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
- (void)post:(CDVInvokedUrlCommand*)command {
HTTPManager *manager = [HTTPManager sharedClient];
HttpManager *manager = [HttpManager sharedClient];
NSString *url = [command.arguments objectAtIndex:0];
NSDictionary *parameters = [command.arguments objectAtIndex:1];
NSDictionary *headers = [command.arguments objectAtIndex:2];
[self setRequestHeaders: headers];
CordovaHTTP* __weak weakSelf = self;
CordovaHttpPlugin* __weak weakSelf = self;
manager.responseSerializer = [TextResponseSerializer serializer];
[manager POST:url parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
[dictionary setObject:[NSNumber numberWithInt:operation.response.statusCode] forKey:@"status"];
@@ -110,12 +96,15 @@
}
- (void)get:(CDVInvokedUrlCommand*)command {
HTTPManager *manager = [HTTPManager sharedClient];
HttpManager *manager = [HttpManager sharedClient];
NSString *url = [command.arguments objectAtIndex:0];
NSDictionary *parameters = [command.arguments objectAtIndex:1];
NSDictionary *headers = [command.arguments objectAtIndex:2];
[self setRequestHeaders: headers];
CordovaHTTP* __weak weakSelf = self;
CordovaHttpPlugin* __weak weakSelf = self;
manager.responseSerializer = [TextResponseSerializer serializer];
[manager GET:url parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
[dictionary setObject:[NSNumber numberWithInt:operation.response.statusCode] forKey:@"status"];
@@ -132,15 +121,19 @@
}
- (void)uploadFile:(CDVInvokedUrlCommand*)command {
HTTPManager *manager = [HTTPManager sharedClient];
HttpManager *manager = [HttpManager sharedClient];
NSString *url = [command.arguments objectAtIndex:0];
NSDictionary *parameters = [command.arguments objectAtIndex:1];
NSString *filePath = [command.arguments objectAtIndex: 2];
NSString *name = [command.arguments objectAtIndex: 3];
NSDictionary *headers = [command.arguments objectAtIndex:2];
NSString *filePath = [command.arguments objectAtIndex: 3];
NSString *name = [command.arguments objectAtIndex: 4];
NSURL *fileURL = [NSURL fileURLWithPath: filePath];
CordovaHTTP* __weak weakSelf = self;
[self setRequestHeaders: headers];
CordovaHttpPlugin* __weak weakSelf = self;
manager.responseSerializer = [TextResponseSerializer serializer];
[manager POST:url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
NSError *error;
[formData appendPartWithFileURL:fileURL name:name error:&error];
@@ -168,12 +161,16 @@
- (void)downloadFile:(CDVInvokedUrlCommand*)command {
HTTPManager *manager = [HTTPManager sharedClient];
HttpManager *manager = [HttpManager sharedClient];
NSString *url = [command.arguments objectAtIndex:0];
NSDictionary *parameters = [command.arguments objectAtIndex:1];
NSString *filePath = [command.arguments objectAtIndex: 2];
NSDictionary *headers = [command.arguments objectAtIndex:2];
NSString *filePath = [command.arguments objectAtIndex: 3];
CordovaHTTP* __weak weakSelf = self;
[self setRequestHeaders: headers];
CordovaHttpPlugin* __weak weakSelf = self;
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager GET:url parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
/*
*
+1 -1
View File
@@ -21,7 +21,7 @@
#import <Foundation/Foundation.h>
#import "AFHTTPRequestOperationManager.h"
@interface HTTPManager : AFHTTPRequestOperationManager
@interface HttpManager : AFHTTPRequestOperationManager
+ (instancetype)sharedClient;
+4 -4
View File
@@ -18,15 +18,15 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// Modified by Andrew Stephan
#import "HTTPManager.h"
#import "HttpManager.h"
@implementation HTTPManager
@implementation HttpManager
+ (instancetype)sharedClient {
static HTTPManager *_sharedClient = nil;
static HttpManager *_sharedClient = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_sharedClient = [HTTPManager manager];
_sharedClient = [HttpManager manager];
});
return _sharedClient;
+1 -1
View File
@@ -23,7 +23,7 @@ static BOOL AFErrorOrUnderlyingErrorHasCode(NSError *error, NSInteger code) {
return nil;
}
self.acceptableContentTypes = [NSSet setWithObjects:@"text/*", nil];
self.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"text/html", @"text/json", @"application/json", @"text/xml", @"application/xml", @"text/css", nil];
return self;
}
+29 -59
View File
@@ -7,45 +7,28 @@
var exec = require('cordova/exec');
var http = {
SSLPinningMode: {
None: 0,
Certificate: 1,
PublicKey: 2
},
setAuthorizationHeaderWithUsernameAndPassword: function(username, password, success, failure) {
return exec(success, failure, "CordovaHTTP", "setAuthorizationHeaderWithUsernameAndPassword", [username, password]);
useBasicAuth: function(username, password, success, failure) {
return exec(success, failure, "CordovaHttpPlugin", "useBasicAuth", [username, password]);
},
setHeader: function(header, value, success, failure) {
return exec(success, failure, "CordovaHTTP", "setHeader", [header, value]);
return exec(success, failure, "CordovaHttpPlugin", "setHeader", [header, value]);
},
setSSLPinningMode: function(mode, success, failure) {
return exec(success, failure, "CordovaHTTP", "setSSLPinningMode", [mode]);
enableSSLPinning: function(enable, success, failure) {
return exec(success, failure, "CordovaHttpPlugin", "enableSSLPinning", [enable]);
},
validateEntireCertificateChain: function(validateChain, success, failure) {
return exec(success, failure, "CordovaHTTP", "validateEntireCertificateChain", [validateChain]);
acceptAllCerts: function(allow, success, failure) {
return exec(success, failure, "CordovaHttpPlugin", "acceptAllCerts", [allow]);
},
allowInvalidCertificates: function(allow, success, failure) {
return exec(success, failure, "CordovaHTTP", "allowInvalidCertificates", [allow]);
post: function(url, params, headers, success, failure) {
return exec(success, failure, "CordovaHttpPlugin", "post", [url, params, headers]);
},
acceptText: function(success, failure) {
return exec(success, failure, "CordovaHTTP", "acceptText", []);
get: function(url, params, headers, success, failure) {
return exec(success, failure, "CordovaHttpPlugin", "get", [url, params, headers]);
},
acceptData: function(success, failure) {
return exec(success, failure, "CordovaHTTP", "acceptData", []);
uploadFile: function(url, params, headers, filePath, name, success, failure) {
return exec(success, failure, "CordovaHttpPlugin", "uploadFile", [url, params, headers, filePath, name]);
},
setAcceptableContentTypes: function(contentTypes, success, failure) {
return exec(success, failure, "CordovaHTTP", "setAcceptableContentTypes", contentTypes);
},
post: function(url, params, success, failure) {
return exec(success, failure, "CordovaHTTP", "post", [url, params]);
},
get: function(url, params, success, failure) {
return exec(success, failure, "CordovaHTTP", "get", [url, params]);
},
uploadFile: function(url, params, filePath, name, success, failure) {
return exec(success, failure, "CordovaHTTP", "uploadFile", [url, params, filePath, name]);
},
downloadFile: function(url, params, filePath, success, failure) {
downloadFile: function(url, params, headers, filePath, success, failure) {
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
@@ -76,7 +59,7 @@ var http = {
entry.fullPath = result.file.fullPath;
success(entry);
};
return exec(win, failure, "CordovaHTTP", "downloadFile", [url, params, filePath]);
return exec(win, failure, "CordovaHttpPlugin", "downloadFile", [url, params, headers, filePath]);
}
};
@@ -114,42 +97,29 @@ if (angular) {
}
var cordovaHTTP = {
SSLPinningMode: http.SSLPinningMode,
setAuthorizationHeaderWithUsernameAndPassword: function(username, password) {
return makePromise(http.setAuthorizationHeaderWithUsernameAndPassword, [username, password]);
useBasicAuth: function(username, password) {
return makePromise(http.useBasicAuth, [username, password]);
},
setHeader: function(header, value) {
return makePromise(http.setHeader, [header, value]);
},
setSSLPinningMode: function(mode) {
return makePromise(http.setSSLPinningMode, [mode]);
enableSSLPinning: function(enable) {
return makePromise(http.enableSSLPinning, [enable]);
},
validateEntireCertificateChain: function(validateChain) {
return makePromise(http.validateEntireCertificateChain, [validateChain]);
acceptAllCerts: function(allow) {
return makePromise(http.acceptAllCerts, [allow]);
},
allowInvalidCertificates: function(allow) {
return makePromise(http.allowInvalidCertificates, [allow]);
post: function(url, params, headers) {
return makePromise(http.post, [url, params, headers], true);
},
acceptText: function() {
return makePromise(http.acceptText, []);
get: function(url, params, headers) {
return makePromise(http.get, [url, params, headers], true);
},
acceptData: function() {
return makePromise(http.acceptData, []);
uploadFile: function(url, params, headers, filePath, name) {
return makePromise(http.uploadFile, [url, params, headers, filePath, name], true);
},
setAcceptableContentTypes: function(contentTypes) {
return makePromise(http.setAcceptableContentTypes, [contentTypes]);
},
post: function(url, params) {
return makePromise(http.post, [url, params], true);
},
get: function(url, params) {
return makePromise(http.get, [url, params], true);
},
uploadFile: function(url, params, filePath, name) {
return makePromise(http.uploadFile, [url, params, filePath, name], true);
},
downloadFile: function(url, params, filePath) {
return makePromise(http.downloadFile, [url, params, filePath], true);
downloadFile: function(url, params, headers, filePath) {
return makePromise(http.downloadFile, [url, params, headers, filePath], true);
}
};
return cordovaHTTP;