public override void DidCompleteWithError(NSUrlSession session, NSUrlSessionTask task, NSError error)
        {
            if (error != null)
            {
                TaskDescription description = JsonParser.ParseTaskDescription(task.TaskDescription).Result;

                OnDownloadCompleted("", task.TaskDescription ?? "", error.LocalizedDescription);
            }
        }
		public override void DidCompleteWithError (NSUrlSession session, NSUrlSessionTask task, NSError error)
		{
			if (error == null) {
				return;
			}

			Console.WriteLine ("DidCompleteWithError - Task: {0}, Error: {1}", task.TaskIdentifier, error);

			task.Cancel ();
		}
        public NetworkUrlSessionTransfer GetUrlSessionTransfer(NSUrlSessionTask task)
        {
            IEnumerable<NetworkUrlSessionTransfer> matches = this._transfers.Where ((NetworkUrlSessionTransfer arg) => {
                return (arg.Tasks.IndexOf (task) >= 0);
            });

            NetworkUrlSessionTransfer transfer = null;

            if (matches.Count() > 0) {
                transfer = matches.First ();
            }

            return transfer;
        }
        /// <summary>
        /// Very misleading method name. Gets called if a download is done. Does not necessarily indicate an error
        /// unless the NSError parameter is not null.
        /// </summary>
        public override void DidCompleteWithError(NSUrlSession session, NSUrlSessionTask task, NSError error)
        {
            if (error == null)
            {
                return;
            }

            Console.WriteLine ("DidCompleteWithError - Task: {0}, Error: {1}", task.TaskIdentifier, error);
            var downloadInfo = AppDelegate.GetDownloadInfoByTaskId (task.TaskIdentifier);
            if (downloadInfo != null)
            {
                downloadInfo.Reset ();
            }

            task.Cancel ();
            this.InvokeOnMainThread (() => this.controller.TableView.ReloadData());
        }
        public override void DidCompleteWithError(NSUrlSession session, NSUrlSessionTask task, NSError error)
        {
            var fileUpload = this.Manager.GetUploadByTask (task);
            Debug.Assert(fileUpload != null, "Could not find FileUpload object for task!");
            if(fileUpload == null)
            {
                return;
            }

            Debug.Assert(fileUpload.State == FileUpload.STATE.Started || fileUpload.State == FileUpload.STATE.Stopping, "Upload is in invalid state!");

            var urlErrorCode = NSUrlError.Unknown;

            if(error != null)
            {
                Enum.TryParse<NSUrlError>(error.Code.ToString(), out urlErrorCode);
            }

            if(error == null)
            {
                fileUpload.Progress = 0f;
                fileUpload.Error = null;
                fileUpload.Response = fileUpload.UploadTask.Response as NSHttpUrlResponse;
                fileUpload.UploadTask = null;
                fileUpload.State = FileUpload.STATE.Uploaded;
                Console.WriteLine($"Completed upload {fileUpload}.");
            }
            else if(urlErrorCode == NSUrlError.Cancelled)
            {
                fileUpload.Error = null;
                fileUpload.UploadTask = null;
                fileUpload.State = FileUpload.STATE.Stopped;
            }
            else
            {
                // Upload was stopped by the network.
                fileUpload.Error = error;
                fileUpload.UploadTask = null;
                fileUpload.State = FileUpload.STATE.Failed;
                Console.WriteLine($"Upload failed: {fileUpload}");
            }

            fileUpload.IsStateValid();

            this.Manager.ActiveUploads.OnCollectionChanged();
        }
        public static void Completed(NSUrlSessionTask downloadTask,NSUrl location)
        {
            NSFileManager fileManager = NSFileManager.DefaultManager;
            var url = downloadTask.OriginalRequest.Url.AbsoluteString;
            NSError errorCopy = null;
            if(Files.ContainsKey(url))
            {
                var file = Files [url];
                file.Status = BackgroundDownloadFile.FileStatus.Completed;
                file.Percent = 1;
                NSUrl originalURL = downloadTask.OriginalRequest.Url;
                NSUrl destinationURL = NSUrl.FromFilename (file.Destination);
                NSError removeCopy;

                fileManager.Remove (destinationURL, out removeCopy);
                var success = fileManager.Copy (location, destinationURL, out errorCopy);
                Console.WriteLine ("Success: {0}", success);
            }
            else
                Console.WriteLine ("Could not find the file!");

            TaskCompletionSource<bool> t;
            if (Tasks.TryGetValue (url, out t)) {
                if (errorCopy == null) {
                    if (!t.TrySetResult (true))
                        Console.WriteLine ("ERROR");
                } else {
                    var file = Files [url];
                    file.Status = BackgroundDownloadFile.FileStatus.Error;
                    file.Error = string.Format("Error during the copy: {0}", errorCopy.LocalizedDescription);
                    t.TrySetException (new Exception (file.Error));
                }
                BackgroundDownloadManager.Tasks.Remove (url);
            }
            RemoveUrl (url);
            saveState ();
            Console.WriteLine ("Tasks: {0}, Downloads {1}, Controllers {2} ", Tasks.Count, DownloadTasks.Count, Controllers.Count);
            foreach (var f in Files) {
                Console.WriteLine (f);
            }
            var evt = FileCompleted;
            if (evt != null)
                evt (downloadTask, new CompletedArgs{ File = Files [url]});
            if (RemoveCompletedAutomatically)
                Remove (url);
        }
//		public override void DidReceiveChallenge (NSUrlSession session, NSUrlAuthenticationChallenge challenge, Action<NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler)
//		{
//			Console.WriteLine("[NSUrlSessionManager] DidReceiveChallenge");
//			Console.WriteLine ("[NSUrlSessionManager] DidReceiveChallenge");
//			Console.WriteLine("[NSUrlSessionManager] DidReceiveChallenge");
//
//			completionHandler (challenge, NSUrlCredential.);
//		}

		public override void DidReceiveChallenge (NSUrlSession session, NSUrlSessionTask task, NSUrlAuthenticationChallenge challenge, Action<NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler)
		{
			Console.WriteLine("[NSUrlSessionManager] DidReceiveChallenge2");
		}
        public override void DidCompleteWithError(NSUrlSession session, NSUrlSessionTask task, NSError error)
        {
            Console.WriteLine ("DidComplete");
            if (error == null)
                Console.WriteLine ("Task: {0} completed successfully", task);
            else
                Console.WriteLine ("Task: {0} completed with error: {1}", task, error.LocalizedDescription);

            float progress = task.BytesReceived / (float)task.BytesExpectedToReceive;
            InvokeOnMainThread (() => {
                controller.ProgressView.Progress = progress;
            });

            controller.downloadTask = null;
        }
		public FileUpload GetUploadByTask(NSUrlSessionTask task)
		{
			var upload = this.ActiveUploads.FirstOrDefault (d => d.UniqueId == task.OriginalRequest.Headers["fileupload_unique_id"].ToString());
			return upload;
		}
 public override void DidCompleteWithError(NSUrlSession session, NSUrlSessionTask task, NSError error)
 => this.DoAction(task, item => item.SetError(error));
