Beispiel #1
0
        async Task HandleClientConnections(HttpListener listener)
        {
            var context = await listener.GetContextAsync().ConfigureAwait(false);

            var action = GetSiteAction(ref context);

            var method   = (context.Request.HttpMethod == "POST") ? HTTPMethod.POST : HTTPMethod.GET;
            var url      = context.Request.Url.PathAndQuery.Split('?');
            var path     = GetContentType((url[0] == "/") ? "/index.html" : url[0], ref context);
            var formdata = GetPostData((url.Length > 1 && method == HTTPMethod.GET) ?
                                       string.Format("?{0}", url[1]) : path, ref context, method);

            var target = GetRequestTarget(ref path, ref context);

            var provider = GetRequestedProvider(ref path);
            var reqType  = GetRequestType(ref context, ref provider);

            switch (target)
            {
            case RequestTarget.Site:
            case RequestTarget.Provider:
                var directEvArgs = new DataReceivedEventArgs();
                directEvArgs.Action      = action;
                directEvArgs.Context     = context;
                directEvArgs.Method      = method;
                directEvArgs.UserAgent   = context.Request.Headers["UAgent"];
                directEvArgs.Params      = formdata;
                directEvArgs.Provider    = provider;
                directEvArgs.Path        = path.Split('?')[0];
                directEvArgs.RequestType = reqType;
                directEvArgs.Target      = target;

                DataReceived?.Invoke(this, directEvArgs);
                break;

            case RequestTarget.File:
                var filePath = GetContentType(Filesystem.Combine(docroot, path), ref context);
                var data     = SendErrorDocument(404, string.Format("Not Found ({0})!", filePath), ref context);

                using (var fs = new Filesystem(docroot))
                {
                    if (fs.Exists(filePath))
                    {
                        Array.Clear(data, 0, data.Length);
                        data = fs.Read(filePath).Result;

                        context.Response.StatusCode        = 200;
                        context.Response.StatusDescription = "OK";
                    }
                }

                Send(ref data, ref context);
                break;

            default:
                break;
            }

            await HandleClientConnections(listener).ConfigureAwait(false);
        }
Beispiel #2
0
        public SQLDatabase(string database)
        {
            if (string.IsNullOrEmpty(database))
            {
                return;
            }

            var dataBase = Filesystem.Combine(Environment.CurrentDirectory, database);

            sqlConn = new SQLiteConnection(string.Format("Data Source={0};Version=3;", dataBase));

            Open();
        }
Beispiel #3
0
        public static string ReadTemplate(ref Filesystem fs, string name)
        {
            var tpl_path = string.Format("templates/{0}.tpl", name.Replace("-", "_"));

            if (!fs.Exists(tpl_path))
            {
                return(string.Format("<p class=\"exclaim\">Dispatcher (Template file for \"{0}\" was not found!</p>", name));
            }
            else
            {
                var output = fs.Read(tpl_path);
                return(Encoding.UTF8.GetString(output, 0, output.Length));
            }
        }
Beispiel #4
0
        public WebServer(Guid id, RequestTarget type, string title, ref Filesystem fs, int port, string hostname)
        {
            this.instance = id;
            this.fs       = fs;
            this.title    = title;
            this.type     = type;
            this.hostname = hostname;
            this.passKey  = Guid.NewGuid();

            listener = new HttpListener
            {
                IgnoreWriteExceptions = true,
                AuthenticationSchemes = AuthenticationSchemes.Basic | AuthenticationSchemes.Anonymous
            };

            listener.Prefixes.Add(string.Format("http://*:{0}/",
                                                type == RequestTarget.Site ? port : (port + 1)));
        }
