Пример #1
0
        /// <summary>
        /// Validates that the webrequest meets minimum requirements. This will be called when WebRequest method is called.
        /// </summary>
        public void Validate()
        {
            if (string.IsNullOrWhiteSpace(Url))
            {
                throw new Exception("Url is empty");
            }

            if (!Uri.IsWellFormedUriString(Url, UriKind.RelativeOrAbsolute))
            {
                throw new Exception("Url is not well formed");
            }

            if (RawBody?.Length > 1048576)
            {
                throw new Exception("RawBody cannot be larger than 10mb");
            }

            if (Headers?.ContainsKey("Content-Type") == true)
            {
                throw new Exception($"Please use {nameof(ContentType)} property rather than adding Content-Type as a seperate.");
            }
        }
Пример #2
0
        private async Task <IEnumerable <KeyValuePair <string, string> > > HandleSearch(Headers sparams, User user, string deviceId)
        {
            var searchCriteria = new SearchCriteria(sparams.GetValueOrDefault("SearchCriteria", ""));
            var sortCriteria   = new SortCriteria(sparams.GetValueOrDefault("SortCriteria", ""));
            var filter         = new Filter(sparams.GetValueOrDefault("Filter", "*"));

            // sort example: dc:title, dc:date

            int?requested = 0;
            int?start     = 0;

            int requestedVal;

            if (sparams.ContainsKey("RequestedCount") && int.TryParse(sparams["RequestedCount"], out requestedVal) && requestedVal > 0)
            {
                requested = requestedVal;
            }

            int startVal;

            if (sparams.ContainsKey("StartingIndex") && int.TryParse(sparams["StartingIndex"], out startVal) && startVal > 0)
            {
                start = startVal;
            }

            //var root = GetItem(id) as IMediaFolder;
            var result = new XmlDocument();

            var didl = result.CreateElement(string.Empty, "DIDL-Lite", NS_DIDL);

            didl.SetAttribute("xmlns:dc", NS_DC);
            didl.SetAttribute("xmlns:dlna", NS_DLNA);
            didl.SetAttribute("xmlns:upnp", NS_UPNP);

            foreach (var att in _profile.XmlRootAttributes)
            {
                didl.SetAttribute(att.Name, att.Value);
            }

            result.AppendChild(didl);

            var folder = (Folder)GetItemFromObjectId(sparams["ContainerID"], user);

            var childrenResult = (await GetChildrenSorted(folder, user, searchCriteria, sortCriteria, start, requested).ConfigureAwait(false));

            var totalCount = childrenResult.TotalRecordCount;

            var provided = childrenResult.Items.Length;

            foreach (var i in childrenResult.Items)
            {
                if (i.IsFolder)
                {
                    var f          = (Folder)i;
                    var childCount = (await GetChildrenSorted(f, user, searchCriteria, sortCriteria, null, 0).ConfigureAwait(false))
                                     .TotalRecordCount;

                    result.DocumentElement.AppendChild(_didlBuilder.GetFolderElement(result, f, childCount, filter));
                }
                else
                {
                    result.DocumentElement.AppendChild(_didlBuilder.GetItemElement(result, i, deviceId, filter));
                }
            }

            var resXML = result.OuterXml;

            return(new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("Result", resXML),
                new KeyValuePair <string, string>("NumberReturned", provided.ToString(_usCulture)),
                new KeyValuePair <string, string>("TotalMatches", totalCount.ToString(_usCulture)),
                new KeyValuePair <string, string>("UpdateID", _systemUpdateId.ToString(_usCulture))
            });
        }