Ejemplo n.º 11
0
            public override void DidReceiveChallenge(NSUrlSession session, NSUrlSessionTask task, NSUrlAuthenticationChallenge challenge, Action<NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler)
            {
               

                if (challenge.ProtectionSpace.AuthenticationMethod == NSUrlProtectionSpace.AuthenticationMethodNTLM) {
                    NetworkCredential credentialsToUse;

                    if (This.Credentials != null) {
                        if (This.Credentials is NetworkCredential) {
                            credentialsToUse = (NetworkCredential)This.Credentials;
                        } else {
                            var uri = this.getResponseForTask(task).Request.RequestUri;
                            credentialsToUse = This.Credentials.GetCredential(uri, "NTLM");
                        }
                        var credential = new NSUrlCredential(credentialsToUse.UserName, credentialsToUse.Password, NSUrlCredentialPersistence.ForSession);
                        completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, credential);
                    }
                    return;
                }

                if (!This.customSSLVerification) {
                    goto doDefault;
                }

                if (challenge.ProtectionSpace.AuthenticationMethod != "NSURLAuthenticationMethodServerTrust") {
                    goto doDefault;
                }

                if (ServicePointManager.ServerCertificateValidationCallback == null) {
                    goto doDefault;
                }

                // Convert Mono Certificates to .NET certificates and build cert 
                // chain from root certificate
                var serverCertChain = challenge.ProtectionSpace.ServerSecTrust;
                var chain = new X509Chain();
                X509Certificate2 root = null;
                var errors = SslPolicyErrors.None;

                if (serverCertChain == null || serverCertChain.Count == 0) { 
                    errors = SslPolicyErrors.RemoteCertificateNotAvailable;
                    goto sslErrorVerify;
                }

                if (serverCertChain.Count == 1) {
                    errors = SslPolicyErrors.RemoteCertificateChainErrors;
                    goto sslErrorVerify;
                }

                var netCerts = Enumerable.Range(0, serverCertChain.Count)
                    .Select(x => serverCertChain[x].ToX509Certificate2())
                    .ToArray();

                for (int i = 1; i < netCerts.Length; i++) {
                    chain.ChainPolicy.ExtraStore.Add(netCerts[i]);
                }

                root = netCerts[0];

                chain.ChainPolicy.RevocationFlag = X509RevocationFlag.EntireChain;
                chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
                chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 1, 0);
                chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;

                if (!chain.Build(root)) {
                    errors = SslPolicyErrors.RemoteCertificateChainErrors;
                    goto sslErrorVerify;
                }

                var subject = root.Subject;
                var subjectCn = cnRegex.Match(subject).Groups[1].Value;

                if (String.IsNullOrWhiteSpace(subjectCn) || !Utility.MatchHostnameToPattern(task.CurrentRequest.Url.Host, subjectCn)) {
                    errors = SslPolicyErrors.RemoteCertificateNameMismatch;
                    goto sslErrorVerify;
                }

            sslErrorVerify:
                var hostname = task.CurrentRequest.Url.Host;
                bool result = ServicePointManager.ServerCertificateValidationCallback(hostname, root, chain, errors);
                if (result) {
                    completionHandler(
                        NSUrlSessionAuthChallengeDisposition.UseCredential,
                        NSUrlCredential.FromTrust(challenge.ProtectionSpace.ServerSecTrust));
                } else {
                    completionHandler(NSUrlSessionAuthChallengeDisposition.CancelAuthenticationChallenge, null);
                }
                return;

            doDefault:
                completionHandler(NSUrlSessionAuthChallengeDisposition.PerformDefaultHandling, challenge.ProposedCredential);
                return;
            }
Ejemplo n.º 12
0
 InflightOperation getResponseForTask(NSUrlSessionTask task)
 {
     lock (This.inflightRequests) {
         return(This.inflightRequests[task]);
     }
 }
Ejemplo n.º 13
0
		public override void DidSendBodyData (NSUrlSession session, NSUrlSessionTask task, long bytesSent, 
		                                      long totalBytesSent, long totalBytesExpectedToSend)
		{
			_progress ((int)totalBytesExpectedToSend, (int)totalBytesSent);
		}
Ejemplo n.º 14
0
 public virtual void WillPerformHttpRedirection(NSUrlSession session, NSUrlSessionTask task, NSHttpUrlResponse response, NSUrlRequest newRequest, Action <NSUrlRequest> completionHandler)
 {
     Called_WillPerformHttpRedirection = true;
     completionHandler(newRequest);
 }
Ejemplo n.º 15
0
 public virtual void DidReceiveChallenge(NSUrlSession session, NSUrlSessionTask task, NSUrlAuthenticationChallenge challenge, Action <NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler)
 {
     Called_DidReceiveChallenge = true;
     completionHandler(NSUrlSessionAuthChallengeDisposition.PerformDefaultHandling, null);
 }