Beispiel #5
0
        public void Bootstrap()
        {
            var _fs = new Filesystem(Directory.GetCurrentDirectory());

            Console.WriteLine("[I] Bootstrap...");
            AccessProvider.ProviderResponse     += Handle_Provider_Event;
            ServerProvider.ProviderResponse     += Handle_Provider_Event;
            ClientProvider.ProviderResponse     += Handle_Provider_Event;
            UserProvider.ProviderResponse       += Handle_Provider_Event;
            NewsProvider.ProviderResponse       += Handle_Provider_Event;
            NavigationProvider.ProviderResponse += Handle_Provider_Event;

            if (!Directory.Exists(Path.Combine(_fs.Root, "Providers")))
            {
                Directory.CreateDirectory(Path.Combine(_fs.Root, "Providers"));
                Console.WriteLine("[I] Provider installation needed..., Bootstrapping them...");
            }

            AccessProvider.Add(Guid.NewGuid(), new GroupEntry <Guid>()
            {
                Active   = true,
                Name     = "System",
                Level    = ulong.MaxValue,
                Locked   = true,
                Provider = AccessProvider.Name,
            });

            AccessProvider.Add(Guid.NewGuid(), new GroupEntry <Guid>()
            {
                Active   = true,
                Name     = "Server-Administratoren",
                Level    = byte.MaxValue,
                Locked   = true,
                Provider = AccessProvider.Name,
            });

            AccessProvider.Add(Guid.NewGuid(), new GroupEntry <Guid>()
            {
                Active   = true,
                Name     = "Server-Operatoren",
                Level    = 250,
                Locked   = true,
                Provider = AccessProvider.Name,
            });

            AccessProvider.Add(Guid.NewGuid(), new GroupEntry <Guid>()
            {
                Active   = true,
                Name     = "Seiten-Administroren",
                Level    = 245,
                Locked   = true,
                Provider = AccessProvider.Name,
            });

            AccessProvider.Add(Guid.NewGuid(), new GroupEntry <Guid>()
            {
                Active   = true,
                Name     = "Seiten-Operatoren",
                Level    = 240,
                Locked   = true,
                Provider = AccessProvider.Name,
            });

            AccessProvider.Add(Guid.NewGuid(), new GroupEntry <Guid>()
            {
                Active   = true,
                Name     = "News-Administratoren",
                Level    = 235,
                Locked   = true,
                Provider = AccessProvider.Name,
            });

            AccessProvider.Add(Guid.NewGuid(), new GroupEntry <Guid>()
            {
                Active   = true,
                Name     = "News-Operatoren",
                Level    = 230,
                Locked   = true,
                Provider = AccessProvider.Name,
            });

            AccessProvider.Add(Guid.NewGuid(), new GroupEntry <Guid>()
            {
                Active   = true,
                Name     = "Sendeplan-Administratoren",
                Level    = 225,
                Locked   = true,
                Provider = AccessProvider.Name,
            });

            AccessProvider.Add(Guid.NewGuid(), new GroupEntry <Guid>()
            {
                Active   = true,
                Name     = "Sendeplan-Operatoren",
                Level    = 220,
                Locked   = true,
                Provider = AccessProvider.Name,
            });

            AccessProvider.Add(Guid.NewGuid(), new GroupEntry <Guid>()
            {
                Active   = true,
                Name     = "Stream-Administratoren",
                Level    = 215,
                Locked   = true,
                Provider = AccessProvider.Name,
            });

            AccessProvider.Add(Guid.NewGuid(), new GroupEntry <Guid>()
            {
                Active   = true,
                Name     = "Stream-Operatoren",
                Level    = 210,
                Locked   = true,
                Provider = AccessProvider.Name,
            });

            AccessProvider.Add(Guid.NewGuid(), new GroupEntry <Guid>()
            {
                Active   = true,
                Name     = "Seiten-Mitglied",
                Level    = 1,
                Locked   = true,
                Provider = AccessProvider.Name,
            });

            AccessProvider.Add(Guid.NewGuid(), new GroupEntry <Guid>()
            {
                Active   = true,
                Name     = "Unregistriert",
                Level    = byte.MinValue,
                Locked   = true,
                Provider = AccessProvider.Name,
            });

            #region "News Provider - Installation"


            var news_user = Guid.Empty;
            var xmlDoc    = new XmlDocument();
            xmlDoc.Load(NewsProvider.InstallScript);
            var newsEntries = xmlDoc.SelectNodes("Namiono/Install/Users/User");

            for (var i = 0; i < newsEntries.Count; i++)
            {
                var res_level = ulong.MinValue;


                var user = new UserEntry <Guid>
                {
                    Id                                 = newsEntries[i].Attributes["Id"] == null?Guid.NewGuid() : Guid.Parse(newsEntries[i].Attributes["Id"].Value),
                                             Name      = newsEntries[i].Attributes["Name"].Value,
                                             Service   = bool.Parse(newsEntries[i].Attributes["Service"].Value == "0" ? "false" : "true"),
                                             Moderator = bool.Parse(newsEntries[i].Attributes["Moderator"].Value == "0" ? "false" : "true"),
                                             Locked    = bool.Parse(newsEntries[i].Attributes["Locked"].Value == "0" ? "false" : "true"),
                                             Password  = MD5.GetMD5Hash(newsEntries[i].Attributes["Password"].Value),
                                             Provider  = UserProvider.Name
                };

                if (newsEntries[i].Attributes["Level"] != null)
                {
                    ulong.TryParse(newsEntries[i].Attributes["Level"].Value, out res_level);
                    user.Level = res_level;
                }

                news_user = user.Id;

                UserProvider.Add(user.Id, user);
            }

            newsEntries = xmlDoc.SelectNodes("Namiono/Install/Entries/Entry");

            for (var i = 0; i < newsEntries.Count; i++)
            {
                var res_level = ulong.MinValue;

                var news = new NewsEntry <Guid>
                {
                    Name      = newsEntries[i].Attributes["Name"].Value,
                    Service   = bool.Parse(newsEntries[i].Attributes["Service"].Value == "0" ? "false" : "true"),
                    Moderator = bool.Parse(newsEntries[i].Attributes["Moderator"].Value == "0" ? "false" : "true"),
                    Locked    = bool.Parse(newsEntries[i].Attributes["Locked"].Value == "0" ? "false" : "true"),
                    OutPut    = newsEntries[i].Attributes["Output"].Value.Replace("[[NL]]", "<br />"),
                    Url       = newsEntries[i].Attributes["Url"].Value,
                    Author    = news_user
                };

                if (newsEntries[i].Attributes["Level"] != null)
                {
                    ulong.TryParse(newsEntries[i].Attributes["Level"].Value, out res_level);
                    news.Level = res_level;
                }


                NewsProvider.Add(Guid.NewGuid(), news);
            }

            #endregion

            #region "Navigation Provider - Installation"
            xmlDoc.Load(NavigationProvider.InstallScript);

            var navEntries = xmlDoc.SelectNodes("Namiono/Install/Entries/Entry");

            for (var i = 0; i < navEntries.Count; i++)
            {
                var res_level = ulong.MinValue;

                var nav = new NavigationEntry <Guid>
                {
                    Name      = navEntries[i].Attributes["Name"].Value,
                    Service   = bool.Parse(navEntries[i].Attributes["Service"].Value == "0" ? "false" : "true"),
                    Moderator = bool.Parse(navEntries[i].Attributes["Moderator"].Value == "0" ? "false" : "true"),
                    Locked    = bool.Parse(navEntries[i].Attributes["Locked"].Value == "0" ? "false" : "true"),
                    OutPut    = navEntries[i].Attributes["Output"].Value.Replace("[[NL]]", "<br />"),
                    Url       = navEntries[i].Attributes["Url"].Value,
                    Author    = Guid.Empty
                };

                if (navEntries[i].Attributes["Level"] != null)
                {
                    ulong.TryParse(navEntries[i].Attributes["Level"].Value, out res_level);
                    nav.Level = res_level;
                }


                NavigationProvider.Add(Guid.NewGuid(), nav);
            }


            NavigationProvider.Add(Guid.NewGuid(), new NavigationEntry <Guid>()
            {
                Name = "Mitglieder", Active = true, Locked = false, Level = 1, Frame = "#content", Provider = UserProvider.Name, Action = "show"
            });
            NavigationProvider.Add(Guid.NewGuid(), new NavigationEntry <Guid>()
            {
                Name = "News", Active = true, Locked = false, Level = 1, Frame = "#content", Provider = NewsProvider.Name, Action = "show"
            });

            #endregion
            AccessProvider.Bootstrap();
            ServerProvider.Bootstrap();
            ClientProvider.Bootstrap();
            UserProvider.Bootstrap();
            NewsProvider.Bootstrap();
            NavigationProvider.Bootstrap();



            Console.WriteLine("[I] Starting ...");
        }