Пример #3
0
        public Response GetResponse(int port = 80, int maxredirect = 10)
        {
            string        content = Method.ToString() + " " + Uri.PathAndQuery + " HTTP/1.1\n";
            List <string> headers = new List <string>();

            if (!Headers.ContainsKey("User-Agent"))
            {
                Headers.Add("User-Agent", UserAgent);
            }
            else
            {
                Headers.Remove("User-Agent");
                Headers.Add("User-Agent", UserAgent);
            }
            foreach (var p in Headers)
            {
                headers.Add(p.Key + ":" + p.Value + '\n');
            }
            for (int i = 0; i < Cookies.Count; i++)
            {
                headers.Add("Cookie:" + Cookies[i] + '\n');
            }
            if (referal != null)
            {
                headers.Add("Referer:" + referal + '\n');
            }
            headers.Sort(StringComparer.Create(System.Threading.Thread.CurrentThread.CurrentCulture, true));
            content += "Host:" + Uri.DnsSafeHost + '\n';
            for (int i = 0; i < headers.Count; i++)
            {
                content += headers[i];
            }
            if (((POSTContent ?? "") != "") && (Method == HttpRequestMethod.POST))
            {
                content += "Content-Length:" + POSTContent.Length + '\n';
                content += '\n' + POSTContent ?? "";
            }
            else
            {
                content += "\n\n";
            }
            System.Net.Sockets.TcpClient client;
            client = new System.Net.Sockets.TcpClient();
            client.Connect(Uri.DnsSafeHost, port);
            var buf = Encoding.Default.GetBytes(content);

            client.GetStream().Write(buf, 0, buf.Length);
            var         stream     = client.GetStream();
            List <byte> response   = new List <byte>();
            string      respHeader = "";
            int         b          = 0;
            bool        endHeader  = false;

            while ((b = stream.ReadByte()) != -1)
            {
                if (b == '\n')
                {
                    if ((response.Count == 0) || ((response.Count == 1) && (response[0] == 13)))
                    {
                        if (!endHeader)
                        {
                            endHeader = true;
                            response.Clear();
                            continue;
                        }
                    }
                    response.Add((byte)b);
                    if (!endHeader)
                    {
                        respHeader += Encoding.Default.GetString(response.ToArray());
                        response.Clear();
                    }
                }
                else
                {
                    response.Add((byte)b);
                }
            }
            if (headers.Contains("Connection"))
            {
                if (Headers["Connection"] == "Close")
                {
                    client.Close();
                }
            }
            else
            {
                client.Close();
            }
            string contentType = respHeader.Substring(respHeader.IndexOf("Content-Type:"));

            contentType = contentType.Substring(13, contentType.IndexOf('\n') - 13).Trim();
            string responseContent = "";

            if (contentType.IndexOf("text/") != -1)
            {
                string charset = (contentType.IndexOf("charset") != -1) ? contentType.Substring(contentType.IndexOf("charset") + 8) : "utf-8";
                if (charset.IndexOf(";") != -1)
                {
                    charset = charset.Substring(0, charset.IndexOf(';'));
                }
                responseContent = Encoding.GetEncoding(charset).GetString(response.ToArray());
            }
            if ((AutoRedirect) && (maxredirect > 0))
            {
                string result = respHeader.Substring(0, respHeader.IndexOf('\n')).Trim();
                int    sci    = respHeader.IndexOf("\nSet-Cookie: ");
                while (sci != -1)
                {
                    int    eqi  = respHeader.IndexOf('=', sci);
                    string name = respHeader.Substring(sci + 13, eqi - sci - 13);

                    string value = respHeader.Substring(eqi + 1, respHeader.IndexOf(';', sci) - eqi - 1);
                    if (value != "deleted")
                    {
                        if (Cookies.FindIndex((x) => { return(x.Name == name); }) == -1)
                        {
                            Cookies.Add(new Cookie()
                            {
                                Name = name, Value = value
                            });
                        }
                        else
                        {
                            Cookies.Find((x) => { return(x.Name == name); }).Value = value;
                        }
                    }
                    else
                    {
                        int index = Cookies.FindIndex((x) => { return(name == x.Name); });
                        if (index != -1)
                        {
                            Cookies.RemoveAt(index);
                        }
                    }
                    sci = respHeader.IndexOf("\nSet-Cookie: ", sci + 1);
                }
                if (result == "HTTP/1.1 302 Found")
                {
                    string redurl = respHeader.Substring(respHeader.IndexOf("\nLocation:"));
                    redurl = redurl.Substring(redurl.IndexOf(':') + 1);
                    redurl = redurl.Substring(0, redurl.IndexOf('\n')).Trim();
                    if (redurl == "/")
                    {
                        redurl = Uri.Scheme + "://" + Uri.Host + "/";
                    }
                    Uri reuri = new Uri(redurl);
                    return((new HttpRequest()
                    {
                        Uri = reuri, UserAgent = UserAgent, AutoRedirect = true, Headers = Headers, Cookies = Cookies, referal = Uri.DnsSafeHost + Uri.PathAndQuery
                    }).GetResponse(port, maxredirect - 1));
                }
            }
            return(new Response(respHeader, responseContent, Cookies.ToArray()));
        }