Ejemplo n.º 16
0
            public override void DidReceiveChallenge(NSUrlSession session, NSUrlSessionTask task, NSUrlAuthenticationChallenge challenge, Action <NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler)
            {
                var inflight = GetInflightData(task);

                if (inflight == null)
                {
                    return;
                }

                // ToCToU for the callback
                var trustCallback = sessionHandler.TrustOverride;

                if (trustCallback != null && challenge.ProtectionSpace.AuthenticationMethod == NSUrlProtectionSpace.AuthenticationMethodServerTrust)
                {
                    if (trustCallback(sessionHandler, challenge.ProtectionSpace.ServerSecTrust))
                    {
                        var credential = new NSUrlCredential(challenge.ProtectionSpace.ServerSecTrust);
                        completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, credential);
                    }
                    else
                    {
                        // user callback rejected the certificate, we want to set the exception, else the user will
                        // see as if the request was cancelled.
                        lock (inflight.Lock) {
                            inflight.Exception = new HttpRequestException("An error occurred while sending the request.", new WebException("Error: TrustFailure"));
                        }
                        completionHandler(NSUrlSessionAuthChallengeDisposition.CancelAuthenticationChallenge, null);
                    }
                    return;
                }
                // case for the basic auth failing up front. As per apple documentation:
                // The URL Loading System is designed to handle various aspects of the HTTP protocol for you. As a result, you should not modify the following headers using
                // the addValue(_:forHTTPHeaderField:) or setValue(_:forHTTPHeaderField:) methods:
                //  Authorization
                //  Connection
                //  Host
                //  Proxy-Authenticate
                //  Proxy-Authorization
                //  WWW-Authenticate
                // but we are hiding such a situation from our users, we can nevertheless know if the header was added and deal with it. The idea is as follows,
                // check if we are in the first attempt, if we are (PreviousFailureCount == 0), we check the headers of the request and if we do have the Auth
                // header, it means that we do not have the correct credentials, in any other case just do what it is expected.

                if (challenge.PreviousFailureCount == 0)
                {
                    var authHeader = inflight.Request?.Headers?.Authorization;
                    if (!(string.IsNullOrEmpty(authHeader?.Scheme) && string.IsNullOrEmpty(authHeader?.Parameter)))
                    {
                        completionHandler(NSUrlSessionAuthChallengeDisposition.RejectProtectionSpace, null);
                        return;
                    }
                }

                if (sessionHandler.Credentials != null && TryGetAuthenticationType(challenge.ProtectionSpace, out string authType))
                {
                    NetworkCredential credentialsToUse = null;
                    if (authType != RejectProtectionSpaceAuthType)
                    {
                        var uri = inflight.Request.RequestUri;
                        credentialsToUse = sessionHandler.Credentials.GetCredential(uri, authType);
                    }

                    if (credentialsToUse != null)
                    {
                        var credential = new NSUrlCredential(credentialsToUse.UserName, credentialsToUse.Password, NSUrlCredentialPersistence.ForSession);
                        completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, credential);
                    }
                    else
                    {
                        // Rejecting the challenge allows the next authentication method in the request to be delivered to
                        // the DidReceiveChallenge method. Another authentication method may have credentials available.
                        completionHandler(NSUrlSessionAuthChallengeDisposition.RejectProtectionSpace, null);
                    }
                }
                else
                {
                    completionHandler(NSUrlSessionAuthChallengeDisposition.PerformDefaultHandling, challenge.ProposedCredential);
                }
            }
Ejemplo n.º 17
0
 public override void DidSendBodyData(NSUrlSession session, NSUrlSessionTask task, long bytesSent,
                                      long totalBytesSent, long totalBytesExpectedToSend)
 {
     _progress((int)totalBytesExpectedToSend, (int)totalBytesSent);
 }
Ejemplo n.º 18
0
        public void DidCompleteWithError(NSUrlSession session, NSUrlSessionTask task, NSError error)
        {
            var userDefaults = NSUserDefaults.StandardUserDefaults;

            Asset asset       = null;
            NSUrl downloadURL = null;
            AVAggregateAssetDownloadTask avTask = task as AVAggregateAssetDownloadTask;

            if (avTask == null ||
                !activeDownloadsMap.TryGetValue(avTask, out asset) ||
                !willDownloadToUrlMap.TryGetValue(avTask, out downloadURL))
            {
                return;
            }

            var userInfo = new Dictionary <string, string>();

            userInfo[Asset.Keys.Name] = new NSString(asset.Stream.Name);

            if (error != null)
            {
                switch (error.Code)
                {
                case (int)NSUrlError.Cancelled:

                    /*
                     * This task was canceled, you should perform cleanup using the
                     * URL saved from AVAssetDownloadDelegate.urlSession(_:assetDownloadTask:didFinishDownloadingTo:).
                     */
                    var localFileLocation = LocalAssetForStream(asset.Stream.Name)?.UrlAsset.Url;

                    if (localFileLocation == null)
                    {
                        return;
                    }

                    try
                    {
                        NSError err = null;
                        NSFileManager.DefaultManager.Remove(localFileLocation, out err);
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine($"An error occured trying to delete the contents on disk for {asset.Stream.Name}: {ex.Message}");
                    }

                    userInfo[Asset.Keys.DownloadState] = new NSString(AssetDownloadState.NotDownloaded.ToString());

                    break;

                case (int)NSUrlError.Unknown:
                    throw new Exception("Downloading HLS streams is not supported in the simulator.");

                default:
                    throw new Exception($"An unexpected error occured {error.Domain}");
                }
            }
            else
            {
                try
                {
                    NSError err;

                    var bookmark = downloadURL.CreateBookmarkData(default(NSUrlBookmarkCreationOptions), new string[] { asset.Stream.Name }, downloadURL.AbsoluteUrl, out err);
                    userDefaults.SetValueForKey(bookmark, new NSString(asset.Stream.Name));
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"Failed to create bookmarkData for download URL: {ex.Message}");
                }

                userInfo[Asset.Keys.DownloadState] = AssetDownloadState.Downloaded.ToString();
                userInfo[Asset.Keys.DownloadSelectionDisplayName] = string.Empty;
            }

            var userInfoDictionary = NSDictionary.FromObjectsAndKeys(userInfo.Values.ToArray(), userInfo.Keys.ToArray());

            NSNotificationCenter.DefaultCenter.PostNotificationName(AssetPersistenceManager.AssetDownloadStateChanged, null, userInfoDictionary);
        }
		public override void NeedNewBodyStream (NSUrlSession session, NSUrlSessionTask task, Action<NSInputStream> completionHandler)
		{
			Console.WriteLine("[NSUrlSessionManager] NeedNewBodyStream");
		}
Ejemplo n.º 20
0
            public override void DidReceiveChallenge(NSUrlSession session, NSUrlSessionTask task, NSUrlAuthenticationChallenge challenge, Action <NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler)
            {
                if (challenge.ProtectionSpace.AuthenticationMethod == NSUrlProtectionSpace.AuthenticationMethodNTLM)
                {
                    NetworkCredential credentialsToUse;

                    if (This.Credentials != null)
                    {
                        if (This.Credentials is NetworkCredential)
                        {
                            credentialsToUse = (NetworkCredential)This.Credentials;
                        }
                        else
                        {
                            var uri = this.getResponseForTask(task).Request.RequestUri;
                            credentialsToUse = This.Credentials.GetCredential(uri, "NTLM");
                        }
                        var credential = new NSUrlCredential(credentialsToUse.UserName, credentialsToUse.Password, NSUrlCredentialPersistence.ForSession);
                        completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, credential);
                    }
                    return;
                }

                if (!This.customSSLVerification)
                {
                    goto doDefault;
                }

                if (challenge.ProtectionSpace.AuthenticationMethod != "NSURLAuthenticationMethodServerTrust")
                {
                    goto doDefault;
                }

                if (ServicePointManager.ServerCertificateValidationCallback == null)
                {
                    goto doDefault;
                }

                // Convert Mono Certificates to .NET certificates and build cert
                // chain from root certificate
                var serverCertChain   = challenge.ProtectionSpace.ServerSecTrust;
                var chain             = new X509Chain();
                X509Certificate2 root = null;
                var errors            = SslPolicyErrors.None;

                if (serverCertChain == null || serverCertChain.Count == 0)
                {
                    errors = SslPolicyErrors.RemoteCertificateNotAvailable;
                    goto sslErrorVerify;
                }

                if (serverCertChain.Count == 1)
                {
                    errors = SslPolicyErrors.RemoteCertificateChainErrors;
                    goto sslErrorVerify;
                }

                var netCerts = Enumerable.Range(0, serverCertChain.Count)
                               .Select(x => serverCertChain[x].ToX509Certificate2())
                               .ToArray();

                for (int i = 1; i < netCerts.Length; i++)
                {
                    chain.ChainPolicy.ExtraStore.Add(netCerts[i]);
                }

                root = netCerts[0];

                chain.ChainPolicy.RevocationFlag      = X509RevocationFlag.EntireChain;
                chain.ChainPolicy.RevocationMode      = X509RevocationMode.NoCheck;
                chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 1, 0);
                chain.ChainPolicy.VerificationFlags   = X509VerificationFlags.AllowUnknownCertificateAuthority;

                if (!chain.Build(root))
                {
                    errors = SslPolicyErrors.RemoteCertificateChainErrors;
                    goto sslErrorVerify;
                }

                var subject   = root.Subject;
                var subjectCn = cnRegex.Match(subject).Groups[1].Value;

                if (String.IsNullOrWhiteSpace(subjectCn) || !Utility.MatchHostnameToPattern(task.CurrentRequest.Url.Host, subjectCn))
                {
                    errors = SslPolicyErrors.RemoteCertificateNameMismatch;
                    goto sslErrorVerify;
                }

