Esempio n. 1
0
        private Task SubscribeToContact(HttpRequest Request, HttpResponse Response)
        {
            Gateway.AssertUserAuthenticated(Request, this.ConfigPrivilege);

            if (!Request.HasData)
            {
                throw new BadRequestException();
            }

            object Obj = Request.DecodeData();

            if (!(Obj is string JID))
            {
                throw new BadRequestException();
            }

            Response.ContentType = "text/plain";

            XmppClient Client  = Gateway.XmppClient;
            RosterItem Contact = Client.GetRosterItem(JID);

            if (Contact is null)
            {
                return(Response.Write("0"));
            }
            else
            {
                Client.RequestPresenceSubscription(Contact.BareJid, this.NickName());
                Log.Informational("Requesting presence subscription.", Contact.BareJid);
                return(Response.Write("1"));
            }
        }
        /// <summary>
        /// Method is called when the user completes the current configuration task.
        /// </summary>
        /// <param name="Request">HTTP Request</param>
        /// <param name="Response">HTTP Response</param>
        protected virtual async void ConfigComplete(HttpRequest Request, HttpResponse Response)
        {
            Gateway.AssertUserAuthenticated(Request);

            Response.StatusCode = 200;
            await this.MakeCompleted();
        }
Esempio n. 3
0
        private Task RenameContact(HttpRequest Request, HttpResponse Response)
        {
            Gateway.AssertUserAuthenticated(Request, this.ConfigPrivilege);

            if (!Request.HasData)
            {
                throw new BadRequestException();
            }

            object Obj     = Request.DecodeData();
            string JID     = Request.Header["X-BareJID"];
            string NewName = Obj as string;

            if (JID is null || string.IsNullOrEmpty(JID))
            {
                throw new BadRequestException();
            }

            Response.ContentType = "text/plain";

            XmppClient Client  = Gateway.XmppClient;
            RosterItem Contact = Client.GetRosterItem(JID);

            if (Contact is null)
            {
                return(Response.Write("0"));
            }
            else
            {
                Client.UpdateRosterItem(Contact.BareJid, NewName, Contact.Groups);
                Log.Informational("Contact renamed.", Contact.BareJid, new KeyValuePair <string, object>("Name", NewName));
                return(Response.Write("1"));
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Executes the POST method on the resource.
        /// </summary>
        /// <param name="Request">HTTP Request</param>
        /// <param name="Response">HTTP Response</param>
        /// <exception cref="HttpException">If an error occurred when processing the method.</exception>
        public async Task POST(HttpRequest Request, HttpResponse Response)
        {
            try
            {
                Gateway.AssertUserAuthenticated(Request, "Admin.Legal.ProposeContract");

                if (Gateway.ContractsClient is null)
                {
                    throw new NotSupportedException("Proposing new contracts not permitted. Broker does not support smart contracts.");
                }

                if (!Request.HasData)
                {
                    throw new BadRequestException("No data in post.");
                }

                Variables PageVariables = Page.GetPageVariables(Request.Session, "/ProposeContract.md");
                object    Posted        = Request.DecodeData();

                if (Posted is XmlDocument Doc)
                {
                    Contract Contract = Contract.Parse(Doc, out bool HasStatus);
                    if (HasStatus)
                    {
                        throw new ForbiddenException("Contract must not have a status section.");
                    }

                    PageVariables["Contract"] = Contract;
                }
                else if (Posted is bool Command)
                {
                    if (!PageVariables.TryGetVariable("Contract", out Variable v) ||
                        !(v.ValueObject is Contract Contract))
                    {
                        throw new BadRequestException("No smart contract uploaded.");
                    }

                    if (Command)
                    {
                        Contract = await Gateway.ContractsClient.CreateContractAsync(Contract.ForMachines, Contract.ForHumans,
                                                                                     Contract.Roles, Contract.Parts, Contract.Parameters, Contract.Visibility, Contract.PartsMode, Contract.Duration,
                                                                                     Contract.ArchiveRequired, Contract.ArchiveOptional, Contract.SignAfter, Contract.SignBefore, Contract.CanActAsTemplate);

                        PageVariables["Contract"] = Contract;
                    }
                    else
                    {
                        PageVariables.Remove("Contract");
                    }
                }
                else
                {
                    throw new BadRequestException("Invalid type of posted data.");
                }
            }
            catch (Exception ex)
            {
                await Response.SendResponse(ex);
            }
        }
Esempio n. 5
0
        private void DeclineRequest(HttpRequest Request, HttpResponse Response)
        {
            Gateway.AssertUserAuthenticated(Request);

            if (!Request.HasData)
            {
                throw new BadRequestException();
            }

            object Obj = Request.DecodeData();

            if (!(Obj is string JID))
            {
                throw new BadRequestException();
            }

            Response.ContentType = "text/plain";

            XmppClient Client = Gateway.XmppClient;

            PresenceEventArgs SubscriptionRequest = Client.GetSubscriptionRequest(JID);

            if (SubscriptionRequest is null)
            {
                Response.Write("0");
            }
            else
            {
                SubscriptionRequest.Decline();
                Log.Informational("Declining presence subscription request.", SubscriptionRequest.FromBareJID);
                Response.Write("1");

                this.RosterItemRemoved(JID);
            }
        }
Esempio n. 6
0
        private void UnsubscribeContact(HttpRequest Request, HttpResponse Response)
        {
            Gateway.AssertUserAuthenticated(Request);

            if (!Request.HasData)
            {
                throw new BadRequestException();
            }

            object Obj = Request.DecodeData();

            if (!(Obj is string JID))
            {
                throw new BadRequestException();
            }

            Response.ContentType = "text/plain";

            XmppClient Client  = Gateway.XmppClient;
            RosterItem Contact = Client.GetRosterItem(JID);

            if (Contact is null)
            {
                Response.Write("0");
            }
            else
            {
                Client.RequestPresenceUnsubscription(Contact.BareJid);
                Log.Informational("Unsubscribing from presence.", Contact.BareJid);
                Response.Write("1");
            }
        }
Esempio n. 7
0
        private Task RemoveContact(HttpRequest Request, HttpResponse Response)
        {
            Gateway.AssertUserAuthenticated(Request);

            if (!Request.HasData)
            {
                throw new BadRequestException();
            }

            object Obj = Request.DecodeData();

            if (!(Obj is string JID))
            {
                throw new BadRequestException();
            }

            Response.ContentType = "text/plain";

            XmppClient Client  = Gateway.XmppClient;
            RosterItem Contact = Client.GetRosterItem(JID);

            if (Contact is null)
            {
                return(Response.Write("0"));
            }
            else
            {
                Client.RemoveRosterItem(Contact.BareJid);
                Log.Informational("Contact removed.", Contact.BareJid);
                return(Response.Write("1"));
            }
        }
Esempio n. 8
0
        private async Task TestNotificationAddresses(HttpRequest Request, HttpResponse Response)
        {
            Gateway.AssertUserAuthenticated(Request, this.ConfigPrivilege);

            if (!Request.HasData)
            {
                throw new BadRequestException();
            }

            object Obj = Request.DecodeData();

            if (!(Obj is string Address))
            {
                throw new BadRequestException();
            }

            string TabID = Request.Header["X-TabID"];

            if (string.IsNullOrEmpty(TabID))
            {
                throw new BadRequestException();
            }

            List <CaseInsensitiveString> Addresses = new List <CaseInsensitiveString>();

            Response.StatusCode = 200;

            try
            {
                foreach (string Part in Address.Split(';'))
                {
                    string s = Part.Trim();
                    if (string.IsNullOrEmpty(s))
                    {
                        continue;
                    }

                    MailAddress Addr = new MailAddress(s);
                    Addresses.Add(Addr.Address);
                }

                this.addresses = Addresses.ToArray();

                await Database.Update(this);

                if (this.addresses.Length > 0)
                {
                    Gateway.SendNotification("Test\r\n===========\r\n\r\nThis message was generated to test the notification feature of **" + Gateway.ApplicationName + "**.");
                }

                await Response.Write(1);
            }
            catch (Exception)
            {
                await Response.Write(0);
            }

            await Response.SendResponse();
        }
Esempio n. 9
0
        /// <summary>
        /// Executes the POST method on the resource.
        /// </summary>
        /// <param name="Request">HTTP Request</param>
        /// <param name="Response">HTTP Response</param>
        /// <exception cref="HttpException">If an error occurred when processing the method.</exception>
        public void POST(HttpRequest Request, HttpResponse Response)
        {
            Gateway.AssertUserAuthenticated(Request);

            if (!Request.HasData ||
                !(Request.DecodeData() is Dictionary <string, object> RequestObj) ||
                !RequestObj.TryGetValue("TypeOfFile", out object Obj) ||
                !(Obj is string TypeOfFile) ||
                !RequestObj.TryGetValue("Database", out Obj) ||
                !(Obj is bool Database) ||
                !RequestObj.TryGetValue("WebContent", out Obj) ||
                !(Obj is bool WebContent))
            {
                throw new BadRequestException();
            }

            KeyValuePair <string, IExportFormat> Exporter = GetExporter(TypeOfFile);

            lock (synchObject)
            {
                if (exporting)
                {
                    Response.StatusCode    = 409;
                    Response.StatusMessage = "Conflict";
                    Response.ContentType   = "text/plain";
                    Response.Write("Export is underway.");
                    return;
                }
                else
                {
                    exporting = true;
                }
            }

            Export.ExportType       = TypeOfFile;
            Export.ExportDatabase   = Database;
            Export.ExportWebContent = WebContent;

            List <string> Folders = new List <string>();

            foreach (Export.FolderCategory FolderCategory in Export.GetRegisteredFolders())
            {
                if (RequestObj.TryGetValue(FolderCategory.CategoryId, out Obj) && Obj is bool b)
                {
                    Export.SetExportFolderAsync(FolderCategory.CategoryId, b).Wait();

                    if (b)
                    {
                        Folders.AddRange(FolderCategory.Folders);
                    }
                }
            }

            Task Task = DoExport(Exporter.Value, Database, WebContent, Folders.ToArray());

            Response.StatusCode  = 200;
            Response.ContentType = "text/plain";
            Response.Write(Exporter.Key);
        }
Esempio n. 10
0
        /// <summary>
        /// Method is called when the user completes the current configuration task.
        /// </summary>
        /// <param name="Request">HTTP Request</param>
        /// <param name="Response">HTTP Response</param>
        protected virtual async Task ConfigComplete(HttpRequest Request, HttpResponse Response)
        {
            Gateway.AssertUserAuthenticated(Request, this.ConfigPrivilege);

            await this.MakeCompleted();

            Response.StatusCode = 200;
        }
Esempio n. 11
0
        private Task RandomizePassword(HttpRequest Request, HttpResponse Response)
        {
            Gateway.AssertUserAuthenticated(Request);

            Response.StatusCode  = 200;
            Response.ContentType = "text/plain";
            return(Response.Write(Base64Url.Encode(Gateway.NextBytes(32))));
        }
Esempio n. 12
0
        private void RandomizePassword(HttpRequest Request, HttpResponse Response)
        {
            Gateway.AssertUserAuthenticated(Request);

            Response.StatusCode  = 200;
            Response.ContentType = "text/plain";
            Response.Write(Hashes.BinaryToString(Gateway.NextBytes(32)));
        }
Esempio n. 13
0
        private async Task Simplified(HttpRequest Request, HttpResponse Response)
        {
            Gateway.AssertUserAuthenticated(Request, this.ConfigPrivilege);

            await Gateway.SimplifiedConfiguration();

            Response.StatusCode = 200;
            await this.MakeCompleted();

            await Response.SendResponse();
        }
Esempio n. 14
0
        private void TestDomainNames(HttpRequest Request, HttpResponse Response)
        {
            Gateway.AssertUserAuthenticated(Request);

            if (!Request.HasData)
            {
                throw new BadRequestException();
            }

            object Obj = Request.DecodeData();

            if (!(Obj is Dictionary <string, object> Parameters))
            {
                throw new BadRequestException();
            }

            if (!Parameters.TryGetValue("domainName", out Obj) || !(Obj is string DomainName))
            {
                throw new BadRequestException();
            }

            List <string> AlternativeNames = new List <string>();
            int           Index            = 0;

            while (Parameters.TryGetValue("altDomainName" + Index.ToString(), out Obj) && Obj is string AltDomainName && !string.IsNullOrEmpty(AltDomainName))
            {
                AlternativeNames.Add(AltDomainName);
                Index++;
            }

            if (Parameters.TryGetValue("altDomainName", out Obj) && Obj is string AltDomainName2 && !string.IsNullOrEmpty(AltDomainName2))
            {
                AlternativeNames.Add(AltDomainName2);
            }

            string TabID = Request.Header["X-TabID"];

            if (string.IsNullOrEmpty(TabID))
            {
                throw new BadRequestException();
            }

            this.domain             = DomainName;
            this.alternativeDomains = AlternativeNames.Count == 0 ? null : AlternativeNames.ToArray();
            this.useDomainName      = true;

            Response.StatusCode = 200;

            this.Test(TabID);
        }
Esempio n. 15
0
        /// <summary>
        /// Executes the POST method on the resource.
        /// </summary>
        /// <param name="Request">HTTP Request</param>
        /// <param name="Response">HTTP Response</param>
        /// <exception cref="HttpException">If an error occurred when processing the method.</exception>
        public Task POST(HttpRequest Request, HttpResponse Response)
        {
            Gateway.AssertUserAuthenticated(Request, "Admin.Data.Backup");

            if (!Request.HasData)
            {
                throw new BadRequestException();
            }

            if (!(Request.DecodeData() is string FileName))
            {
                throw new BadRequestException();
            }

            string Dir;

            if (FileName.EndsWith(".key", StringComparison.CurrentCultureIgnoreCase))
            {
                Dir = Export.FullKeyExportFolder;
            }
            else
            {
                Dir = Export.FullExportFolder;
            }

            if (!Directory.Exists(Dir))
            {
                throw new NotFoundException("Folder not found: " + Dir);
            }

            string FullFileName = Dir + Path.DirectorySeparatorChar + FileName;

            if (!File.Exists(FullFileName))
            {
                throw new NotFoundException("File not found: " + FullFileName);
            }

            File.Delete(FullFileName);

            Log.Informational("Export deleted.", FileName);

            Response.StatusCode  = 200;
            Response.ContentType = "text/plain";
            Response.Write("1");

            ExportFormat.UpdateClientsFileDeleted(FileName);

            return(Task.CompletedTask);
        }
Esempio n. 16
0
        /// <summary>
        /// Method is called when the user completes the current configuration task.
        /// </summary>
        /// <param name="Request">HTTP Request</param>
        /// <param name="Response">HTTP Response</param>
        protected virtual async void ConfigComplete(HttpRequest Request, HttpResponse Response)
        {
            try
            {
                Gateway.AssertUserAuthenticated(Request);

                Response.StatusCode = 200;
                await this.MakeCompleted();

                Response.SendResponse();
            }
            catch (Exception ex)
            {
                Response.SendResponse(ex);
            }
        }
Esempio n. 17
0
        private async void Simplified(HttpRequest Request, HttpResponse Response)
        {
            try
            {
                Gateway.AssertUserAuthenticated(Request);

                await Gateway.SimplifiedConfiguration();

                Response.StatusCode = 200;
                await this.MakeCompleted();

                Response.SendResponse();
            }
            catch (Exception ex)
            {
                Response.SendResponse(ex);
            }
        }
Esempio n. 18
0
        private Task ConnectToJID(HttpRequest Request, HttpResponse Response)
        {
            Gateway.AssertUserAuthenticated(Request, this.ConfigPrivilege);

            if (!Request.HasData)
            {
                throw new BadRequestException();
            }

            object Obj = Request.DecodeData();

            if (!(Obj is string JID))
            {
                throw new BadRequestException();
            }

            Response.ContentType = "text/plain";

            if (!XmppClient.BareJidRegEx.IsMatch(JID))
            {
                return(Response.Write("0"));
            }
            else
            {
                RosterItem Item = Gateway.XmppClient.GetRosterItem(JID);
                if (Item is null)
                {
                    Gateway.XmppClient.RequestPresenceSubscription(JID, this.NickName());
                    Log.Informational("Requesting presence subscription.", JID);
                    return(Response.Write("1"));
                }
                else if (Item.State != SubscriptionState.Both && Item.State != SubscriptionState.To)
                {
                    Gateway.XmppClient.RequestPresenceSubscription(JID, this.NickName());
                    Log.Informational("Requesting presence subscription.", JID);
                    return(Response.Write("2"));
                }
                else
                {
                    return(Response.Write("3"));
                }
            }
        }
Esempio n. 19
0
        private Task AcceptRequest(HttpRequest Request, HttpResponse Response)
        {
            Gateway.AssertUserAuthenticated(Request, this.ConfigPrivilege);

            if (!Request.HasData)
            {
                throw new BadRequestException();
            }

            object Obj = Request.DecodeData();

            if (!(Obj is string JID))
            {
                throw new BadRequestException();
            }

            Response.ContentType = "text/plain";

            XmppClient Client = Gateway.XmppClient;

            PresenceEventArgs SubscriptionRequest = Client.GetSubscriptionRequest(JID);

            if (SubscriptionRequest is null)
            {
                return(Response.Write("0"));
            }
            else
            {
                SubscriptionRequest.Accept();
                Log.Informational("Accepting presence subscription request.", SubscriptionRequest.FromBareJID);

                if (Gateway.XmppClient.LastSetPresenceAvailability != Availability.Offline)
                {
                    Gateway.XmppClient.SetPresence(
                        Gateway.XmppClient.LastSetPresenceAvailability,
                        Gateway.XmppClient.LastSetPresenceCustomStatus);
                }

                return(Response.Write("1"));
            }
        }
Esempio n. 20
0
        private Task SetTheme(HttpRequest Request, HttpResponse Response)
        {
            Gateway.AssertUserAuthenticated(Request);

            if (!Request.HasData)
            {
                throw new BadRequestException();
            }

            object Obj = Request.DecodeData();

            if (!(Obj is string ThemeId))
            {
                throw new BadRequestException();
            }

            string TabID = Request.Header["X-TabID"];

            if (string.IsNullOrEmpty(TabID))
            {
                throw new BadRequestException();
            }

            if (themeDefinitions.TryGetValue(ThemeId, out ThemeDefinition Def))
            {
                Theme.CurrerntTheme = Def;
            }
            else
            {
                throw new NotFoundException("Theme not found: " + ThemeId);
            }

            this.UpdateTheme(Def, TabID);

            Response.StatusCode = 200;

            return(Task.CompletedTask);
        }
Esempio n. 21
0
        private void TestCA(HttpRequest Request, HttpResponse Response)
        {
            Gateway.AssertUserAuthenticated(Request);

            if (!Request.HasData)
            {
                throw new BadRequestException();
            }

            object Obj = Request.DecodeData();

            if (!(Obj is Dictionary <string, object> Parameters))
            {
                throw new BadRequestException();
            }

            if (!Parameters.TryGetValue("useEncryption", out Obj) || !(Obj is bool UseEncryption))
            {
                throw new BadRequestException();
            }

            if (!Parameters.TryGetValue("customCA", out Obj) || !(Obj is bool CustomCA))
            {
                throw new BadRequestException();
            }

            if (!Parameters.TryGetValue("acmeDirectory", out Obj) || !(Obj is string AcmeDirectory))
            {
                throw new BadRequestException();
            }

            if (!Parameters.TryGetValue("contactEMail", out Obj) || !(Obj is string ContactEMail))
            {
                throw new BadRequestException();
            }

            if (!Parameters.TryGetValue("acceptToS", out Obj) || !(Obj is bool AcceptToS))
            {
                throw new BadRequestException();
            }

            if (!Parameters.TryGetValue("domainName", out Obj) || !(Obj is string DomainName))
            {
                throw new BadRequestException();
            }

            List <string> AlternativeNames = new List <string>();
            int           Index            = 0;

            while (Parameters.TryGetValue("altDomainName" + Index.ToString(), out Obj) && Obj is string AltDomainName && !string.IsNullOrEmpty(AltDomainName))
            {
                AlternativeNames.Add(AltDomainName);
                Index++;
            }

            if (Parameters.TryGetValue("altDomainName", out Obj) && Obj is string AltDomainName2 && !string.IsNullOrEmpty(AltDomainName2))
            {
                AlternativeNames.Add(AltDomainName2);
            }

            string TabID = Request.Header["X-TabID"];

            if (string.IsNullOrEmpty(TabID))
            {
                throw new BadRequestException();
            }

            this.domain             = DomainName;
            this.alternativeDomains = AlternativeNames.Count == 0 ? null : AlternativeNames.ToArray();
            this.useDomainName      = true;
            this.useEncryption      = UseEncryption;
            this.customCA           = CustomCA;
            this.acmeDirectory      = AcmeDirectory;
            this.contactEMail       = ContactEMail;
            this.acceptToS          = AcceptToS;

            Response.StatusCode = 200;

            if (!this.inProgress)
            {
                this.inProgress = true;
                Task _ = this.CreateCertificate(TabID);
            }
        }
Esempio n. 22
0
        private void TestDomainNames(HttpRequest Request, HttpResponse Response)
        {
            Gateway.AssertUserAuthenticated(Request);

            if (!Request.HasData)
            {
                throw new BadRequestException();
            }

            object Obj = Request.DecodeData();

            if (!(Obj is Dictionary <string, object> Parameters))
            {
                throw new BadRequestException();
            }

            if (!Parameters.TryGetValue("domainName", out Obj) || !(Obj is string DomainName) ||
                !Parameters.TryGetValue("dynamicDns", out Obj) || !(Obj is bool DynamicDns) ||
                !Parameters.TryGetValue("dynDnsTemplate", out Obj) || !(Obj is string DynDnsTemplate) ||
                !Parameters.TryGetValue("checkIpScript", out Obj) || !(Obj is string CheckIpScript) ||
                !Parameters.TryGetValue("updateIpScript", out Obj) || !(Obj is string UpdateIpScript) ||
                !Parameters.TryGetValue("dynDnsAccount", out Obj) || !(Obj is string DynDnsAccount) ||
                !Parameters.TryGetValue("dynDnsPassword", out Obj) || !(Obj is string DynDnsPassword) ||
                !Parameters.TryGetValue("dynDnsInterval", out Obj) || !(Obj is int DynDnsInterval))
            {
                throw new BadRequestException();
            }

            List <string> AlternativeNames = new List <string>();
            int           Index            = 0;

            while (Parameters.TryGetValue("altDomainName" + Index.ToString(), out Obj) && Obj is string AltDomainName && !string.IsNullOrEmpty(AltDomainName))
            {
                AlternativeNames.Add(AltDomainName);
                Index++;
            }

            if (Parameters.TryGetValue("altDomainName", out Obj) && Obj is string AltDomainName2 && !string.IsNullOrEmpty(AltDomainName2))
            {
                AlternativeNames.Add(AltDomainName2);
            }

            string TabID = Request.Header["X-TabID"];

            if (string.IsNullOrEmpty(TabID))
            {
                throw new BadRequestException();
            }

            this.dynamicDns         = DynamicDns;
            this.dynDnsTemplate     = DynDnsTemplate;
            this.checkIpScript      = CheckIpScript;
            this.updateIpScript     = UpdateIpScript;
            this.dynDnsAccount      = DynDnsAccount;
            this.dynDnsPassword     = DynDnsPassword;
            this.dynDnsInterval     = DynDnsInterval;
            this.domain             = DomainName;
            this.alternativeDomains = AlternativeNames.Count == 0 ? null : AlternativeNames.ToArray();
            this.useDomainName      = true;

            Response.StatusCode = 200;

            this.Test(TabID);
        }
        /// <summary>
        /// Executes the POST method on the resource.
        /// </summary>
        /// <param name="Request">HTTP Request</param>
        /// <param name="Response">HTTP Response</param>
        /// <exception cref="HttpException">If an error occurred when processing the method.</exception>
        public async Task POST(HttpRequest Request, HttpResponse Response)
        {
            Gateway.AssertUserAuthenticated(Request, "Admin.Data.Backup");

            if (!Request.HasData)
            {
                throw new BadRequestException();
            }

            object Obj = Request.DecodeData();

            string[] P;

            if (!(Obj is string s))
            {
                throw new BadRequestException();
            }

            P = s.Split('\n');
            if (P.Length != 2)
            {
                throw new BadRequestException();
            }

            string ExportFolder = P[0].Trim();
            string KeyFolder    = P[1].Trim();
            int    Len;

            Len = ExportFolder.Length;
            if (Len > 0 && (ExportFolder[Len - 1] == '/' || ExportFolder[Len - 1] == '\\'))
            {
                ExportFolder = ExportFolder.Substring(0, Len - 1);
            }

            Len = KeyFolder.Length;
            if (Len > 0 && (KeyFolder[Len - 1] == '/' || KeyFolder[Len - 1] == '\\'))
            {
                KeyFolder = KeyFolder.Substring(0, Len - 1);
            }

            if (!string.IsNullOrEmpty(ExportFolder))
            {
                if (!Path.IsPathRooted(ExportFolder))
                {
                    Response.StatusCode    = 400;
                    Response.StatusMessage = "Bad Request";
                    Response.ContentType   = "text/plain";
                    await Response.Write("Export folder must be rooted. Relative paths are not accepted.");

                    await Response.SendResponse();

                    return;
                }

                if (!Directory.Exists(ExportFolder))
                {
                    Response.StatusCode    = 400;
                    Response.StatusMessage = "Bad Request";
                    Response.ContentType   = "text/plain";
                    await Response.Write("Export folder does not exist, or cannot be accessed or reached.");

                    await Response.SendResponse();

                    return;
                }

                try
                {
                    s = ExportFolder + Path.DirectorySeparatorChar + "test.txt";
                    File.WriteAllText(s, "test");
                    File.Delete(s);
                }
                catch (Exception)
                {
                    Response.StatusCode    = 400;
                    Response.StatusMessage = "Bad Request";
                    Response.ContentType   = "text/plain";
                    await Response.Write("Not allowed to write data to the export folder.");

                    await Response.SendResponse();

                    return;
                }
            }

            if (!string.IsNullOrEmpty(KeyFolder))
            {
                if (!Path.IsPathRooted(KeyFolder))
                {
                    Response.StatusCode    = 400;
                    Response.StatusMessage = "Bad Request";
                    Response.ContentType   = "text/plain";
                    await Response.Write("Key folder must be rooted. Relative paths are not accepted.");

                    await Response.SendResponse();

                    return;
                }

                if (!Directory.Exists(KeyFolder))
                {
                    Response.StatusCode    = 400;
                    Response.StatusMessage = "Bad Request";
                    Response.ContentType   = "text/plain";
                    await Response.Write("Key folder does not exist, or cannot be accessed or reached.");

                    await Response.SendResponse();

                    return;
                }

                try
                {
                    s = KeyFolder + Path.DirectorySeparatorChar + "test.txt";
                    File.WriteAllText(s, "test");
                    File.Delete(s);
                }
                catch (Exception)
                {
                    Response.StatusCode    = 400;
                    Response.StatusMessage = "Bad Request";
                    Response.ContentType   = "text/plain";
                    await Response.Write("Not allowed to write data to the key folder.");

                    await Response.SendResponse();

                    return;
                }
            }

            Export.ExportFolder    = ExportFolder;
            Export.ExportKeyFolder = KeyFolder;

            Response.StatusCode    = 200;
            Response.StatusMessage = "OK";
            await Response.SendResponse();
        }
Esempio n. 24
0
        /// <summary>
        /// Executes the POST method on the resource.
        /// </summary>
        /// <param name="Request">HTTP Request</param>
        /// <param name="Response">HTTP Response</param>
        /// <exception cref="HttpException">If an error occurred when processing the method.</exception>
        public async Task POST(HttpRequest Request, HttpResponse Response)
        {
            Gateway.AssertUserAuthenticated(Request);

            if (!Request.HasData)
            {
                throw new BadRequestException();
            }

            object Obj = Request.DecodeData();

            if (!(Obj is Dictionary <string, object> Parameters))
            {
                throw new BadRequestException();
            }

            if (!Parameters.TryGetValue("repair", out Obj) || !(Obj is bool Repair))
            {
                throw new BadRequestException();
            }

            if (!CanStartAnalyzeDB())
            {
                Response.StatusCode    = 409;
                Response.StatusMessage = "Conflict";
                Response.ContentType   = "text/plain";
                await Response.Write("Analysis is underway.");
            }

            string BasePath = Export.FullExportFolder;

            if (!Directory.Exists(BasePath))
            {
                Directory.CreateDirectory(BasePath);
            }

            BasePath += Path.DirectorySeparatorChar;

            string FullFileName = Path.Combine(BasePath, "DBReport " + DateTime.Now.ToString("yyyy-MM-dd HH_mm_ss"));

            FullFileName = StartExport.GetUniqueFileName(FullFileName, ".xml");
            FileStream fs = null;

            try
            {
                fs = new FileStream(FullFileName, FileMode.Create, FileAccess.Write);
                DateTime  Created   = File.GetCreationTime(FullFileName);
                XmlWriter XmlOutput = XmlWriter.Create(fs, XML.WriterSettings(true, false));
                string    FileName  = FullFileName.Substring(BasePath.Length);

                Task _ = Task.Run(() => DoAnalyze(FullFileName, FileName, Created, XmlOutput, fs, Repair));

                Response.StatusCode  = 200;
                Response.ContentType = "text/plain";
                await Response.Write(FileName);

                await Response.SendResponse();
            }
            catch (Exception ex)
            {
                if (!(fs is null))
                {
                    fs.Dispose();
                    File.Delete(FullFileName);
                }

                await Response.SendResponse(ex);
            }
        }
        /// <summary>
        /// Executes the POST method on the resource.
        /// </summary>
        /// <param name="Request">HTTP Request</param>
        /// <param name="Response">HTTP Response</param>
        /// <exception cref="HttpException">If an error occurred when processing the method.</exception>
        public async Task POST(HttpRequest Request, HttpResponse Response)
        {
            Gateway.AssertUserAuthenticated(Request);

            if (!Request.HasData)
            {
                throw new BadRequestException();
            }

            object Obj = Request.DecodeData();

            string[] P;

            if (!(Obj is string s))
            {
                throw new BadRequestException();
            }

            P = s.Split('\n');
            if (P.Length != 5)
            {
                throw new BadRequestException();
            }

            if (!CommonTypes.TryParse(P[0].Trim(), out bool AutomaticBackups))
            {
                throw new BadRequestException();
            }

            if (!TimeSpan.TryParse(P[1].Trim(), out TimeSpan BackupTime))
            {
                Response.StatusCode    = 400;
                Response.StatusMessage = "Bad Request";
                Response.ContentType   = "text/plain";
                await Response.Write("Backup time invalid.");

                await Response.SendResponse();

                return;
            }

            if (!int.TryParse(P[2].Trim(), out int KeepDays) || KeepDays < 0)
            {
                Response.StatusCode    = 400;
                Response.StatusMessage = "Bad Request";
                Response.ContentType   = "text/plain";
                await Response.Write("Invalid number of days specified.");

                await Response.SendResponse();

                return;
            }

            if (!int.TryParse(P[3].Trim(), out int KeepMonths) || KeepMonths < 0)
            {
                Response.StatusCode    = 400;
                Response.StatusMessage = "Bad Request";
                Response.ContentType   = "text/plain";
                await Response.Write("Invalid number of months specified.");

                await Response.SendResponse();

                return;
            }

            if (!int.TryParse(P[4].Trim(), out int KeepYears) || KeepYears < 0)
            {
                Response.StatusCode    = 400;
                Response.StatusMessage = "Bad Request";
                Response.ContentType   = "text/plain";
                await Response.Write("Invalid number of years specified.");

                await Response.SendResponse();

                return;
            }

            Export.AutomaticBackups = AutomaticBackups;
            Export.BackupTime       = BackupTime;
            Export.BackupKeepDays   = KeepDays;
            Export.BackupKeepMonths = KeepMonths;
            Export.BackupKeepYears  = KeepYears;

            Response.StatusCode    = 200;
            Response.StatusMessage = "OK";
            await Response.SendResponse();
        }
Esempio n. 26
0
        private Task GetGroups(HttpRequest Request, HttpResponse Response)
        {
            Gateway.AssertUserAuthenticated(Request, this.ConfigPrivilege);

            if (!Request.HasData)
            {
                throw new BadRequestException();
            }

            string StartsWith = Request.DecodeData() as string;

            if (string.IsNullOrEmpty(StartsWith))
            {
                throw new BadRequestException();
            }

            SuggestionEventArgs e = new SuggestionEventArgs(StartsWith.Trim());

            foreach (RosterItem Item in Gateway.XmppClient.Roster)
            {
                foreach (string Group in Item.Groups)
                {
                    e.AddSuggestion(Group);
                }
            }

            try
            {
                OnGetGroupSuggestions?.Invoke(this, e);
            }
            catch (Exception ex)
            {
                Log.Critical(ex);
            }

            StringBuilder sb = new StringBuilder();

            string[] Groups = e.ToArray();
            bool     First  = true;
            int      Nr     = 0;

            sb.Append("{\"groups\":[");

            foreach (string Group in Groups)
            {
                if (First)
                {
                    First = false;
                }
                else
                {
                    sb.Append(',');
                }

                sb.Append('"');
                sb.Append(CommonTypes.JsonStringEncode(Group));
                sb.Append('"');

                Nr++;
            }

            sb.Append("],\"count\":");
            sb.Append(Nr.ToString());
            sb.Append("}");

            Response.ContentType = "application/json";
            return(Response.Write(sb.ToString()));
        }
Esempio n. 27
0
        private Task UpdateContactGroups(HttpRequest Request, HttpResponse Response)
        {
            Gateway.AssertUserAuthenticated(Request, this.ConfigPrivilege);

            if (!Request.HasData)
            {
                throw new BadRequestException();
            }

            object Obj     = Request.DecodeData();
            string BareJid = Obj as string;

            if (string.IsNullOrEmpty(BareJid))
            {
                throw new BadRequestException();
            }

            XmppClient Client  = Gateway.XmppClient;
            RosterItem Contact = Client.GetRosterItem(BareJid);

            if (Contact is null)
            {
                throw new NotFoundException();
            }

            SortedDictionary <string, bool> Groups = new SortedDictionary <string, bool>(StringComparer.InvariantCultureIgnoreCase);

            string[] GroupsArray;
            int      i = 0;
            string   s;

            while (!string.IsNullOrEmpty(s = System.Web.HttpUtility.UrlDecode(Request.Header["X-Group-" + (++i).ToString()])))
            {
                Groups[s] = true;
            }

            if (Groups.Count > 0)
            {
                GroupsArray = new string[Groups.Count];
                Groups.Keys.CopyTo(GroupsArray, 0);
            }
            else
            {
                GroupsArray = new string[0];
            }

            StringBuilder sb    = new StringBuilder();
            bool          First = true;

            if (!(Groups is null))
            {
                foreach (string Group in GroupsArray)
                {
                    if (First)
                    {
                        First = false;
                    }
                    else
                    {
                        sb.Append(", ");
                    }

                    sb.Append(Group);
                }
            }

            Client.UpdateRosterItem(Contact.BareJid, Contact.Name, GroupsArray);
            Log.Informational("Contact groups updated.", Contact.BareJid, new KeyValuePair <string, object>("Groups", sb.ToString()));

            Response.ContentType = "text/plain";
            return(Response.Write("1"));
        }
Esempio n. 28
0
        /// <summary>
        /// Executes the POST method on the resource.
        /// </summary>
        /// <param name="Request">HTTP Request</param>
        /// <param name="Response">HTTP Response</param>
        /// <exception cref="HttpException">If an error occurred when processing the method.</exception>
        public async Task POST(HttpRequest Request, HttpResponse Response)
        {
            try
            {
                Gateway.AssertUserAuthenticated(Request, "Admin.Data.Backup");

                if (!Request.HasData ||
                    !(Request.DecodeData() is Dictionary <string, object> RequestObj) ||
                    !RequestObj.TryGetValue("TypeOfFile", out object Obj) || !(Obj is string TypeOfFile) ||
                    !RequestObj.TryGetValue("Database", out Obj) || !(Obj is bool Database) ||
                    !RequestObj.TryGetValue("Ledger", out Obj) || !(Obj is bool Ledger) ||
                    !RequestObj.TryGetValue("WebContent", out Obj) || !(Obj is bool WebContent) ||
                    !RequestObj.TryGetValue("OnlySelectedCollections", out Obj) || !(Obj is bool OnlySelectedCollections) ||
                    !RequestObj.TryGetValue("selectedCollections", out Obj) || !(Obj is Array SelectedCollections) ||
                    !RequestObj.TryGetValue("exportOnly", out Obj) || !(Obj is bool ExportOnly))
                {
                    throw new BadRequestException();
                }

                KeyValuePair <string, IExportFormat> Exporter = GetExporter(TypeOfFile, OnlySelectedCollections, SelectedCollections);

                lock (synchObject)
                {
                    if (exporting)
                    {
                        Response.StatusCode    = 409;
                        Response.StatusMessage = "Conflict";
                        Response.ContentType   = "text/plain";
                        Response.Write("Export is underway.");
                        return;
                    }
                    else
                    {
                        exporting = true;
                    }
                }

                if (!ExportOnly)
                {
                    Export.ExportType       = TypeOfFile;
                    Export.ExportDatabase   = Database;
                    Export.ExportLedger     = Ledger;
                    Export.ExportWebContent = WebContent;
                }

                List <string> Folders = new List <string>();

                foreach (Export.FolderCategory FolderCategory in Export.GetRegisteredFolders())
                {
                    if (RequestObj.TryGetValue(FolderCategory.CategoryId, out Obj) && Obj is bool b)
                    {
                        if (!ExportOnly)
                        {
                            await Export.SetExportFolderAsync(FolderCategory.CategoryId, b);
                        }

                        if (b)
                        {
                            Folders.AddRange(FolderCategory.Folders);
                        }
                    }
                }

                Task _ = DoExport(Exporter.Value, Database, Ledger, WebContent, Folders.ToArray());

                Response.StatusCode  = 200;
                Response.ContentType = "text/plain";
                await Response.Write(Exporter.Key);
            }
            catch (Exception ex)
            {
                await Response.SendResponse(ex);
            }
        }
Esempio n. 29
0
        private void ConnectToHost(HttpRequest Request, HttpResponse Response)
        {
            Gateway.AssertUserAuthenticated(Request);

            if (!Request.HasData)
            {
                throw new BadRequestException();
            }

            object Obj = Request.DecodeData();

            if (!(Obj is Dictionary <string, object> Parameters))
            {
                throw new BadRequestException();
            }

            if (!Parameters.TryGetValue("host", out Obj) || !(Obj is string HostName))
            {
                throw new BadRequestException();
            }

            string TabID = Request.Header["X-TabID"];

            if (string.IsNullOrEmpty(TabID))
            {
                throw new BadRequestException();
            }

            if (!Parameters.TryGetValue("port", out Obj) || !(Obj is int Port) || Port < 1 || Port > 65535)
            {
                throw new BadRequestException();
            }

            if (!Parameters.TryGetValue("boshUrl", out Obj) || !(Obj is string BoshUrl))
            {
                throw new BadRequestException();
            }

            if (!Parameters.TryGetValue("wsUrl", out Obj) || !(Obj is string WsUrl))
            {
                throw new BadRequestException();
            }

            if (!Parameters.TryGetValue("customBinding", out Obj) || !(Obj is bool CustomBinding))
            {
                throw new BadRequestException();
            }

            if (!Parameters.TryGetValue("trustServer", out Obj) || !(Obj is bool TrustServer))
            {
                throw new BadRequestException();
            }

            if (!Parameters.TryGetValue("insecureMechanisms", out Obj) || !(Obj is bool InsecureMechanisms))
            {
                throw new BadRequestException();
            }

            if (!Parameters.TryGetValue("storePassword", out Obj) || !(Obj is bool StorePasswordInsteadOfHash))
            {
                throw new BadRequestException();
            }

            if (!Parameters.TryGetValue("sniffer", out Obj) || !(Obj is bool Sniffer))
            {
                throw new BadRequestException();
            }

            if (!Parameters.TryGetValue("transport", out Obj) || !(Obj is string s2) || !Enum.TryParse <XmppTransportMethod>(s2, out XmppTransportMethod Method))
            {
                throw new BadRequestException();
            }

            if (!Parameters.TryGetValue("account", out Obj) || !(Obj is string Account))
            {
                throw new BadRequestException();
            }

            if (!Parameters.TryGetValue("password", out Obj) || !(Obj is string Password))
            {
                throw new BadRequestException();
            }

            if (!Parameters.TryGetValue("createAccount", out Obj) || !(Obj is bool CreateAccount))
            {
                throw new BadRequestException();
            }

            if (!Parameters.TryGetValue("accountName", out Obj) || !(Obj is string AccountName))
            {
                throw new BadRequestException();
            }

            this.host                       = HostName;
            this.port                       = Port;
            this.boshUrl                    = BoshUrl.Trim();
            this.wsUrl                      = WsUrl.Trim();
            this.customBinding              = CustomBinding;
            this.trustServer                = TrustServer;
            this.allowInsecureMechanisms    = InsecureMechanisms;
            this.storePasswordInsteadOfHash = StorePasswordInsteadOfHash;
            this.sniffer                    = Sniffer;
            this.transportMethod            = Method;
            this.account                    = Account;
            this.createAccount              = CreateAccount;
            this.accountHumanReadableName   = AccountName;

            if (this.password != Password)
            {
                this.password     = Password;
                this.passwordType = string.Empty;
            }

            if (this.client != null)
            {
                this.client.Dispose();
                this.client = null;
            }

            Response.StatusCode = 200;

            this.Connect(TabID);
        }