Пример #4
0
        internal void LoadPost(WebServerClient client)
        {
            if (!Headers.TryGetValue("content-type", out string contentType))
            {
                return;
            }

            string contentTypeShort = contentType.BeforeFirst(';').Trim().ToLower();

            switch (contentTypeShort)
            {
            case "application/x-www-form-urlencoded": break;

            case "application/octet-stream": break;

            case "multipart/form-data": break;

            default: throw new WebServerException(WebError.UnknownContent, 0, "Unknown content type!");
            }
            int size = 0;

            {
                if (Headers.TryGetValue("content-length", out string sizeStr))
                {
                    int.TryParse(sizeStr, out size);
                }
            }

            // if (size > 20 * 1024 * 1024) throw new CaveWebException(CaveWebError.MaximumSizeExceeded, "Maximum transfer size exceeded!");
            if (Headers.ContainsKey("expect"))
            {
                if (Headers["expect"].Contains("100-continue"))
                {
                    string @continue = $"{Protocol} {(int)HttpStatusCode.Continue} {HttpStatusCode.Continue}";
                    if (Server.VerboseMode)
                    {
                        Trace.TraceInformation($"Request {ID} {@continue}");
                    }

                    client.Writer.WriteLine(@continue);
                    client.Writer.WriteLine();
                }
            }
            byte[] data = null;
            if (Headers.TryGetValue("transfer-encoding", out string transferEncoding))
            {
                switch (transferEncoding.ToLower().Trim())
                {
                case "chunked":
                    var buf = new FifoBuffer();
                    while (true)
                    {
                        string line      = client.Reader.ReadLine();
                        int    chunkSize = Convert.ToInt32(line, 16);
                        if (chunkSize == 0)
                        {
                            break;
                        }

                        byte[] chunkData = client.Reader.ReadBytes(chunkSize);
                        buf.Enqueue(chunkData);
                        client.Reader.ReadLine();
                    }
                    data = buf.ToArray();
                    break;

                default:
                    throw new WebServerException(WebError.UnknownContent, 0, string.Format("Unknown transfer encoding {0}", transferEncoding));
                }
            }
            switch (contentTypeShort)
            {
            case "application/x-www-form-urlencoded":
                if (data != null)
                {
                    DecodeUrl(Encoding.ASCII.GetString(data).Replace('+', ' '), true);
                }
                else
                {
                    DecodeUrl(Encoding.ASCII.GetString(client.Reader.ReadBytes(size)).Replace('+', ' '), true);
                }
                break;

            case "application/octet-stream":
                if (data != null)
                {
                    SetPostData(data);
                }
                else
                {
                    SetPostData(client.Reader.ReadBytes(size));
                }
                break;

            case "multipart/form-data":
                if (data != null)
                {
                    DecodeMultiPartFormData(contentType, new DataReader(new MemoryStream(data), newLineMode: NewLineMode.CRLF));
                }
                else
                {
                    DecodeMultiPartFormData(contentType, client.Reader);
                }
                break;

            default: throw new WebServerException(WebError.UnknownContent, 0, "Unknown content type!");
            }
        }
Пример #5
0
        private async Task <IEnumerable <KeyValuePair <string, string> > > HandleBrowse(Headers sparams, User user, string deviceId)
        {
            var id           = sparams["ObjectID"];
            var flag         = sparams["BrowseFlag"];
            var filter       = new Filter(sparams.GetValueOrDefault("Filter", "*"));
            var sortCriteria = new SortCriteria(sparams.GetValueOrDefault("SortCriteria", ""));

            var provided = 0;

            // Default to null instead of 0
            // Upnp inspector sends 0 as requestedCount when it wants everything
            int?requestedCount = null;
            int?start          = 0;

            int requestedVal;

            if (sparams.ContainsKey("RequestedCount") && int.TryParse(sparams["RequestedCount"], out requestedVal) && requestedVal > 0)
            {
                requestedCount = requestedVal;
            }

            int startVal;

            if (sparams.ContainsKey("StartingIndex") && int.TryParse(sparams["StartingIndex"], out startVal) && startVal > 0)
            {
                start = startVal;
            }

            //var root = GetItem(id) as IMediaFolder;
            var result = new XmlDocument();

            var didl = result.CreateElement(string.Empty, "DIDL-Lite", NS_DIDL);

            didl.SetAttribute("xmlns:dc", NS_DC);
            didl.SetAttribute("xmlns:dlna", NS_DLNA);
            didl.SetAttribute("xmlns:upnp", NS_UPNP);
            //didl.SetAttribute("xmlns:sec", NS_SEC);
            result.AppendChild(didl);

            var serverItem = GetItemFromObjectId(id, user);
            var item       = serverItem.Item;

            int totalCount;

            if (string.Equals(flag, "BrowseMetadata"))
            {
                totalCount = 1;

                if (item.IsFolder || serverItem.StubType.HasValue)
                {
                    var childrenResult = (await GetUserItems(item, serverItem.StubType, user, sortCriteria, start, requestedCount).ConfigureAwait(false));

                    result.DocumentElement.AppendChild(_didlBuilder.GetFolderElement(result, item, serverItem.StubType, null, childrenResult.TotalRecordCount, filter, id));
                }
                else
                {
                    result.DocumentElement.AppendChild(_didlBuilder.GetItemElement(result, item, null, null, deviceId, filter));
                }

                provided++;
            }
            else
            {
                var childrenResult = (await GetUserItems(item, serverItem.StubType, user, sortCriteria, start, requestedCount).ConfigureAwait(false));
                totalCount = childrenResult.TotalRecordCount;

                provided = childrenResult.Items.Length;

                foreach (var i in childrenResult.Items)
                {
                    var childItem       = i.Item;
                    var displayStubType = i.StubType;

                    if (childItem.IsFolder || displayStubType.HasValue)
                    {
                        var childCount = (await GetUserItems(childItem, displayStubType, user, sortCriteria, null, 0).ConfigureAwait(false))
                                         .TotalRecordCount;

                        result.DocumentElement.AppendChild(_didlBuilder.GetFolderElement(result, childItem, displayStubType, item, childCount, filter));
                    }
                    else
                    {
                        result.DocumentElement.AppendChild(_didlBuilder.GetItemElement(result, childItem, item, serverItem.StubType, deviceId, filter));
                    }
                }
            }

            var resXML = result.OuterXml;

            return(new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("Result", resXML),
                new KeyValuePair <string, string>("NumberReturned", provided.ToString(_usCulture)),
                new KeyValuePair <string, string>("TotalMatches", totalCount.ToString(_usCulture)),
                new KeyValuePair <string, string>("UpdateID", _systemUpdateId.ToString(_usCulture))
            });
        }