sslErrorVerify:
                var hostname = task.CurrentRequest.Url.Host;
                bool result = ServicePointManager.ServerCertificateValidationCallback(hostname, root, chain, errors);

                if (result)
                {
                    completionHandler(
                        NSUrlSessionAuthChallengeDisposition.UseCredential,
                        NSUrlCredential.FromTrust(challenge.ProtectionSpace.ServerSecTrust));
                }
                else
                {
                    completionHandler(NSUrlSessionAuthChallengeDisposition.CancelAuthenticationChallenge, null);
                }
                return;

doDefault:
                completionHandler(NSUrlSessionAuthChallengeDisposition.PerformDefaultHandling, challenge.ProposedCredential);
                return;
            }
Ejemplo n.º 21
0
 public override void DidCompleteWithError(NSUrlSession session, NSUrlSessionTask task, NSError error) => Dispatcher.ExecuteBackgroundTask(async() =>
        public override void DidSendBodyData(NSUrlSession session, NSUrlSessionTask task, long bytesSent, long totalBytesSent, long totalBytesExpectedToSend)
        {
            var fileUpload = this.Manager.GetUploadByTask (task);
            Debug.Assert(fileUpload != null, "Could not find FileUpload object for task!");
            if(fileUpload == null)
            {
                return;
            }

            fileUpload.Progress = (float)totalBytesSent / (float)totalBytesExpectedToSend;

            this.Manager.ActiveUploads.OnCollectionChanged();
        }
Ejemplo n.º 23
0
            public override void DidCompleteWithError (NSUrlSession session, NSUrlSessionTask task, NSError error)
            {
                var data = getResponseForTask(task);
                data.IsCompleted = true;

                if (error != null) {
                    var ex = createExceptionForNSError(error);

                    // Pass the exception to the response
                    data.FutureResponse.TrySetException(ex);
                    data.ResponseBody.SetException(ex);
                    return;
                }

                data.ResponseBody.Complete();

                lock (This.inflightRequests) {
                    This.inflightRequests.Remove(task);
                }
            }
Ejemplo n.º 24
0
		// Called by iOS when the task finished trasferring data. It's important to note that his is called even when there isn't an error.
		// See: https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSURLSessionTaskDelegate_protocol/index.html#//apple_ref/occ/intfm/NSURLSessionTaskDelegate/URLSession:task:didCompleteWithError:
		public override void DidCompleteWithError (NSUrlSession session, NSUrlSessionTask task, NSError error)
		{
			Console.WriteLine (string.Format("DidCompleteWithError TaskId: {0}{1}", task.TaskIdentifier, (error == null ? "" : " Error: " + error.Description)));

			if (error == null) {
				var appDel = UIApplication.SharedApplication.Delegate as AppDelegate;
				appDel.ProcessCompletedTask (task);
			}
		}
Ejemplo n.º 25
0
 public override void DidReceiveChallenge(NSUrlSession session, NSUrlSessionTask task, NSUrlAuthenticationChallenge challenge, Action <NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler)
 => completionHandler.Invoke(NSUrlSessionAuthChallengeDisposition.PerformDefaultHandling, null);
            public override void DidCompleteWithError (NSUrlSession session, NSUrlSessionTask task, NSError error)
            {
                var data = getResponseForTask(task);
                data.IsCompleted = true;

                if (error != null) {
                    var ex = default(Exception);
                    if (error.Description.StartsWith("cancel", StringComparison.OrdinalIgnoreCase)) {
                        ex = new OperationCanceledException();
                    } else {
                        ex = new WebException(error.LocalizedDescription);
                    }

                    data.FutureResponse.TrySetException(ex);
                    data.ResponseBody.SetException(ex);
                    return;
                }

                data.ResponseBody.Complete();
                lock (This.inflightRequests) {
                    This.inflightRequests.Remove(task);
                }
            }
            public override void DidReceiveChallenge(NSUrlSession session, NSUrlSessionTask task, NSUrlAuthenticationChallenge challenge, Action <NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler)
            {
                // TODO: add NSUrlProtectionSpace.HTTPSProxy case

                if (challenge.ProtectionSpace.AuthenticationMethod == NSUrlProtectionSpace.AuthenticationMethodNTLM)
                {
                    NetworkCredential credentialsToUse;

                    if (nativeHandler.Credentials != null)
                    {
                        if (nativeHandler.Credentials is NetworkCredential)
                        {
                            credentialsToUse = (NetworkCredential)nativeHandler.Credentials;
                        }
                        else
                        {
                            var uri = this.getResponseForTask(task).Request.RequestUri;
                            credentialsToUse = nativeHandler.Credentials.GetCredential(uri, "NTLM");
                        }
                        var credential = new NSUrlCredential(credentialsToUse.UserName, credentialsToUse.Password, NSUrlCredentialPersistence.ForSession);
                        completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, credential);
                    }
                    return;
                }

                if (challenge.ProtectionSpace.AuthenticationMethod == NSUrlProtectionSpace.AuthenticationMethodServerTrust)
                {
                    var errors = SslPolicyErrors.None;

                    if (nativeHandler.TLSConfig.DangerousAcceptAnyServerCertificateValidator)
                    {
                        goto sslErrorVerify;
                    }

                    // Convert java certificates to .NET certificates and build cert chain from root certificate
                    var serverCertChain   = challenge.ProtectionSpace.ServerSecTrust;
                    var chain             = new X509Chain();
                    X509Certificate2 root = null;

                    // Build certificate chain and check for errors
                    if (serverCertChain == null || serverCertChain.Count == 0)
                    {//no cert at all
                        errors = SslPolicyErrors.RemoteCertificateNotAvailable;
                        PinningFailureMessage = FailureMessages.NoCertAtAll;
                        goto sslErrorVerify;
                    }

                    if (serverCertChain.Count == 1)
                    {//no root?
                        errors = SslPolicyErrors.RemoteCertificateChainErrors;
                        PinningFailureMessage = FailureMessages.NoRoot;
                        goto sslErrorVerify;
                    }

                    var netCerts = Enumerable.Range(0, serverCertChain.Count)
                                   .Select(x => serverCertChain[x].ToX509Certificate2())
                                   .ToArray();

                    for (int i = 1; i < netCerts.Length; i++)
                    {
                        chain.ChainPolicy.ExtraStore.Add(netCerts[i]);
                    }

                    root = netCerts[0];

                    chain.ChainPolicy.RevocationFlag      = X509RevocationFlag.EntireChain;
                    chain.ChainPolicy.RevocationMode      = X509RevocationMode.NoCheck;
                    chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 1, 0);
                    chain.ChainPolicy.VerificationFlags   = X509VerificationFlags.AllowUnknownCertificateAuthority;

                    if (!chain.Build(root))
                    {
                        errors = SslPolicyErrors.RemoteCertificateChainErrors;
                        PinningFailureMessage = FailureMessages.ChainError;
                        goto sslErrorVerify;
                    }

                    var hostname = task.CurrentRequest.Url.Host;

                    var subject   = root.Subject;
                    var subjectCn = cnRegex.Match(subject).Groups[1].Value;

                    if (string.IsNullOrWhiteSpace(subjectCn) || !Utility.MatchHostnameToPattern(hostname, subjectCn))
                    {
                        var subjectAn = root.ParseSubjectAlternativeName();

                        if (!subjectAn.Contains(hostname))
                        {
                            errors = SslPolicyErrors.RemoteCertificateNameMismatch;
                            PinningFailureMessage = FailureMessages.SubjectNameMismatch;
                            goto sslErrorVerify;
                        }
                    }

                    if (nativeHandler.CertificatePinner != null)
                    {
                        if (!nativeHandler.CertificatePinner.HasPins(hostname))
                        {
                            errors = SslPolicyErrors.RemoteCertificateNameMismatch;
                            PinningFailureMessage = FailureMessages.NoPinsProvided + " " + hostname;
                            goto sslErrorVerify;
                        }

                        if (!nativeHandler.CertificatePinner.Check(hostname, root.RawData))
                        {
                            errors = SslPolicyErrors.RemoteCertificateNameMismatch;
                            PinningFailureMessage = FailureMessages.PinMismatch;
                        }
                    }

sslErrorVerify:
                    if (errors == SslPolicyErrors.None)
                    {
                        completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, NSUrlCredential.FromTrust(challenge.ProtectionSpace.ServerSecTrust));
                    }
                    else
                    {
                        completionHandler(NSUrlSessionAuthChallengeDisposition.CancelAuthenticationChallenge, null);
                    }
                    return;
                }

                if (challenge.ProtectionSpace.AuthenticationMethod == NSUrlProtectionSpace.AuthenticationMethodClientCertificate)
                {
                    completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, nativeHandler.UrlCredential);

                    return;
                }

                completionHandler(NSUrlSessionAuthChallengeDisposition.PerformDefaultHandling, challenge.ProposedCredential);
            }
