Esempio n. 1
0
        private static unsafe void HandleSessionError(IntPtr sessionHandlePtr, ErrorCode errorCode, byte *messageBuffer, IntPtr messageLength, IntPtr userInfoPairs, int userInfoPairsLength)
        {
            var handle  = new SessionHandle(sessionHandlePtr);
            var session = new Session(handle);
            var message = Encoding.UTF8.GetString(messageBuffer, (int)messageLength);

            SessionException exception;

            if (errorCode.IsClientResetError())
            {
                var userInfo = MarshalErrorUserInfo(userInfoPairs, userInfoPairsLength);
                exception = new ClientResetException(message, userInfo);
            }
            else if (errorCode == ErrorCode.PermissionDenied)
            {
                var userInfo = MarshalErrorUserInfo(userInfoPairs, userInfoPairsLength);
                exception = new PermissionDeniedException(message, userInfo);
            }
            else
            {
                exception = new SessionException(message, errorCode);
            }

            Session.RaiseError(session, exception);
        }
Esempio n. 2
0
        private static unsafe void HandleSessionError(IntPtr sessionHandlePtr, ErrorCode errorCode, byte *messageBuffer, IntPtr messageLength, IntPtr userInfoPairs, int userInfoPairsLength, bool isClientReset)
        {
            try
            {
                var handle  = new SessionHandle(sessionHandlePtr);
                var session = new Session(handle);
                var message = Encoding.UTF8.GetString(messageBuffer, (int)messageLength);

                SessionException exception;

                if (isClientReset)
                {
                    var userInfo = StringStringPair.UnmarshalDictionary(userInfoPairs, userInfoPairsLength);
                    exception = new ClientResetException(session.User.App, message, userInfo);
                }
                else if (errorCode == ErrorCode.PermissionDenied)
                {
                    var userInfo = StringStringPair.UnmarshalDictionary(userInfoPairs, userInfoPairsLength);
                    exception = new PermissionDeniedException(session.User.App, message, userInfo);
                }
                else
                {
                    exception = new SessionException(message, errorCode);
                }

                Session.RaiseError(session, exception);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Esempio n. 3
0
        public void OnMsg(ReliableTransferMsg msg)
        {
            if (netFail)
            {
                return;
            }

            StreamTransferSession session;
            ArgCollection         args;
            AppRef         appRef;
            AppPackageInfo packageInfo;
            string         path;

            args   = ArgCollection.Parse(msg.Args);
            appRef = AppRef.Parse(args["appref"]);

            if (msg.Direction == TransferDirection.Upload)
            {
                path    = packageFolder.BeginTransit(appRef);
                session = StreamTransferSession.ServerUpload(router, msg, path);
                session.BeginTransfer(onTransfer, new TransferInfo(session, path, msg.Direction));
            }
            else
            {
                packageInfo = packageFolder.GetPackageInfo(appRef);
                if (packageInfo == null)
                {
                    throw SessionException.Create(null, "Package [{0}] cannot be found.", appRef);
                }

                path    = packageInfo.FullPath;
                session = StreamTransferSession.ServerDownload(router, msg, path);
                session.BeginTransfer(onTransfer, new TransferInfo(session, path, msg.Direction));
            }
        }
Esempio n. 4
0
        public void OnMsg(AppStoreMsg msg)
        {
            if (netFail)
            {
                return;
            }

            try
            {
                switch (msg.Command)
                {
                case AppStoreQuery.RemoveCmd:

                    packageFolder.Remove(msg.AppRef);
                    break;

                case AppStoreQuery.SyncCmd:

                    using (TimedLock.Lock(syncLock))
                    {
                        this.forceSync       = true;
                        this.primaryPollTime = SysTime.Now;
                    }
                    break;

                default:

                    throw SessionException.Create("Unexpected AppStore command [{0}].", msg.Command);
                }
            }
            catch (Exception e)
            {
                SysLog.LogException(e);
            }
        }
        private void SessionExceptionHandler(IInvocation invocation, SessionException exception)
        {
            var methodName = invocation.Method.Name;
            var message    = $"{exception.Message} error in method {methodName}.";

            this._loggerService.LogMessage(message, LogLevel.Error);

            this._loggerService.LogMessage(
                new LogMessage
            {
                ClassName  = this.ToString(),
                Message    = exception.Message,
                MethodName = invocation.Method.Name
            },
                LogLevel.Debug);

            throw new System.ServiceModel.FaultException <ExceptionDetail>(
                      new ExceptionDetail(
                          false,
                          exception.Message,
                          description: methodName,
                          status: exception.errorCode != 0 ? exception.errorCode : ErrorCode.SessionError,
                          exceptionType: exception.GetType(),
                          loginAttempts: exception.attemptsLeft,
                          blockedTill: exception.blockedTill
                          ),
                      message
                      );
        }
        public static async Task RefreshAccessTokenAsync(Session session, bool reportErrors = true)
        {
            var user = session.User;

            if (user == null)
            {
                return;
            }

            try
            {
                var json = new Dictionary <string, object>
                {
                    ["data"]     = user.RefreshToken,
                    ["path"]     = session.ServerUri.AbsolutePath,
                    ["provider"] = "realm",
                    ["app_id"]   = AppId
                };

                var result = await MakeAuthRequestAsync(HttpMethod.Post, new Uri(user.ServerUri, "auth"), json)
                             .ConfigureAwait(continueOnCapturedContext: false);

                var syncWorker = result["sync_worker"];
                if (syncWorker != null)
                {
                    session.Handle.SetUrlPrefix(syncWorker["path"].Value <string>());
                }

                var accessToken = result["access_token"];
                var token_data  = accessToken["token_data"];

                session.Handle.SetMultiplexIdentifier(token_data["sync_label"].Value <string>());

                session.Handle.RefreshAccessToken(accessToken["token"].Value <string>(), token_data["path"].Value <string>());
                ScheduleTokenRefresh(user.Identity, user.ServerUri, session.Path, _date_1970.AddSeconds(accessToken["token_data"]["expires"].Value <long>()));
            }
            catch (HttpException ex) when(_connectivityStatusCodes.Contains(ex.StatusCode))
            {
                // 30 seconds is an arbitrarily chosen value, consider rationalizing it.
                ScheduleTokenRefresh(user.Identity, user.ServerUri, session.Path, DateTimeOffset.UtcNow.AddSeconds(30));
            }
            catch (Exception ex)
            {
                if (reportErrors)
                {
                    var sessionException = new SessionException("An error has occurred while refreshing the access token.",
                                                                ErrorCode.BadUserAuthentication,
                                                                ex);

                    Session.RaiseError(session, sessionException);
                }
            }
            finally
            {
                // session.User creates a new user each time, so it's safe to dispose the handle here.
                // It won't actually corrupt the state of the session.
                user.Handle.Dispose();
            }
        }
Esempio n. 7
0
 private void RaiseSessionExceptionEvent(Exception ex)
 {
     if (SessionException == null)
     {
         return;
     }
     foreach (EventHandler <TcpIpSessionExceptionEventArgs> del in SessionException.GetInvocationList())
     {
         del.BeginInvoke(this, new TcpIpSessionExceptionEventArgs(ex),
                         AsyncCallBackRaiseSessionExceptionEvent, del);
     }
 }
Esempio n. 8
0
        private static unsafe void HandleSessionWaitCallback(IntPtr taskCompletionSource, int error_code, byte *messageBuffer, IntPtr messageLength)
        {
            var handle = GCHandle.FromIntPtr(taskCompletionSource);
            var tcs    = (TaskCompletionSource <object>)handle.Target;

            if (error_code == 0)
            {
                tcs.TrySetResult(null);
            }
            else
            {
                var          inner        = new SessionException(Encoding.UTF8.GetString(messageBuffer, (int)messageLength), (ErrorCode)error_code);
                const string OuterMessage = "A system error occurred while waiting for completion. See InnerException for more details";
                tcs.TrySetException(new RealmException(OuterMessage, inner));
            }
        }
Esempio n. 9
0
        private static unsafe void HandleOpenRealmCallback(IntPtr taskCompletionSource, IntPtr realm_reference, int error_code, byte *messageBuffer, IntPtr messageLength)
        {
            var handle = GCHandle.FromIntPtr(taskCompletionSource);
            var tcs    = (TaskCompletionSource <ThreadSafeReferenceHandle>)handle.Target;

            if (error_code == 0)
            {
                tcs.TrySetResult(new ThreadSafeReferenceHandle(realm_reference, isRealmReference: true));
            }
            else
            {
                var          inner        = new SessionException(Encoding.UTF8.GetString(messageBuffer, (int)messageLength), (ErrorCode)error_code);
                const string OuterMessage = "A system error occurred while opening a Realm. See InnerException for more details";
                tcs.TrySetException(new RealmException(OuterMessage, inner));
            }
        }
Esempio n. 10
0
        private static SessionException CreateInvalidResponseException(ICollection <KeyValuePair <string, string> > metaData, HttpStatusCode statusCode)
        {
            var ex = new SessionException(
                string.Format(
                    SessionResources.DynamoDB_ErrorInResponse, Enum.GetName(typeof(HttpStatusCode), statusCode)));

            if (metaData != null && metaData.Count > 0)
            {
                foreach (var pair in metaData)
                {
                    ex.Data.Add(pair.Key, pair.Value);
                }
            }

            return(ex);
        }
Esempio n. 11
0
        private void RaiseSessionExceptionEvent(Exception ex)
        {
            if (SessionException == null)
            {
                return;
            }
            foreach (EventHandler <TcpIpSessionExceptionEventArgs> del in SessionException.GetInvocationList())
            {
#if NET40
                del.BeginInvoke(this, new TcpIpSessionExceptionEventArgs(ex),
                                AsyncCallBackRaiseSessionExceptionEvent, del);
#else
                System.Threading.Tasks.Task.Run(() => del.Invoke(this, new TcpIpSessionExceptionEventArgs(ex)));
#endif
            }
        }
Esempio n. 12
0
        internal static Exception TranslateFaultException(FaultException <SessionFault> innerException)
        {
            Exception exception = null;

            if (innerException != null)
            {
                string errorMessage = innerException.Reason.GetMatchingTranslation().Text;
                switch (innerException.Detail.Code)
                {
                case (int)SOAFaultCode.NoAvailableBrokerNodes:
                    errorMessage = SR.NoBrokerNodeFound;
                    break;

                case (int)SOAFaultCode.StorageSpaceNotSufficient:
                    errorMessage = SR.StorageSpaceNotSufficient;
                    break;

                case (int)SOAFaultCode.OperationTimeout:
                    exception = new TimeoutException(innerException.Detail.Reason);
                    break;

                case (int)SOAFaultCode.AccessDenied_Broker:
                case (int)SOAFaultCode.AccessDenied_BrokerLauncher:
                case (int)SOAFaultCode.AccessDenied_BrokerQueue:
                case (int)SOAFaultCode.AuthenticationFailure:
                    exception = new AuthenticationException(GenerateErrorMessage(innerException.Detail, errorMessage), innerException);
                    break;

                case (int)SOAFaultCode.ConfigFile_Invalid:
                    exception = new ConfigurationErrorsException(GenerateErrorMessage(innerException.Detail, errorMessage), innerException);
                    break;

                default:
                    // If no such string is found, null is returned
                    errorMessage = GenerateErrorMessage(innerException.Detail, errorMessage);
                    break;
                }

                if (exception == null)
                {
                    exception = new SessionException(innerException.Detail.Code, errorMessage);
                }
            }

            return(exception);
        }
Esempio n. 13
0
        private static unsafe void HandleSessionError(IntPtr sessionHandlePtr, ErrorCode errorCode, sbyte *messageBuffer, IntPtr messageLength, IntPtr userInfoPairs, int userInfoPairsLength)
        {
            var session = Session.Create(sessionHandlePtr);
            var message = new string(messageBuffer, 0, (int)messageLength, Encoding.UTF8);

            SessionException exception;

            if (errorCode.IsClientResetError())
            {
                var userInfo = MarshalErrorUserInfo(userInfoPairs, userInfoPairsLength);
                exception = new ClientResetException(message, userInfo);
            }
            else
            {
                exception = new SessionException(message, errorCode);
            }

            Session.RaiseError(session, exception);
        }
        public static async Task RefreshAccessToken(Session session, bool reportErrors = true)
        {
            var user = session.User;

            try
            {
                var json = new JsonObject
                {
                    ["data"]     = user.RefreshToken,
                    ["path"]     = session.ServerUri.AbsolutePath,
                    ["provider"] = "realm"
                };

                var result = await MakeAuthRequestAsync(user.ServerUri, json, TimeSpan.FromSeconds(30)).ConfigureAwait(continueOnCapturedContext: false);

                var access_token = result["access_token"];

                session.Handle.RefreshAccessToken(access_token["token"], access_token["token_data"]["path"]);
                ScheduleTokenRefresh(user.Identity, session.Path, _date_1970.AddSeconds(access_token["token_data"]["expires"]));
            }
            catch (HttpException ex) when(_connectivityStatusCodes.Contains(ex.StatusCode))
            {
                // 30 seconds is an arbitrarily chosen value, consider rationalizing it.
                ScheduleTokenRefresh(user.Identity, session.Path, DateTimeOffset.UtcNow.AddSeconds(30));
            }
            catch (Exception ex)
            {
                if (reportErrors)
                {
                    var sessionException = new SessionException("An error has occurred while refreshing the access token.",
                                                                ErrorCode.BadUserAuthentication,
                                                                ex);

                    Session.RaiseError(session, sessionException);
                }
            }
            finally
            {
                // session.User creates a new user each time, so it's safe to dispose the handle here.
                // It won't actually corrupt the state of the session.
                user.Handle.Dispose();
            }
        }
Esempio n. 15
0
        private void FireException(string Message, EFlags ExceptionCode, string Token)
        {
            SessionException exception = new SessionException();

            exception.SetMessage(Message);
            exception.Token         = Token;
            exception.ExceptionCode = ExceptionCode;

            string Url = GetDefaultUrl();

            if (Url != null)
            {
                throw exception;
            }
            else
            {
                throw new ApplicationException("Session expire. Please login again.");
            }
        }
Esempio n. 16
0
        public void OnMsg(AppStoreQuery msg)
        {
            if (netFail)
            {
                return;
            }

            var ack = new AppStoreAck();

            try
            {
                switch (msg.Command)
                {
                case AppStoreQuery.GetPrimaryCmd:

                    ack.StoreEP = this.PrimaryEP;
                    break;

                case AppStoreQuery.ListCmd:

                    ack.Packages = packageFolder.GetPackages();
                    break;

                case AppStoreQuery.RemoveCmd:

                    packageFolder.Remove(msg.AppRef);
                    break;

                case AppStoreQuery.SyncCmd:

                    using (TimedLock.Lock(syncLock))
                    {
                        this.forceSync       = true;
                        this.primaryPollTime = SysTime.Now;
                    }
                    break;

                case AppStoreQuery.DownloadCmd:

                    ack.StoreEP = cluster.InstanceEP;

                    MsgEP           primaryEP;
                    PendingDownload pending;

                    using (TimedLock.Lock(syncLock))
                    {
                        if (packageFolder.GetPackageInfo(msg.AppRef) != null)
                        {
                            break;      // The package is ready for downloading
                        }
                        if (mode == AppStoreMode.Primary || this.PrimaryEP == null)
                        {
                            throw SessionException.Create(null, "Package [{0}] cannot be found.", msg.AppRef);
                        }

                        primaryEP = this.PrimaryEP;
                        downloads.TryGetValue(msg.AppRef, out pending);
                    }

                    if (pending != null)
                    {
                        // A download is already pending for this package so wait
                        // for it to complete.

                        pending.Wait();
                    }
                    else
                    {
                        // Try downloading the requested package from the primary
                        // application store.

                        string transitPath = null;

                        pending = new PendingDownload(msg.AppRef);
                        using (TimedLock.Lock(syncLock))
                            downloads.Add(msg.AppRef, pending);

                        try
                        {
                            transitPath = packageFolder.BeginTransit(msg.AppRef);
                            DownloadPackage(primaryEP, msg.AppRef, transitPath);
                            packageFolder.EndTransit(transitPath, true);

                            pending.Done(null);
                        }
                        catch (Exception e)
                        {
                            packageFolder.EndTransit(transitPath, false);
                            pending.Done(e);
                            throw;
                        }
                        finally
                        {
                            using (TimedLock.Lock(syncLock))
                            {
                                try
                                {
                                    downloads.Remove(msg.AppRef);
                                }
                                catch
                                {
                                    // Ignore errors
                                }
                            }
                        }
                    }
                    break;

                default:

                    throw SessionException.Create("Unexpected AppStore command [{0}].", msg.Command);
                }
            }
            catch (Exception e)
            {
                ack.Exception = e.Message;
                SysLog.LogException(e);
            }

            router.ReplyTo(msg, ack);
        }