public static ViewNodeAddress Parse(string uri)
        {
            int    x;
            string scheme, absolutePath, query;

            x = uri.IndexOf("://");

            scheme       = uri.Substring(0, x);
            absolutePath = uri.Substring(x + 3);

            if (absolutePath.Length > 0 && absolutePath[0] != '/')
            {
                throw new MalformedUriException(uri, "Path must be absolute");
            }

            if ((x = absolutePath.IndexOf('?')) > 0)
            {
                query        = absolutePath.Substring(x + 1);
                absolutePath = absolutePath.Substring(0, x);
            }
            else
            {
                query = "";
            }

            absolutePath = TextConversion.FromEscapedHexString(absolutePath);

            return(new ViewNodeAddress(scheme, absolutePath, query));
        }
        public virtual Exception GetErrorException()
        {
            if (this.ResponseType == ResponseCodes.ERROR)
            {
                var errorCode = this.ResponseTuples["code"];

                if (errorCode.Equals(ErrorCodes.END_OF_FILE, StringComparison.CurrentCultureIgnoreCase))
                {
                    return(new EndOfStreamException());
                }
                else if (errorCode.Equals(ErrorCodes.FILE_NOT_FOUND, StringComparison.CurrentCultureIgnoreCase))
                {
                    return(new FileNodeNotFoundException(this.ResponseTuples["uri"]));
                }
                else if (errorCode.Equals(ErrorCodes.DIRECTORY_NOT_FOUND, StringComparison.CurrentCultureIgnoreCase))
                {
                    return(new DirectoryNodeNotFoundException(this.ResponseTuples["uri"]));
                }
                else if (errorCode.Equals(ErrorCodes.UNAUTHORISED, StringComparison.CurrentCultureIgnoreCase))
                {
                    return(new UnauthorizedAccessException(TextConversion.FromEscapedHexString(this.ResponseTuples["details"])));
                }
                else
                {
                    return(new TextNetworkProtocolErrorResponseException(TextConversion.FromEscapedHexString(this.ResponseTupleString)));
                }
            }

            return(null);
        }
        public override INode Find(INodeResolver resolver, string uri, NodeType nodeType, FileSystemOptions options)
        {
            var result = uri.SplitOnFirst("://");

            if (result.Left != this.viewFileSystem.RootDirectory.Address.Scheme)
            {
                throw new NotSupportedException(result.Left);
            }

            return(this.viewFileSystem.Resolve(TextConversion.FromEscapedHexString(result.Right), nodeType));
        }
Ejemplo n.º 4
0
        public void Test_HexStringConversion()
        {
            const string complex = "http://github.com/+123%$";

            var s = TextConversion.ToEscapedHexString(complex);

            Assert.AreEqual("http%3A%2F%2Fgithub%2Ecom%2F%2B123%25%24", s);

            s = TextConversion.FromEscapedHexString(s);

            Assert.AreEqual(complex, s);
        }
        public static string DecodeString(string value, string encoding)
        {
            switch (encoding)
            {
            case "url":
                return(TextConversion.FromEscapedHexString(value));

            case "b64":
                return(Encoding.UTF8.GetString(TextConversion.FromBase64String(value)));

            default:
                throw new NotSupportedException();
            }
        }
        /// <summary>
        /// Parses a <c>GenericFileName</c>.
        /// </summary>
        /// <param name="uri"></param>
        /// <param name="defaultPort">
        /// The default port if no port is specified in the URI and the URI scheme is unknown.
        /// If the URI scheme is known, the default port for that scheme is used.
        /// </param>
        /// <returns></returns>
        public static StandardNodeAddress Parse(string uri, int defaultPort)
        {
            Uri sysUri;

            try
            {
                // For the moment use the Uri class to do parsing...

                sysUri = new Uri(uri);
            }
            catch (Exception e)
            {
                throw new MalformedUriException(uri, e.Message, e);
            }

            int    x;
            string username = sysUri.UserInfo, password = "";

            x = username.IndexOf(':');

            if (x > 0)
            {
                username = username.Substring(0, x);
                password = username.Substring(x + 1);
            }

            if (defaultPort == -1)
            {
                if (sysUri.IsDefaultPort)
                {
                    defaultPort = sysUri.Port;
                }
            }

            return(new StandardNodeAddress(sysUri.Scheme, sysUri.Host, defaultPort,
                                           sysUri.Port, username, password,
                                           TextConversion.FromEscapedHexString(sysUri.AbsolutePath), TextConversion.FromEscapedHexString(StringUtils.Right(sysUri.Query, sysUri.Query.Length - 1))));
        }
        private static object PrivateFromString(string s, bool escaped)
        {
            int    x;
            Type   type;
            string typeName, value;

            x = s.IndexOf(':');

            if (x < 0)
            {
                throw new ArgumentException();
            }

            typeName = s.Substring(0, x);
            value    = s.Substring(x + 1);

            if ((type = GetType(typeName)) == null)
            {
                throw new NotSupportedException(typeName);
            }

            if (type == typeof(DateTime))
            {
                DateTime retval;

                retval =
                    DateTime.ParseExact(value, DateTimeFormats.SortableUtcDateTimeFormatWithFractionSecondsString,
                                        System.Globalization.CultureInfo.InvariantCulture);
                retval = DateTime.SpecifyKind(retval, DateTimeKind.Utc);

                return(retval.ToLocalTime());
            }
            else if (type == typeof(byte[]))
            {
                byte[] retval;

                retval = TextConversion.FromBase64String(value);

                return(retval);
            }
            else if (type == typeof(bool))
            {
                value = value.ToLower();

                if (value == "t")
                {
                    return(true);
                }
                else if (value == "f")
                {
                    return(false);
                }
                else
                {
                    return(Convert.ChangeType(value, type));
                }
            }
            else
            {
                if (escaped)
                {
                    if (type == typeof(string))
                    {
                        return(TextConversion.FromEscapedHexString(value));
                    }
                }

                return(Convert.ChangeType(value, type));
            }
        }