Ejemplo n.º 28
0
        void FetchQuakes(object sender, EventArgs e)
        {
            fetchQuakesButton.Enabled = false;
            var jsonURL           = new NSUrl("http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_month.geojson");
            var session           = NSUrlSession.FromConfiguration(NSUrlSessionConfiguration.EphemeralSessionConfiguration);
            NSUrlSessionTask task = session.CreateDataTask(jsonURL, (data, response, error) => {
                if (data == null)
                {
                    Console.WriteLine("Error connecting: {0}", error.LocalizedDescription);
                    return;
                }

                NSError anyError;
                NSManagedObjectContext taskContext = CreatePrivateQueueContext(out anyError);
                var jsonDictionary = NSJsonSerialization.Deserialize(data, NSJsonReadingOptions.AllowFragments, new NSError());

                if (jsonDictionary == null)
                {
                    Console.WriteLine("Error creating JSON dictionary: {0}", anyError.LocalizedDescription);
                    return;
                }

                var featuresArray     = (NSArray)jsonDictionary.ValueForKey((NSString)"features");
                int totalFeatureCount = (int)featuresArray.Count;

                int numBatches = totalFeatureCount / BatchSize;
                numBatches    += totalFeatureCount % BatchSize > 0 ? 1 : 0;
                for (int batchNumber = 0; batchNumber < numBatches; batchNumber++)
                {
                    int rangeStart  = batchNumber * BatchSize;
                    int rangeLength = Math.Min(BatchSize, totalFeatureCount - batchNumber * BatchSize);

                    NSArray featuresBatchArray = featuresArray.SubarrayWithRange(new NSRange(rangeStart, rangeLength));
                    // Create a request to fetch existing quakes with the same codes as those in the JSON data.
                    // Existing quakes will be updated with new data; if there isn't a match, then create a new quake to represent the event.
                    NSFetchRequest matchingQuakeRequest = NSFetchRequest.FromEntityName("Quake");

                    // Get the codes for each of the features and store them in an array.
                    NSArray codesDump = (NSArray)featuresBatchArray.ValueForKeyPath((NSString)"properties.code");

                    matchingQuakeRequest.Predicate = NSPredicate.FromFormat("code in %@", codesDump);
                    var rawFetch = taskContext.ExecuteFetchRequest(matchingQuakeRequest, out anyError);
                    Quake[] allMatchingQuakes = Array.ConvertAll(rawFetch, item => (Quake)item);
                    NSString[] codes          = NSArray.FromArray <NSString> (codesDump);

                    for (int k = 0; k < codes.Length; k++)
                    {
                        var code           = codes [k];
                        var matchingQuakes = allMatchingQuakes.Where(q => q.Code == code).ToArray <Quake> ();

                        Quake quake = null;

                        int matchingLength = matchingQuakes.Length;
                        switch (matchingLength)
                        {
                        case 0:
                            //Insert new item
                            quake = (Quake)NSEntityDescription.InsertNewObjectForEntityForName("Quake", taskContext);
                            break;

                        case 1:
                            //Update existing item
                            quake = matchingQuakes [0];
                            break;

                        default:
                            //Remove duplicates
                            for (int i = 1; i < matchingQuakes.Length; i++)
                            {
                                taskContext.DeleteObject(matchingQuakes [i]);
                            }

                            quake = matchingQuakes [0];
                            break;
                        }

                        var result          = featuresBatchArray.GetItem <NSDictionary> ((nuint)k);
                        var quakeDictionary = (NSDictionary)result.ObjectForKey((NSString)"properties");
                        quake.UpdateFromDictionary(quakeDictionary);
                    }

                    if (!taskContext.Save(out anyError))
                    {
                        Console.WriteLine("Error saving batch: {0}", anyError.LocalizedDescription);
                        return;
                    }

                    taskContext.Reset();
                }

                // Bounce back to the main queue to reload the table view and reenable the fetch button.
                NSOperationQueue.MainQueue.AddOperation(() => {
                    ReloadTableView();
                    fetchQuakesButton.Enabled = true;
                });
            });

            task.Resume();
        }