Пример #6
0
        public void Resolve()
        {
            if (Message != "")
            {
                HttpMethod method;

                string[] lines = Message.Replace("\r", "").Split('\n');

                Content = Message.Substring(Message.IndexOf("\r\n\r\n")).Replace("\r\n\r\n", "");

                foreach (string line in lines)
                {
                    if (line == string.Empty)
                    {
                        continue;
                    }

                    if (line.Contains("HTTP/"))
                    {
                        string[] split = line.Split(' ');
                        if (Enum.TryParse(split[0], out method))
                        {
                            Method = method;
                        }
                        else
                        {
                            Method = HttpMethod.None;
                        }

                        if (Method != HttpMethod.None)
                        {
                            Uri uri;
                            if (Uri.TryCreate(split[1], UriKind.RelativeOrAbsolute, out uri))
                            {
                                HttpUri = uri;
                            }
                            else
                            {
                                Query = split[1];
                            }
                        }


                        Version = split[2];
                        //Console.WriteLine("Method: " + Method + " Version: " + Version);
                    }
                    else
                    {
                        //Console.WriteLine("Line: " + line);
                        string[] split = line.Replace(" ", string.Empty).Split(':');
                        string   key   = split[0];
                        string   value = string.Empty;

                        for (int loop = 1; loop < split.Length; loop++)
                        {
                            value += split[loop];
                            if (loop != split.Length - 1)
                            {
                                value += ":";
                            }
                        }

                        //Console.WriteLine("Key: " + split[0] + " Value: " + value);
                        if (!Headers.ContainsKey(key))
                        {
                            Headers.Add(key, value);
                        }
                    }
                }
            }
        }
Пример #7
0
        private async Task<IEnumerable<KeyValuePair<string, string>>> HandleBrowse(Headers sparams, User user, string deviceId)
        {
            var id = sparams["ObjectID"];
            var flag = sparams["BrowseFlag"];
            var filter = new Filter(sparams.GetValueOrDefault("Filter", "*"));
            var sortCriteria = new SortCriteria(sparams.GetValueOrDefault("SortCriteria", ""));

            var provided = 0;

            // Default to null instead of 0
            // Upnp inspector sends 0 as requestedCount when it wants everything
            int? requestedCount = null;
            int? start = 0;

            int requestedVal;
            if (sparams.ContainsKey("RequestedCount") && int.TryParse(sparams["RequestedCount"], out requestedVal) && requestedVal > 0)
            {
                requestedCount = requestedVal;
            }

            int startVal;
            if (sparams.ContainsKey("StartingIndex") && int.TryParse(sparams["StartingIndex"], out startVal) && startVal > 0)
            {
                start = startVal;
            }

            //var root = GetItem(id) as IMediaFolder;
            var result = new XmlDocument();

            var didl = result.CreateElement(string.Empty, "DIDL-Lite", NS_DIDL);
            didl.SetAttribute("xmlns:dc", NS_DC);
            didl.SetAttribute("xmlns:dlna", NS_DLNA);
            didl.SetAttribute("xmlns:upnp", NS_UPNP);
            //didl.SetAttribute("xmlns:sec", NS_SEC);
            result.AppendChild(didl);

            var serverItem = GetItemFromObjectId(id, user);
            var item = serverItem.Item;

            int totalCount;

            if (string.Equals(flag, "BrowseMetadata"))
            {
                totalCount = 1;

                if (item.IsFolder || serverItem.StubType.HasValue)
                {
                    var childrenResult = (await GetUserItems(item, serverItem.StubType, user, sortCriteria, start, requestedCount).ConfigureAwait(false));

                    result.DocumentElement.AppendChild(_didlBuilder.GetFolderElement(result, item, serverItem.StubType, null, childrenResult.TotalRecordCount, filter, id));
                }
                else
                {
                    result.DocumentElement.AppendChild(_didlBuilder.GetItemElement(result, item, null, null, deviceId, filter));
                }

                provided++;
            }
            else
            {
                var childrenResult = (await GetUserItems(item, serverItem.StubType, user, sortCriteria, start, requestedCount).ConfigureAwait(false));
                totalCount = childrenResult.TotalRecordCount;

                provided = childrenResult.Items.Length;

                foreach (var i in childrenResult.Items)
                {
                    var childItem = i.Item;
                    var displayStubType = i.StubType;

                    if (childItem.IsFolder || displayStubType.HasValue)
                    {
                        var childCount = (await GetUserItems(childItem, displayStubType, user, sortCriteria, null, 0).ConfigureAwait(false))
                            .TotalRecordCount;

                        result.DocumentElement.AppendChild(_didlBuilder.GetFolderElement(result, childItem, displayStubType, item, childCount, filter));
                    }
                    else
                    {
                        result.DocumentElement.AppendChild(_didlBuilder.GetItemElement(result, childItem, item, serverItem.StubType, deviceId, filter));
                    }
                }
            }

            var resXML = result.OuterXml;

            return new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string,string>("Result", resXML),
                new KeyValuePair<string,string>("NumberReturned", provided.ToString(_usCulture)),
                new KeyValuePair<string,string>("TotalMatches", totalCount.ToString(_usCulture)),
                new KeyValuePair<string,string>("UpdateID", _systemUpdateId.ToString(_usCulture))
            };
        }