Ejemplo n.º 8
0
        public override void Process(Command command)
        {
            var count   = 0;
            var options = this.LoadOptions <CommandOptions>((TextCommand)command);
            var dir     = this.Connection.FileSystemManager.ResolveDirectory(options.Uri);

            dir.Refresh();

            if (options.Regex != null)
            {
                options.Regex = TextConversion.FromEscapedHexString(options.Regex);
            }

            if (!dir.Exists)
            {
                throw new DirectoryNodeNotFoundException(dir.Address);
            }

            Connection.WriteOk();

            if (options.IncludeAttributes)
            {
                Exception       exception = null;
                InvocationQueue queue;

                if (t_InvocationQueue == null)
                {
                    t_InvocationQueue = new InvocationQueue();
                }

                queue = t_InvocationQueue;

                queue.TaskAsynchronisity = TaskAsynchronisity.AsyncWithSystemPoolThread;

                queue.Start();

                try
                {
                    IEnumerable <INode> children = null;

                    if (String.IsNullOrEmpty(options.Regex))
                    {
                        children = dir.GetChildren();
                    }
                    else
                    {
                        children = dir.GetChildren(RegexBasedNodePredicateHelper.New(options.Regex));
                    }

                    foreach (var node in children)
                    {
                        var enclosedNode = node;

                        if (queue.TaskState == TaskState.Stopped)
                        {
                            break;
                        }

                        queue.Enqueue
                        (
                            delegate
                        {
                            try
                            {
                                if (enclosedNode.NodeType == NodeType.Directory)
                                {
                                    Connection.WriteTextPartialBlock("d:");
                                }
                                else
                                {
                                    Connection.WriteTextPartialBlock("f:");
                                }

                                Connection.WriteTextBlock(TextConversion.ToEscapedHexString(enclosedNode.Name, TextConversion.IsStandardUrlEscapedChar));

                                AttributesCommands.PrintAttributes(this.Connection, enclosedNode);

                                count++;

                                if (count % 15 == 0)
                                {
                                    Connection.Flush();
                                }
                            }
                            catch (Exception e)
                            {
                                queue.Stop();

                                exception = e;
                            }
                        }
                        );
                    }

                    if (queue.TaskState == TaskState.Stopped)
                    {
                        throw exception;
                    }
                }
                finally
                {
                    queue.Enqueue(queue.Stop);

                    queue.WaitForAnyTaskState(value => value != TaskState.Running);

                    queue.Reset();

                    Connection.Flush();
                }
            }
            else
            {
                IEnumerable <string> children;

                if (string.IsNullOrEmpty(options.Regex))
                {
                    children = dir.GetChildNames(NodeType.Directory);
                }
                else
                {
                    children = dir.GetChildNames(NodeType.Directory, PredicateUtils.NewRegex(options.Regex));
                }

                foreach (var name in children)
                {
                    Connection.WriteTextPartialBlock("d:");
                    Connection.WriteTextBlock(TextConversion.ToEscapedHexString(name, TextConversion.IsStandardUrlEscapedChar));

                    count++;

                    if (count % 15 == 0)
                    {
                        Connection.Flush();
                    }
                }

                count = 0;

                if (string.IsNullOrEmpty(options.Regex))
                {
                    children = dir.GetChildNames(NodeType.File);
                }
                else
                {
                    children = dir.GetChildNames(NodeType.File, PredicateUtils.NewRegex(options.Regex));
                }

                foreach (var name in children)
                {
                    Connection.WriteTextPartialBlock("f:");
                    Connection.WriteTextBlock(TextConversion.ToEscapedHexString(name));

                    count++;

                    if (count % 15 == 0)
                    {
                        Connection.Flush();
                    }
                }
            }

            Connection.Flush();
        }
        public static IEnumerable <Pair <NetworkFileSystemEntry, string> > ReadEntries(Func <string> readNextLine)
        {
            string               currentFile     = null;
            NodeType             currentNodeType = null;
            AttributesEnumerable attributesEnumerable;
            ValueBox <string>    currentLine = new ValueBox <string>();

            Predicate <string> isAttributeLine = delegate(string s)
            {
                return(s[0] == ' ');
            };

            currentLine.Value = readNextLine();

            try
            {
                for (; ;)
                {
                    currentFile     = null;
                    currentNodeType = null;

                    if (currentLine.Value.StartsWith(ResponseCodes.RESPONSE_MARKER, StringComparison.CurrentCultureIgnoreCase))
                    {
                        if (currentLine.Value.EqualsIgnoreCase(ResponseCodes.READY))
                        {
                            break;
                        }
                        else if (currentLine.Value.StartsWith(ResponseCodes.ERROR, StringComparison.CurrentCultureIgnoreCase))
                        {
                            yield return(new Pair <NetworkFileSystemEntry, string>
                                         (
                                             new NetworkFileSystemEntry(),
                                             currentLine.Value
                                         ));

                            yield break;
                        }
                        else if (currentLine.Value.StartsWith(ResponseCodes.ENCODING))
                        {
                            string value = null, encoding = "url";

                            currentLine.Value = currentLine.Value.Substring(ResponseCodes.ENCODING.Length);

                            foreach (KeyValuePair <string, string> keyValuePair in CommandResponse.ParseTupleString(currentLine.Value))
                            {
                                if (keyValuePair.Key == "value")
                                {
                                    value = keyValuePair.Value;
                                }
                                else if (keyValuePair.Key == "encoding")
                                {
                                    encoding = keyValuePair.Key;
                                }
                                else if (keyValuePair.Key == "type")
                                {
                                    currentNodeType = GetNodeType(keyValuePair.Value);
                                }
                            }

                            if (value == null || currentNodeType == null)
                            {
                                AttributesEnumerable.ConsumeAttributes(readNextLine, currentLine, isAttributeLine);

                                continue;
                            }

                            try
                            {
                                currentFile = ProtocolTypes.DecodeString(value, encoding);
                            }
                            catch (NotSupportedException)
                            {
                                AttributesEnumerable.ConsumeAttributes(readNextLine, currentLine, isAttributeLine);

                                continue;
                            }
                        }
                        else
                        {
                            // Major error

                            throw new TextNetworkProtocolException();
                        }
                    }

                    if (currentLine.Value.Length == 0)
                    {
                        continue;
                    }

                    if (currentFile == null)
                    {
                        Pair <string, string> result;

                        result          = currentLine.Value.SplitAroundFirstCharFromLeft(':');
                        currentFile     = TextConversion.FromEscapedHexString(result.Right);
                        currentNodeType = GetNodeType(result.Left);
                    }

                    if (currentNodeType == null)
                    {
                        AttributesEnumerable.ConsumeAttributes(readNextLine, currentLine, isAttributeLine);

                        continue;
                    }

                    attributesEnumerable = new AttributesEnumerable
                                           (
                        readNextLine,
                        isAttributeLine,
                        currentLine
                                           );

                    try
                    {
                        yield return(new Pair <NetworkFileSystemEntry, string>
                                     (
                                         new NetworkFileSystemEntry(currentFile, currentNodeType, attributesEnumerable),
                                         null
                                     ));
                    }
                    finally
                    {
                        attributesEnumerable.Finish();
                    }
                }
            }
            finally
            {
                while (!currentLine.Value.StartsWith(ResponseCodes.READY))
                {
                    currentLine.Value = readNextLine();
                }
            }
        }
        public static LocalNodeAddress Parse(string uri)
        {
            Group  group;
            Match  match = null;
            string root, scheme, query;

            // Often Parse will be called with the exact same URI reference that was last passed
            // to CanParse.  If this is the case then use the results cached by the last call to
            // CanParse from this thread.

            if ((object)uri == (object)lastCanParseUri)
            {
                match = lastCanParseMatch;
            }

            while (true)
            {
                if (match == null)
                {
                    match = localFileNameRegEx.Match(uri);
                }

                if (!match.Success)
                {
                    throw new MalformedUriException(uri);
                }

                bool schemeExplicitlyProvided;

                group = match.Groups["scheme"];

                if (group.Value == "")
                {
                    scheme = "file";
                    schemeExplicitlyProvided = false;
                }
                else
                {
                    scheme = group.Value;
                    schemeExplicitlyProvided = true;
                }

                group = match.Groups["uncserver"];

                if (group.Success)
                {
                    string path;
                    Pair <string, string> result;

                    path = match.Groups["path1"].Value;

                    result = path.SplitAroundCharFromLeft(1, PredicateUtils.ObjectEqualsAny('\\', '/'));

                    root = "//" + group.Value + result.Left.Replace('\\', '/');
                    path = "/" + result.Right;

                    if (path == "")
                    {
                        path = "/";
                    }

                    query = match.Groups["query"].Value;

                    return(new LocalNodeAddress(scheme, root, true, StringUriUtils.NormalizePath(path), query));
                }
                else
                {
                    string path;

                    group = match.Groups["root"];

                    if (group.Captures.Count > 0)
                    {
                        //
                        // Windows path specification
                        //

                        root = group.Value;

                        path = match.Groups["path2"].Value;

                        if (path.Length == 0)
                        {
                            path = FileSystemManager.SeperatorString;
                        }

                        query = match.Groups["query"].Value;

                        path = StringUriUtils.NormalizePath(path);

                        if (schemeExplicitlyProvided)
                        {
                            //
                            // Explicitly provided scheme means
                            // special characters are hexcoded
                            //

                            path  = TextConversion.FromEscapedHexString(path);
                            query = TextConversion.FromEscapedHexString(query);
                        }

                        return(new LocalNodeAddress(scheme, root, true, path, query));
                    }
                    else if (match.Groups["path3"].Value != "")
                    {
                        //
                        // Unix path specification
                        //

                        path  = match.Groups["path3"].Value;
                        query = match.Groups["query"].Value;

                        path = StringUriUtils.NormalizePath(path);

                        if (schemeExplicitlyProvided)
                        {
                            //
                            // Explicitly provided scheme means
                            // special characters are hexcoded
                            //

                            path  = TextConversion.FromEscapedHexString(path);
                            query = TextConversion.FromEscapedHexString(query);
                        }

                        return(new LocalNodeAddress(scheme, "", true, path, query));
                    }
                    else
                    {
                        //
                        // Relative path specification
                        //

                        path  = match.Groups["path4"].Value;
                        query = match.Groups["query"].Value;

                        path = StringUriUtils.Combine(Environment.CurrentDirectory, path);
                        path = StringUriUtils.NormalizePath(path);

                        if (!string.IsNullOrEmpty(query))
                        {
                            query = "?" + query;
                        }
                        else
                        {
                            query = "";
                        }

                        if (schemeExplicitlyProvided)
                        {
                            uri = scheme + "://" + path + "query";
                        }
                        else
                        {
                            uri = path + query;
                        }

                        match = null;
                    }
                }
            }
        }
        public override IEnumerable <Pair <string, NodeType> > List(string uri, string regex)
        {
            Predicate <string> acceptName = null;

            using (this.AcquireCommandContext(false))
            {
                try
                {
                    try
                    {
                        if (!String.IsNullOrEmpty(regex))
                        {
                            SendCommand(DefaultTryCount, @"list -regex=""{0}"" ""{1}""", TextConversion.ToEscapedHexString(regex), uri).ProcessError();
                        }
                        else
                        {
                            SendCommand(DefaultTryCount, @"list ""{0}""", uri).ProcessError();

                            acceptName = PredicateUtils.NewRegex(regex);
                        }
                    }
                    catch
                    {
                        ReadReady();

                        throw;
                    }
                }
                catch (TextNetworkProtocolException)
                {
                    this.connected = false;

                    throw;
                }
                catch (IOException)
                {
                    this.connected = false;

                    throw;
                }

                for (; ;)
                {
                    string   line;
                    NodeType currentNodeType;
                    Pair <string, string> currentFile;

                    try
                    {
                        line = TextConversion.FromEscapedHexString(ReadNextLine());
                    }
                    catch (TextNetworkProtocolException)
                    {
                        this.connected = false;

                        throw;
                    }
                    catch (IOException)
                    {
                        this.connected = false;

                        throw;
                    }

                    if (line.EqualsIgnoreCase(ResponseCodes.READY))
                    {
                        break;
                    }

                    currentFile = line.SplitAroundFirstCharFromLeft(':');

                    currentFile.Right = TextConversion.FromEscapedHexString(currentFile.Right);

                    currentNodeType = TextNetworkProtocol.GetNodeType(currentFile.Left);

                    if (currentNodeType == null || currentFile.Right.Length == 0)
                    {
                        continue;
                    }

                    if (acceptName != null)
                    {
                        if (acceptName(currentFile.Right))
                        {
                            yield return(new Pair <string, NodeType>(currentFile.Right, currentNodeType));
                        }
                    }
                    else
                    {
                        yield return(new Pair <string, NodeType>(currentFile.Right, currentNodeType));
                    }
                }
            }
        }
 public override string ToString()
 {
     return(TextConversion.FromEscapedHexString(this.Uri.ToString()));
 }