Ejemplo n.º 29
0
		/// <summary>
		/// Processes the completed task.
		/// </summary>
		/// <param name="sessionTask">Session task.</param>
		public void ProcessCompletedTask(NSUrlSessionTask sessionTask)
		{
			try {
				Console.WriteLine (string.Format("Task ID: {0}, State: {1}, Response: {2}", sessionTask.TaskIdentifier, sessionTask.State, sessionTask.Response));

				// Make sure that we have a response to process
				if (sessionTask.Response == null || sessionTask.Response.ToString() == "")
				{
					Console.WriteLine("ProcessCompletedTask no response...");
				} 
				else
				{
					// Get response
					var resp = (NSHttpUrlResponse)sessionTask.Response;

					// Check that our task completed and server returned StatusCode 201 = CREATED.
					if (sessionTask.State == NSUrlSessionTaskState.Completed && resp.StatusCode == 201) 
					{
						// Do something with the uploaded file...
					}
				}
			} catch (Exception ex) {
				Console.WriteLine ("ProcessCompletedTask Ex: {0}", ex.Message);
			}
		}
            public override void WillPerformHttpRedirection(NSUrlSession session, NSUrlSessionTask task, NSHttpUrlResponse response, NSUrlRequest newRequest, Action <NSUrlRequest> completionHandler)
            {
                NSUrlRequest nextRequest = (nativeHandler.AllowAutoRedirect ? newRequest : null);

                completionHandler(nextRequest);
            }
Ejemplo n.º 31
0
		// Called by iOS to periodically inform the progress of sending body content to the server.
		// See: https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSURLSessionTaskDelegate_protocol/index.html#//apple_ref/occ/intfm/NSURLSessionTaskDelegate/URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:
		public override void DidSendBodyData (NSUrlSession session, NSUrlSessionTask task, long bytesSent, long totalBytesSent, long totalBytesExpectedToSend)
		{
			// Uncomment line below to see file upload progress outputed to the console. You can track/manage this in your app to monitor the upload progress.
			//Console.WriteLine ("DidSendBodyData bSent: {0}, totalBSent: {1} totalExpectedToSend: {2}", bytesSent, totalBytesSent, totalBytesExpectedToSend);
		}
Ejemplo n.º 32
0
 public virtual void DidFinishCollectingMetrics(NSUrlSession session, NSUrlSessionTask task, NSUrlSessionTaskMetrics metrics)
 {
     throw new NotImplementedException();
 }
		void SyncUploadTasks(NSUrlSessionTask[] uploadTasks)
		{
			
		}