Пример #8
0
        private void ConnectionTree_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs <object> e)
        {
            this.ConnectionListView.Items.Clear();

            GridView GridView;

            if ((GridView = this.ConnectionListView.View as GridView) != null)
            {
                while (GridView.Columns.Count > 2)
                {
                    GridView.Columns.RemoveAt(2);
                }
            }

            this.selectedNode = this.ConnectionTree.SelectedItem as TreeNode;
            if (this.selectedNode != null)
            {
                TreeNode[] Children = this.selectedNode.Children;
                Dictionary <string, bool> Headers = null;
                DisplayableParameters     Parameters;

                if (Children != null)
                {
                    foreach (TreeNode Child in this.selectedNode.Children)
                    {
                        this.ConnectionListView.Items.Add(Child);

                        if (GridView != null)
                        {
                            Parameters = Child.DisplayableParameters;
                            if (Parameters != null)
                            {
                                foreach (Parameter P in Parameters.Ordered)
                                {
                                    if (P.Id == "NodeId" || P.Id == "Type")
                                    {
                                        continue;
                                    }

                                    if (Headers is null)
                                    {
                                        Headers = new Dictionary <string, bool>();
                                    }

                                    if (!Headers.ContainsKey(P.Id))
                                    {
                                        Headers[P.Id] = true;

                                        GridViewColumn Column = new GridViewColumn()
                                        {
                                            Header = P.Name,
                                            Width  = double.NaN,
                                            DisplayMemberBinding = new Binding("DisplayableParameters[" + P.Id + "]")
                                        };

                                        GridView.Columns.Add(Column);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            MainWindow MainWindow = MainWindow.FindWindow(this);

            if (MainWindow != null)
            {
                MainWindow.SelectionChanged();
            }
        }
Пример #9
0
 /// <summary>
 /// Gets the header.
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="key">The key.</param>
 /// <param name="defaultValue">The default value.</param>
 /// <returns></returns>
 public T GetHeader <T>(string key, T defaultValue = default(T))
 {
     return(Headers != null && Headers.ContainsKey(key) ? (T)Headers[key] : defaultValue);
 }
Пример #10
0
        internal bool Process()
        {
            //Core.Log.LibVerbose("Connection from {0}:{1}", RemoteAddress, RemotePort);

            #region Init
            //Core.Log.LibVerbose("Initializing request...");
            var request = _streamReader.ReadLine();
            if (string.IsNullOrEmpty(request))
            {
                throw new Exception("Invalid http request line");
            }

            //Core.Log.LibVerbose("Request: {0}", request);

            var newIndex = request.IndexOf(' ', 2);
            if (newIndex < 0)
            {
                throw new Exception("Invalid http request line");
            }
            var strMethod = request.Substring(0, newIndex);
            var lastIndex = newIndex + 1;
            newIndex = request.IndexOf(' ', lastIndex);
            if (newIndex < 0)
            {
                throw new Exception("Invalid http request line");
            }
            RawUrl      = request.Substring(lastIndex, newIndex - lastIndex);
            HttpVersion = request.Substring(newIndex + 1);

            switch (strMethod)
            {
            case "GET":
                Method = HttpMethod.GET;
                break;

            case "POST":
                Method = HttpMethod.POST;
                break;

            case "OPTIONS":
                Method = HttpMethod.OPTIONS;
                break;

            case "HEAD":
                Method = HttpMethod.HEAD;
                break;

            case "PUT":
                Method = HttpMethod.PUT;
                break;

            case "DELETE":
                Method = HttpMethod.DELETE;
                break;

            case "TRACE":
                Method = HttpMethod.TRACE;
                break;

            default:
                throw new Exception("Http method invalid");
            }
            #endregion

            #region Extract Headers
            //Core.Log.LibVerbose("Extracting headers...");
            string line;
            var    hostHeader        = false;
            string host              = null;
            var    contentTypeHeader = false;
            while (!string.IsNullOrEmpty(line = _streamReader.ReadLine()))
            {
                var separator = line.IndexOf(':', 1);
                if (separator > -1)
                {
                    var name  = line.Substring(0, separator);
                    var value = line[separator + 1] == ' ' ? line.Substring(separator + 2) : line.Substring(separator + 1);
                    Headers[name] = value;
                    if (!hostHeader && name == "Host")
                    {
                        host       = value;
                        hostHeader = true;
                    }
                    if (!contentTypeHeader && name == "Content-Type")
                    {
                        ContentType       = value;
                        contentTypeHeader = true;
                    }
                    //Core.Log.LibVerbose("Header: {0}:{1}", name, value);
                }
                else
                {
                    Core.Log.Warning("Invalid http header line: " + line);
                }
            }
            //Core.Log.LibVerbose("Headers done.");
            #endregion

            #region Extract Post Data
            if (Method == HttpMethod.POST || Method == HttpMethod.PUT)
            {
                HasPostObject = true;
                Core.Log.LibVerbose("Getting Post Data...");
                ContentLength = 0;
                if (Headers.ContainsKey("Content-Length"))
                {
                    ContentLength = Convert.ToInt32(Headers["Content-Length"]);
                    if (ContentLength > MaxPostSize)
                    {
                        throw new Exception(string.Format("POST Content-Length({0}) too big for this simple server", ContentLength));
                    }
                    if (ContentLength > 0)
                    {
                        var fReader = new BinaryReader(InputStream, Encoding.UTF8, true);
                        PostData = fReader.ReadBytes(ContentLength);
                    }
                }
                Core.Log.LibVerbose("Post Data done.");
            }
            #endregion

            Url         = new Uri("http://" + host + RawUrl);
            QueryString = HttpUtility.ParseQueryString(Url.Query);
            Form        = ContentType == "application/x-www-form-urlencoded" ?
                          new FormUrlEncodedContentParser(PostData) :
                          new FormUrlEncodedContentParser();

            return(true);
        }
Пример #11
0
 /// <summary>
 /// True if header exists
 /// </summary>
 /// <param name="name"></param>
 /// <returns></returns>
 public bool HeaderExists(string name)
 {
     return(Headers.ContainsKey(name) || NonUniqueHeaders.ContainsKey(name));
 }
Пример #12
0
 bool HasHeader(string key)
 {
     return(Headers.ContainsKey(key));
 }
Пример #13
0
        public async Task <T> CreateResponse <T>(RequestData data)
        {
            var headers = data.Headers;
            var method  = data.Method;
            var url     = data.Url;
            var content = data.Content;

            if (headers != null)
            {
                foreach (var item in headers)
                {
                    if (Headers.ContainsKey(item.Key))
                    {
                        Headers[item.Key] = item.Value;
                    }
                    else
                    {
                        Headers.Add(item.Key, item.Value);
                    }
                }
            }
            if (!Headers.ContainsKey("ClientId") && string.IsNullOrWhiteSpace(ConnectId))
            {
                Headers.Add("ClientId", ConnectId);
            }
            try
            {
                var client = HttpClient ?? new HttpClient();
                var req    = new HttpRequestMessage()
                {
                    RequestUri = new Uri(url),
                    Method     = method,
                };
                if (content != null)
                {
                    req.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                    req.Content = new StringContent(ToJson(content), Encoding.UTF8, "application/json");
                }

                foreach (var item in Headers)
                {
                    req.Headers.Add(item.Key, item.Value);
                }

                var rsp = await client.SendAsync(req);

                data.OnStatusCode?.Invoke((int)rsp.StatusCode);
                var rspbody = rsp.Content.ReadAsStringAsync().Result;
                //if ((int)rsp.StatusCode>=400)
                //{
                //    return default(T);
                //}

                var result = FromJson <T>(rspbody);
                return(result);
            }
            catch (Exception ex)
            {
                data.OnStatusCode?.Invoke(999);
                data.Catch?.Invoke(ex, data);
                Log($"{method.ToString()} {url} {ex.Message}");
            }
            return(default(T));
        }
Пример #14
0
 int ReportedBodyLength()
 {
     return(Headers.ContainsKey("Content-Length") ? GetContentLength() : 0);
 }
Пример #15
0
 bool IsChunked()
 {
     return(Headers.ContainsKey("Transfer-Encoding") &&
            Headers["Transfer-Encoding"].ToLowerInvariant() == "chunked");
 }
Пример #16
0
        private IEnumerable<KeyValuePair<string, string>> HandleSearch(Headers sparams, User user, string deviceId)
        {
            var searchCriteria = new SearchCriteria(sparams.GetValueOrDefault("SearchCriteria", ""));
            var sortCriteria = new SortCriteria(sparams.GetValueOrDefault("SortCriteria", ""));
            var filter = new Filter(sparams.GetValueOrDefault("Filter", "*"));

            // sort example: dc:title, dc:date

            var provided = 0;
            var requested = 0;
            var start = 0;

            if (sparams.ContainsKey("RequestedCount") && int.TryParse(sparams["RequestedCount"], out requested) && requested <= 0)
            {
                requested = 0;
            }
            if (sparams.ContainsKey("StartingIndex") && int.TryParse(sparams["StartingIndex"], out start) && start <= 0)
            {
                start = 0;
            }

            //var root = GetItem(id) as IMediaFolder;
            var result = new XmlDocument();

            var didl = result.CreateElement(string.Empty, "DIDL-Lite", NS_DIDL);
            didl.SetAttribute("xmlns:dc", NS_DC);
            didl.SetAttribute("xmlns:dlna", NS_DLNA);
            didl.SetAttribute("xmlns:upnp", NS_UPNP);
            didl.SetAttribute("xmlns:sec", NS_SEC);
            result.AppendChild(didl);

            var folder = (Folder)GetItemFromObjectId(sparams["ContainerID"], user);

            var children = GetChildrenSorted(folder, user, searchCriteria, sortCriteria).ToList();

            var totalCount = children.Count;

            if (start > 0)
            {
                children = children.Skip(start).ToList();
            }
            if (requested > 0)
            {
                children = children.Take(requested).ToList();
            }

            provided = children.Count;

            foreach (var i in children)
            {
                if (i.IsFolder)
                {
                    var f = (Folder)i;
                    var childCount = GetChildrenSorted(f, user, searchCriteria, sortCriteria).Count();

                    Browse_AddFolder(result, f, childCount, filter);
                }
                else
                {
                    Browse_AddItem(result, i, user, deviceId, filter);
                }
            }

            var resXML = result.OuterXml;

            return new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string,string>("Result", resXML),
                new KeyValuePair<string,string>("NumberReturned", provided.ToString(_usCulture)),
                new KeyValuePair<string,string>("TotalMatches", totalCount.ToString(_usCulture)),
                new KeyValuePair<string,string>("UpdateID", _systemUpdateId.ToString(_usCulture))
            };
        }
Пример #17
0
        /// <summary>
        /// Writes the response in one-step, and then closes the response stream
        /// </summary>
        /// <returns><c>true</c>, if written successfully, <c>false</c> otherwise.</returns>
        public bool WriteToContext()
        {
            bool syncWrite = true;

            if (_requestMethod != "HEAD")
            {
                if (JsonBody != null)
                {
                    if (!Chunked && !Headers.ContainsKey("Content-Type"))
                    {
                        var accept = _requestHeaders["Accept"];
                        if (accept != null)
                        {
                            if (accept.Contains("*/*") || accept.Contains("application/json"))
                            {
                                _responseWriter.AddHeader("Content-Type", "application/json");
                            }
                            else if (accept.Contains("text/plain"))
                            {
                                _responseWriter.AddHeader("Content-Type", "text/plain; charset=utf-8");
                            }
                            else
                            {
                                Reset();
                                _responseWriter.AddHeader("Content-Type", "application/json");
                                InternalStatus = StatusCode.NotAcceptable;
                            }
                        }
                    }

                    var json = default(byte[]);
                    try {
                        json = JsonBody.AsJson().ToArray();
                    } catch (Exception e) {
                        Log.To.Router.E(TAG, "Invalid body on response", e);
                        json = null;
                    }

                    if (!Chunked)
                    {
                        _responseWriter.ContentEncoding = Encoding.UTF8;
                        _responseWriter.ContentLength   = json.Length;
                    }

                    if (!WriteToStream(json))
                    {
                        return(false);
                    }
                }
                else if (BinaryBody != null)
                {
                    this["Content-Type"]            = BaseContentType;
                    _responseWriter.ContentEncoding = Encoding.UTF8;
                    var data = BinaryBody.ToArray();
                    if (!Chunked)
                    {
                        _responseWriter.ContentLength = data.LongLength;
                    }

                    if (!WriteToStream(data))
                    {
                        return(false);
                    }
                }
                else if (MultipartWriter != null)
                {
                    _responseWriter.ContentLength = MultipartWriter.Length;
                    MultipartWriter.WriteAsync(_responseWriter.OutputStream).ContinueWith(t =>
                    {
                        if (t.IsCompleted && t.Result)
                        {
                            TryClose();
                        }
                        else
                        {
                            Log.To.Router.I(TAG, "Multipart async write did not finish properly");
                        }
                    });
                    syncWrite = false;
                }
                else
                {
                    WriteBodyCallback?.Invoke(this, WriteBodyContext);
                }
            }

            if (syncWrite)
            {
                TryClose();
            }

            return(true);
        }
Пример #18
0
 public bool HasHeader(string name)
 {
     return(Headers != null && Headers.ContainsKey(name));
 }
Пример #19
0
 /// <summary>
 /// Gets the header with the specified key as a string if possible, otherwise null
 /// </summary>
 public string GetStringHeader(string key)
 {
     return(Headers.ContainsKey(key) && Headers[key] is string?(string)Headers[key] : null);
 }
Пример #20
0
        internal EventMessage(BasicMessage basicMessage)
        {
            if (basicMessage is EventMessage)
            {
                Headers  = basicMessage.Headers;
                BodyText = basicMessage.BodyText;
                return;
            }

            if (basicMessage.ContentType == ContentTypes.CommandReply)
            {
                /*
                 * Special Case:
                 * When an Outbound Socket sends the "connect" command, FreeSwitch responds with a Command-Reply.
                 * This Command-Reply message contains a CHANNEL_DATA event message buried in its headers.
                 * In this case, we can hydrate an event message from a message of content type Command-Reply.
                 */
                if (basicMessage.Headers.ContainsKey(HeaderNames.EventName))
                {
                    Headers  = basicMessage.Headers;
                    BodyText = basicMessage.BodyText;
                    return;
                }

                /* otherwise, we'll throw an exception if we get the wrong content-type message passed in*/
                throw new InvalidOperationException("Expected content type event/plain, got {0} instead.".Fmt(basicMessage.ContentType));
            }

            // normally, the content of the event will be in the BasicMessage's body text and will need to be parsed to produce an EventMessage
            if (string.IsNullOrEmpty(basicMessage.BodyText))
            {
                throw new ArgumentException("Message did not contain an event body.");
            }

            try
            {
                var delimiterIndex = basicMessage.BodyText.IndexOf("\n\n", StringComparison.Ordinal);
                if (delimiterIndex == -1 || delimiterIndex == basicMessage.BodyText.Length - 2)
                {
                    // body text consists of key-value-pair event headers, no body
                    Headers  = basicMessage.BodyText.ParseKeyValuePairs(": ");
                    BodyText = null;
                }
                else
                {
                    // ...but some Event Messages also carry a body payload, eg. a BACKGROUND_JOB event
                    // which is a message carried inside an EventMessage carried inside a BasicMessage..
                    Headers = basicMessage.BodyText.Substring(0, delimiterIndex).ParseKeyValuePairs(": ");

                    Debug.Assert(Headers.ContainsKey(HeaderNames.ContentLength));
                    var contentLength = int.Parse(Headers[HeaderNames.ContentLength]);

                    Debug.Assert(delimiterIndex + 2 + contentLength <= basicMessage.BodyText.Length, "Message cut off mid-transmission");
                    var body = basicMessage.BodyText.Substring(delimiterIndex + 2, contentLength);

                    //remove any \n\n if any
                    var index = body.IndexOf("\n\n", StringComparison.Ordinal);
                    BodyText = index > 0 ? body.Substring(0, index) : body;
                }
            }
            catch (Exception ex)
            {
                Log.ErrorException("Failed to parse body of event", ex);
                Log.Error(BodyText);
                throw;
            }
        }
Пример #21
0
        private async Task<IEnumerable<KeyValuePair<string, string>>> HandleSearch(Headers sparams, User user, string deviceId)
        {
            var searchCriteria = new SearchCriteria(sparams.GetValueOrDefault("SearchCriteria", ""));
            var sortCriteria = new SortCriteria(sparams.GetValueOrDefault("SortCriteria", ""));
            var filter = new Filter(sparams.GetValueOrDefault("Filter", "*"));

            // sort example: dc:title, dc:date

            // Default to null instead of 0
            // Upnp inspector sends 0 as requestedCount when it wants everything
            int? requestedCount = null;
            int? start = 0;

            int requestedVal;
            if (sparams.ContainsKey("RequestedCount") && int.TryParse(sparams["RequestedCount"], out requestedVal) && requestedVal > 0)
            {
                requestedCount = requestedVal;
            }

            int startVal;
            if (sparams.ContainsKey("StartingIndex") && int.TryParse(sparams["StartingIndex"], out startVal) && startVal > 0)
            {
                start = startVal;
            }

            //var root = GetItem(id) as IMediaFolder;
            var result = new XmlDocument();

            var didl = result.CreateElement(string.Empty, "DIDL-Lite", NS_DIDL);
            didl.SetAttribute("xmlns:dc", NS_DC);
            didl.SetAttribute("xmlns:dlna", NS_DLNA);
            didl.SetAttribute("xmlns:upnp", NS_UPNP);

            foreach (var att in _profile.XmlRootAttributes)
            {
                didl.SetAttribute(att.Name, att.Value);
            }

            result.AppendChild(didl);

            var serverItem = GetItemFromObjectId(sparams["ContainerID"], user);

            var item = serverItem.Item;

            var childrenResult = (await GetChildrenSorted(item, user, searchCriteria, sortCriteria, start, requestedCount).ConfigureAwait(false));

            var totalCount = childrenResult.TotalRecordCount;

            var provided = childrenResult.Items.Length;

            foreach (var i in childrenResult.Items)
            {
                if (i.IsFolder)
                {
                    var childCount = (await GetChildrenSorted(i, user, searchCriteria, sortCriteria, null, 0).ConfigureAwait(false))
                        .TotalRecordCount;

                    result.DocumentElement.AppendChild(_didlBuilder.GetFolderElement(result, i, null, item, childCount, filter));
                }
                else
                {
                    result.DocumentElement.AppendChild(_didlBuilder.GetItemElement(result, i, item, serverItem.StubType, deviceId, filter));
                }
            }

            var resXML = result.OuterXml;

            return new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string,string>("Result", resXML),
                new KeyValuePair<string,string>("NumberReturned", provided.ToString(_usCulture)),
                new KeyValuePair<string,string>("TotalMatches", totalCount.ToString(_usCulture)),
                new KeyValuePair<string,string>("UpdateID", _systemUpdateId.ToString(_usCulture))
            };
        }
Пример #22
0
        public bool IsCache()
        {
            bool cache = Headers.ContainsKey("Cache-Control") || Headers.ContainsKey("ETag") || Headers.ContainsKey("If-Modified-Since");

            return(cache);
        }