Beispiel #6
0
        public static async Task <Dictionary <string, string> > GetPostData(Filesystem fs,
                                                                            string path, HttpListenerContext context, HTTPMethod method)
        {
            var formdata = new Dictionary <string, string>();

            switch (method)
            {
            case HTTPMethod.POST:
                var encoding = context.Request.ContentEncoding;
                var ctype    = context.Request.ContentType;
                var line     = string.Empty;

                using (var reader = new StreamReader(context.Request.InputStream, encoding))
                    line = reader.ReadToEnd();

                if (string.IsNullOrEmpty(line))
                {
                    return(formdata);
                }

                if (!string.IsNullOrEmpty(ctype))
                {
                    if (ctype.Split(';')[0] != "application/x-www-form-urlencoded")
                    {
                        var boundary = ctype.Split('=')[1];

                        if (string.IsNullOrEmpty(line))
                        {
                            return(null);
                        }

                        var start = line.IndexOf(boundary) + (boundary.Length + 2);
                        var end   = line.LastIndexOf(boundary) + boundary.Length;
                        line = line.Substring(start, end - start);
                        var formparts = new List <string>();

                        while (line.Contains(boundary))
                        {
                            if (line.StartsWith("Content-Disposition:"))
                            {
                                start = line.IndexOf("Content-Disposition: form-data;") +
                                        "Content-Disposition: form-data;".Length;

                                end = line.IndexOf(boundary);
                                formparts.Add(line.Substring(start, end - start).TrimStart());
                                line = line.Remove(0, end);
                            }

                            if (line.StartsWith(boundary))
                            {
                                if (line.Length > boundary.Length + 2)
                                {
                                    line = line.Remove(0, boundary.Length + 2);
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }

                        foreach (var item in formparts)
                        {
                            if (item.Contains("filename=\""))
                            {
                                var posttag = item.Substring(0, item.IndexOf(";"));
                                if (string.IsNullOrEmpty(posttag))
                                {
                                    continue;
                                }

                                var data = item;
                                start = data.IndexOf("filename=\"") + "filename=\"".Length;
                                data  = data.Remove(0, start);
                                end   = data.IndexOf("\"");

                                var filename = data.Substring(0, end);
                                if (string.IsNullOrEmpty(filename))
                                {
                                    continue;
                                }

                                if (filename.Contains("\\") || filename.Contains("/"))
                                {
                                    var parts = filename.Split(filename.Contains("\\") ? '\\' : '/');
                                    filename = parts[parts.Length - 1];
                                }

                                start = data.IndexOf("Content-Type: ");
                                data  = data.Remove(0, start);
                                end   = data.IndexOf("\r\n");

                                var cType = data.Substring(0, end + 2);
                                data = data.Remove(0, end + 2);

                                var filedata = context.Request.ContentEncoding
                                               .GetBytes(data.Substring(2, data.IndexOf("\r\n--")));

                                if (filedata.Length != 0)
                                {
                                    var uploadpath = Filesystem.Combine(path, filename);

                                    try
                                    {
                                        await fs.Write(uploadpath, filedata);

                                        if (!formdata.ContainsKey(posttag))
                                        {
                                            formdata.Add(posttag, uploadpath);
                                        }
                                    }
                                    catch
                                    {
                                        continue;
                                    }
                                }
#if DEBUG
                                else
                                {
                                    throw new Exception(string.Format("Die hochgeladene Datei \"{0}\", enthält keine Daten (leer?)!", filename));
                                }
#endif
                            }
                            else
                            {
                                var x = item.Replace("\r\n--", string.Empty).Replace("name=\"",
                                                                                     string.Empty).Replace("\"", string.Empty).Replace("\r\n\r\n", "|").Split('|');
                                x[0] = x[0].Replace(" file", string.Empty);

                                if (!formdata.ContainsKey(x[0]))
                                {
                                    formdata.Add(x[0].Replace("\"", string.Empty), x[1].Replace("\"", string.Empty));
                                }
                            }
                        }

                        formparts.Clear();
                        formparts = null;
                    }
                    else
                    {
                        var tmp = line.Split('&');
                        for (var i = 0; i < tmp.Length; i++)
                        {
                            if (tmp[i].Contains("="))
                            {
                                var p = tmp[i].Split('=');
                                if (!formdata.ContainsKey(p[0]))
                                {
                                    formdata.Add(p[0].Replace("\"", string.Empty), HttpUtility.UrlDecode(p[1]).Replace("\"", string.Empty));
                                }
                            }
                        }
                    }
                }

                break;

            case HTTPMethod.GET:
                if (path.Contains("?") && path.Contains("&") && path.Contains("="))
                {
                    var get_params = HttpUtility.UrlDecode(path).Split('?')[1].Split('&');
                    for (var i = 0; i < get_params.Length; i++)
                    {
                        if (get_params[i].Contains("="))
                        {
                            var p = get_params[i].Split('=');
                            if (!formdata.ContainsKey(p[0]))
                            {
                                formdata.Add(p[0], p[1]);
                            }
                        }
                    }
                }

                break;

            default:
                break;
            }

            return(formdata);
        }
Beispiel #7
0
        public WebSite(ref Common common, ref SQLDatabase <T> db, string name, string title, ushort port, Realm realm, string hostname, string design = "default")
        {
            this.title  = title;
            this.db     = db;
            this.common = common;
            this.design = design;
            this.realm  = realm;

            Webservers = new Dictionary <Guid, WebServer>();
            fs         = new Filesystem(Path.Combine(Environment.CurrentDirectory, string.Format("{0}_website", name)));

            foreach (var type in new[] { WebServer.RequestTarget.Site, WebServer.RequestTarget.api })
            {
                var _guid = Guid.NewGuid();

                var ws = new WebServer(_guid, type, this.title, ref fs, port, hostname);
                ws.DirectRequestReceived += (sender, e) =>
                {
                    var p = e.Path.Split('.')[0].ToLower();
                    if (p.StartsWith("/"))
                    {
                        p = p.Remove(0, 1);
                    }

                    var userid = Get_UserID_From_Cookie(ref e.Context);

                    foreach (var item in e.Params)
                    {
                        Console.WriteLine("{0} : {1} ", item.Key, e.Params[item.Key]);
                    }

                    switch (e.Target)
                    {
                    case WebServer.RequestTarget.api:
                        if (e.Context.User.Identity.IsAuthenticated)
                        {
                            var identity = (HttpListenerBasicIdentity)e.Context.User.Identity;
                            Console.WriteLine(identity.Name);
                            Console.WriteLine(identity.Password);
                        }

                        if (e.Context.User.Identity.IsAuthenticated)
                        {
                            Handle_Provider_Request(ref this.common, ref e.Provider, ref e.Action, ref e.Context, ref userid, ref e.Params, e.Instance);
                        }
                        else
                        {
                            e.Context.Response.StatusCode        = 401;
                            e.Context.Response.StatusDescription = "Network Authentication Required!";

                            var data = new byte[0];
                            Webservers[e.Instance].Send(ref data, ref e.Context);
                        }
                        break;

                    case WebServer.RequestTarget.Site:
                        Handle_Site_Request(ref userid, ref e.Context, e.Instance, ref e.Params);
                        break;
                    }
                };

                Webservers.Add(_guid, ws);
            }
        }