Ejemplo n.º 34
0
 public virtual void DidReceiveChallenge(NSUrlSession session, NSUrlSessionTask task, NSUrlAuthenticationChallenge challenge, [BlockProxy(typeof(Trampolines.NIDActionArity2V0))] Action <NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 35
0
			public override void DidCompleteWithError (NSUrlSession session, NSUrlSessionTask task, NSError error)
			{
				Console.WriteLine ("DidCompleteWithError");
				if (error != null) {
					Console.WriteLine (error.LocalizedDescription);
					BackgroundDownloadManager.Failed (session, task, error);
				} else {
					Console.WriteLine ("False positive");
				}

			}
Ejemplo n.º 36
0
 public virtual void DidSendBodyData(NSUrlSession session, NSUrlSessionTask task, long bytesSent, long totalBytesSent, long totalBytesExpectedToSend)
 {
     throw new NotImplementedException();
 }
		public override void DidCompleteWithError (NSUrlSession session, NSUrlSessionTask task, NSError error)
		{

			Console.WriteLine("[NSUrlSessionManager] DidCompleteWithError");
			Console.WriteLine("[NSUrlSessionManager] DidCompleteWithError Session : {0}", session.Description);
			Console.WriteLine("[NSUrlSessionManager] DidCompleteWithError Task    : {0}", task.TaskDescription);

			var staskdescription = task.TaskDescription;
			if (staskdescription == null) {
				Console.WriteLine("[NSUrlSessionManager] DidCompleteWithError NullTaskId");
				_bus.SendAsync<DownloadError> (new DownloadError {
					Error = ErrorEnum.DidCompleteWithError_NullTaskId
				});
				return;
			}
			int taskid;
			if (!int.TryParse (staskdescription, out taskid)) {
				Console.WriteLine("[NSUrlSessionManager] DidCompleteWithError InvalidTaskId");

				_bus.SendAsync<DownloadError> (new DownloadError {
					Error = ErrorEnum.DidCompleteWithError_InvalidTaskId
				});
				return;
			}

			if (error != null) {
				Console.WriteLine("[NSUrlSessionManager] DidCompleteWithError Error");
				Console.WriteLine("[NSUrlSessionManager] DidCompleteWithError Description : {0}", error.LocalizedDescription);
				Console.WriteLine("[NSUrlSessionManager] DidCompleteWithError TaskId      : {0}", taskid);
				_bus.SendAsync<TaskError> (new TaskError {
					Id = taskid,
					Error = TaskErrorEnum.DownloadError,
					Description = error.LocalizedDescription
				});
				return;
			}

		}
Ejemplo n.º 38
0
 public virtual void NeedNewBodyStream(NSUrlSession session, NSUrlSessionTask task, [BlockProxy(typeof(Trampolines.NIDActionArity1V0))] Action <NSInputStream> completionHandler)
 {
     throw new NotImplementedException();
 }
		public override void DidSendBodyData (NSUrlSession session, NSUrlSessionTask task, long bytesSent, long totalBytesSent, long totalBytesExpectedToSend)
		{
			Console.WriteLine("[NSUrlSessionManager] DidSendBodyData");
		}
Ejemplo n.º 40
0
 public virtual void WillPerformHttpRedirection(NSUrlSession session, NSUrlSessionTask task, NSHttpUrlResponse response, NSUrlRequest newRequest, [BlockProxy(typeof(Trampolines.NIDActionArity1V1))] Action <NSUrlRequest> completionHandler)
 {
     throw new NotImplementedException();
 }
		public override void WillPerformHttpRedirection (NSUrlSession session, NSUrlSessionTask task, NSHttpUrlResponse response, NSUrlRequest newRequest, Action<NSUrlRequest> completionHandler)
		{
			Console.WriteLine("[NSUrlSessionManager] WillPerformHttpRedirection");
		}
            public override void DidReceiveChallenge(NSUrlSession session, NSUrlSessionTask task, NSUrlAuthenticationChallenge challenge, Action<NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler)
            {
               

                if (challenge.ProtectionSpace.AuthenticationMethod == NSUrlProtectionSpace.AuthenticationMethodNTLM) {
                    NetworkCredential credentialsToUse;

                    if (This.Credentials != null) {
                        if (This.Credentials is NetworkCredential) {
                            credentialsToUse = (NetworkCredential)This.Credentials;
                        } else {
                            var uri = this.getResponseForTask(task).Request.RequestUri;
                            credentialsToUse = This.Credentials.GetCredential(uri, "NTLM");
                        }
                        var credential = new NSUrlCredential(credentialsToUse.UserName, credentialsToUse.Password, NSUrlCredentialPersistence.ForSession);
                        completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, credential);
                    }
                    return;
                }

                if (challenge.ProtectionSpace.AuthenticationMethod == NSUrlProtectionSpace.AuthenticationMethodClientCertificate)
                {
                    Console.WriteLine("Client Cert!");

                    var password = "******";
                    var options = NSDictionary.FromObjectAndKey(NSObject.FromObject(password), SecImportExport.Passphrase);

                    var path = Path.Combine(NSBundle.MainBundle.BundlePath, "Content", "client.p12");
                    var certData = File.ReadAllBytes(path);

                    NSDictionary[] importResult;

                    X509Certificate cert = new X509Certificate(certData, password);

                    SecStatusCode statusCode = SecImportExport.ImportPkcs12(certData, options, out importResult);
                    var identityHandle = importResult[0][SecImportExport.Identity];
                    var identity = new SecIdentity(identityHandle.Handle);
                    var certificate = new SecCertificate(cert.GetRawCertData());

                    SecCertificate[] certificates = { certificate };
                    NSUrlCredential credential = NSUrlCredential.FromIdentityCertificatesPersistance(identity, certificates, NSUrlCredentialPersistence.ForSession);
                    completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, credential);

                    return;
                }

                if (!This.customSSLVerification) {
                    goto doDefault;
                }

                if (challenge.ProtectionSpace.AuthenticationMethod != "NSURLAuthenticationMethodServerTrust") {
                    goto doDefault;
                }

                if (ServicePointManager.ServerCertificateValidationCallback == null) {
                    goto doDefault;
                }

                // Convert Mono Certificates to .NET certificates and build cert 
                // chain from root certificate
                var serverCertChain = challenge.ProtectionSpace.ServerSecTrust;
                var chain = new X509Chain();
                X509Certificate2 root = null;
                var errors = SslPolicyErrors.None;

                if (serverCertChain == null || serverCertChain.Count == 0) { 
                    errors = SslPolicyErrors.RemoteCertificateNotAvailable;
                    goto sslErrorVerify;
                }

                if (serverCertChain.Count == 1) {
                    errors = SslPolicyErrors.RemoteCertificateChainErrors;
                    goto sslErrorVerify;
                }

                var netCerts = Enumerable.Range(0, serverCertChain.Count)
                    .Select(x => serverCertChain[x].ToX509Certificate2())
                    .ToArray();

                for (int i = 1; i < netCerts.Length; i++) {
                    chain.ChainPolicy.ExtraStore.Add(netCerts[i]);
                }

                root = netCerts[0];

                chain.ChainPolicy.RevocationFlag = X509RevocationFlag.EntireChain;
                chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
                chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 1, 0);
                chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;

                if (!chain.Build(root)) {
                    errors = SslPolicyErrors.RemoteCertificateChainErrors;
                    goto sslErrorVerify;
                }

                var subject = root.Subject;
                var subjectCn = cnRegex.Match(subject).Groups[1].Value;

                if (String.IsNullOrWhiteSpace(subjectCn) || !Utility.MatchHostnameToPattern(task.CurrentRequest.Url.Host, subjectCn)) {
                    errors = SslPolicyErrors.RemoteCertificateNameMismatch;
                    goto sslErrorVerify;
                }

            sslErrorVerify:
                var hostname = task.CurrentRequest.Url.Host;
                bool result = ServicePointManager.ServerCertificateValidationCallback(hostname, root, chain, errors);
                if (result) {
                    completionHandler(
                        NSUrlSessionAuthChallengeDisposition.UseCredential,
                        NSUrlCredential.FromTrust(challenge.ProtectionSpace.ServerSecTrust));
                } else {
                    completionHandler(NSUrlSessionAuthChallengeDisposition.CancelAuthenticationChallenge, null);
                }
                return;

            doDefault:
                completionHandler(NSUrlSessionAuthChallengeDisposition.PerformDefaultHandling, challenge.ProposedCredential);
                return;
            }
            public override void DidReceiveChallenge(NSUrlSession session, NSUrlSessionTask task, NSUrlAuthenticationChallenge challenge, Action<NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler)
            {
                if (challenge.ProtectionSpace.AuthenticationMethod == NSUrlProtectionSpace.AuthenticationMethodNTLM) {
                    NetworkCredential credentialsToUse;

                    if (This.Credentials != null) {
                        if (This.Credentials is NetworkCredential) {
                            credentialsToUse = (NetworkCredential)This.Credentials;
                        } else {
                            var uri = this.getResponseForTask(task).Request.RequestUri;
                            credentialsToUse = This.Credentials.GetCredential(uri, "NTLM");
                        }
                        var credential = new NSUrlCredential(credentialsToUse.UserName, credentialsToUse.Password, NSUrlCredentialPersistence.ForSession);
                        completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, credential);
                    }
                    return;
                }

                if (!This.customSSLVerification) {
                    completionHandler(NSUrlSessionAuthChallengeDisposition.PerformDefaultHandling, challenge.ProposedCredential);
                }

                if (challenge.ProtectionSpace.AuthenticationMethod != "NSURLAuthenticationMethodServerTrust") {
                    completionHandler(NSUrlSessionAuthChallengeDisposition.PerformDefaultHandling, challenge.ProposedCredential);
                }

                if (ServicePointManager.ServerCertificateValidationCallback == null) {
                    completionHandler(NSUrlSessionAuthChallengeDisposition.PerformDefaultHandling, challenge.ProposedCredential);
                }

                // Convert Mono Certificates to .NET certificates and build cert 
                // chain from root certificate
                var serverCertChain = challenge.ProtectionSpace.ServerSecTrust;
                var chain = new X509Chain();
               
                var netCerts = Enumerable.Range(0, serverCertChain.Count)
                    .Select(x => serverCertChain[x].ToX509Certificate2())
                    .ToArray();

                for (int i = 1; i < netCerts.Length; i++) {
                    chain.ChainPolicy.ExtraStore.Add(netCerts[i]);
                }

                X509Certificate2 root = netCerts[0];

                chain.ChainPolicy.RevocationFlag = X509RevocationFlag.EntireChain;
                chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
                chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 1, 0);
                chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;

                chain.Build(root);

                var hostname = task.CurrentRequest.Url.Host;
                bool result = ServicePointManager.ServerCertificateValidationCallback(hostname, root, chain, SslPolicyErrors.None);
                if (result) {
                    completionHandler(NSUrlSessionAuthChallengeDisposition.PerformDefaultHandling, challenge.ProposedCredential);
                    /* Normally, the ServerCertificateValidationCallback can override the actual validation of the certificate. However, for some dumb reason, 
                     * the validation doesn't happen correctly. Thus either always rejecting trusted CAs, or always trusting untrusted CAs. The best way to fix this is if the callback
                     * returns true, do the default validation. This will prevent the callback from ever trusting and untrusted certificate. But we'll never need to do that. 
                     * completionHandler(
                        NSUrlSessionAuthChallengeDisposition.UseCredential,
                        NSUrlCredential.FromTrust(challenge.ProtectionSpace.ServerSecTrust));
                    */

                } else {
                    completionHandler(NSUrlSessionAuthChallengeDisposition.CancelAuthenticationChallenge, null);
                }
                return;
            }
Ejemplo n.º 44
0
 public virtual void DidCompleteWithError(NSUrlSession session, NSUrlSessionTask task, NSError error)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 45
0
		public override void DidCompleteWithError (NSUrlSession session, NSUrlSessionTask task, NSError error)
		{
			if (error != null) {
				_uploadCompleted (this, new NSUrlEventArgs (error));
			}
		}
Ejemplo n.º 46
0
        public static void Completed(NSUrlSessionTask downloadTask,NSUrl location)
        {
            NSFileManager fileManager = NSFileManager.DefaultManager;
            var url = downloadTask.OriginalRequest.Url.AbsoluteString;
            Console.WriteLine ("Looking for: {0}",url);
            NSError errorCopy = null;
            foreach (var f in Files) {
                Console.WriteLine ("Existing file: {0}", f.Key);
            }
            if(Files.ContainsKey(url))
            {
                var file = Files [url];
                file.Status = BackgroundDownloadFile.FileStatus.Temporary;
                file.Percent = 1;
                if (!AutoProcess) {
                    var sharedFolder = fileManager.GetContainerUrl (BackgroundDownload.SharedContainerIdentifier);
                    fileManager.CreateDirectory (sharedFolder, true, null,out errorCopy);
                    var fileName = Path.GetFileName (file.Destination);
                    var newTemp = Path.Combine (sharedFolder.RelativePath,fileName);

                    var success1 = fileManager.Copy (location, NSUrl.FromFilename(newTemp), out errorCopy);
                    Console.WriteLine ("Success: {0} {1}", success1,errorCopy);
                    file.TempLocation = fileName;
                    saveState ();
                    return;
                }
                NSUrl originalURL = downloadTask.OriginalRequest.Url;
                var dest = Path.Combine (BaseDir + file.Destination);
                NSUrl destinationURL = NSUrl.FromFilename (dest);
                NSError removeCopy;

                fileManager.Remove (destinationURL, out removeCopy);
                Console.WriteLine ("Trying to copy to {0}", dest);
                var success = fileManager.Copy (location, destinationURL, out errorCopy);
                if (success)
                    file.Status = BackgroundDownloadFile.FileStatus.Completed;
                Console.WriteLine ("Success: {0} {1}", success,errorCopy);
            }
            else
                Console.WriteLine ("Could not find the file!");

            TaskCompletionSource<bool> t;
            if (Tasks.TryGetValue (url, out t)) {
                if (errorCopy == null) {
                    if (!t.TrySetResult (true))
                        Console.WriteLine ("ERROR");
                } else {
                    var file = Files [url];
                    file.Status = BackgroundDownloadFile.FileStatus.Error;
                    file.Error = string.Format("Error during the copy: {0}", errorCopy.LocalizedDescription);
                    t.TrySetException (new Exception (file.Error));
                }
                BackgroundDownloadManager.Tasks.Remove (url);
            }
            RemoveUrl (url);
            saveState ();
            Console.WriteLine ("Tasks: {0}, Downloads {1}, Controllers {2} ", Tasks.Count, DownloadTasks.Count, Controllers.Count);
            foreach (var f in Files) {
                Console.WriteLine (f);
            }
            var evt = FileCompleted;
            if (evt != null)
                evt (downloadTask, new CompletedArgs{ File = Files [url]});
            if (RemoveCompletedAutomatically)
                Remove (url);
        }
Ejemplo n.º 47
0
 InflightOperation getResponseForTask(NSUrlSessionTask task)
 {
     lock (This.inflightRequests) {
         return This.inflightRequests[task];
     }
 }
Ejemplo n.º 48
0
        public static void Failed(NSUrlSession session, NSUrlSessionTask task, NSError error)
        {
            if (error != null)
                Console.WriteLine (error.LocalizedDescription);
            float progress = task.BytesReceived / (float)task.BytesExpectedToReceive;
            var url = task.OriginalRequest.Url.AbsoluteString;
            DownloadTasks.Remove (url);
            UpdateProgress (url, progress);
            TaskCompletionSource<bool> t;
            if (BackgroundDownloadManager.Tasks.TryGetValue (task.OriginalRequest.Url.AbsoluteString, out t)) {
                if (error == null) {
                    if (!t.TrySetResult (true))
                        Console.WriteLine ("ERROR");
                } else {

                    t.TrySetException (new Exception (string.Format ("Error during the copy: {0}", error.LocalizedDescription)));
                }
                BackgroundDownloadManager.Tasks.Remove (task.OriginalRequest.Url.AbsoluteString);
            }

            RemoveUrl (url);
        }
Ejemplo n.º 49
0
 public override void WillPerformHttpRedirection(NSUrlSession session, NSUrlSessionTask task, NSHttpUrlResponse response, NSUrlRequest newRequest, Action<NSUrlRequest> completionHandler)
 {
     NSUrlRequest nextRequest = (This.AllowAutoRedirect ? newRequest : null);
     completionHandler(nextRequest);
 }
Ejemplo n.º 50
0
 public HttpTask(TaskConfiguration config, NSUrlSessionTask task) : base(config, task is NSUrlSessionUploadTask)
 {
     this.task       = task;
     this.Identifier = task.TaskIdentifier.ToString();
 }