Ejemplo n.º 1
0
        public static int Terminate(PhpResource process, int signal)
        {
            PhpProcessHandle handle = PhpProcessHandle.Validate(process);

            if (handle == null)
            {
                return(-1);
            }

            try
            {
                handle.Process.Kill();
            }
            catch (Exception e)
            {
                PhpException.Throw(PhpError.Warning, LibResources.GetString("error_terminating_process",
                                                                            handle.Process.ProcessName, handle.Process.Id, e.Message));
                return(-1);
            }
            return(handle.Process.ExitCode);
        }
Ejemplo n.º 2
0
        public static bool SetType(ref object variable, string type)
        {
            switch (System.Globalization.CultureInfo.InvariantCulture.TextInfo.ToLower(type)) // we don't need Unicode characters to be lowercased properly // CurrentCulture is slow
            {
            case "bool":
            case "boolean":
                variable = PHP.Core.Convert.ObjectToBoolean(variable);
                return(true);

            case "int":
            case "integer":
                variable = PHP.Core.Convert.ObjectToInteger(variable);
                return(true);

            case "float":
            case "double":
                variable = PHP.Core.Convert.ObjectToDouble(variable);
                return(true);

            case "string":
                variable = PHP.Core.Convert.ObjectToString(variable);
                return(true);

            case "array":
                variable = PHP.Core.Convert.ObjectToPhpArray(variable);
                return(true);

            case "object":
                variable = PHP.Core.Convert.ObjectToDObject(variable, ScriptContext.CurrentContext);
                return(true);

            case "null":
                variable = null;
                return(true);

            default:
                PhpException.InvalidArgument("type", LibResources.GetString("invalid_type_name"));
                return(false);
            }
        }
Ejemplo n.º 3
0
        public static object ParseUrl(string url, UrlComponent component)
        {
            PhpArray array = ParseUrl(url);

            if (array == null)
            {
                return(null);
            }

            switch (component)
            {
            case UrlComponent.Fragment: return((string)array["fragment"]);

            case UrlComponent.Host: return((string)array["host"]);

            case UrlComponent.Password: return((string)array["pass"]);

            case UrlComponent.Path: return((string)array["path"]);

            case UrlComponent.Port: object port = array["port"]; if (port != null)
                {
                    return((int)port);
                }
                else
                {
                    return(null);
                }

            case UrlComponent.Query: return((string)array["query"]);

            case UrlComponent.Scheme: return((string)array["scheme"]);

            case UrlComponent.User: return((string)array["user"]);

            default:
                PhpException.Throw(PhpError.Warning, LibResources.GetString("arg:invalid_value", "component", component));
                return(null);
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Calls the method referred by <paramref name="methodName"/> from the user defined
        /// object <paramref name="classNameOrObject"/> with parameters <paramref name="args"/>.
        /// </summary>
        /// <param name="caller">DTypeDesc of the caller's class context. Can be UnknownTypeDesc.</param>
        /// <param name="methodName">The name of the method.</param>
        /// <param name="classNameOrObject">An instance to invoke the method on or a class name.</param>
        /// <param name="args">Parameters to invoke the method with.</param>
        /// <returns>The method's return value (always dereferenced).</returns>
        internal static object CallUserMethodInternal(DTypeDesc caller, string methodName, object classNameOrObject, ICollection args)
        {
            PhpException.Throw(PhpError.Notice, LibResources.GetString("call_user_method_deprecated"));

            object  ret_val = false;
            DObject obj;
            string  class_name;

            ScriptContext context = ScriptContext.CurrentContext;

            //DTypeDesc classContext = PhpStackTrace.GetClassContext();  // TODO: GetClassContext only if needed by context.ResolveType
            if (caller != null && caller.IsUnknown)
            {
                caller = PhpStackTrace.GetClassContext();
            }

            if ((obj = classNameOrObject as DObject) != null)
            {
                // push arguments on stack
                context.Stack.AddFrame(args);
                ret_val = obj.InvokeMethod(methodName, caller, context);
            }
            else if ((class_name = PhpVariable.AsString(classNameOrObject)) != null)
            {
                // push arguments on stack
                context.Stack.AddFrame(args);

                ResolveTypeFlags flags = ResolveTypeFlags.UseAutoload | ResolveTypeFlags.ThrowErrors;
                DTypeDesc        type  = PHP.Core.Convert.ObjectToTypeDesc(class_name, flags, caller, context, null, null);

                ret_val = Operators.InvokeStaticMethod(type, methodName, null, caller, context);
            }
            else
            {
                PhpException.InvalidArgument("classNameOrObject", LibResources.GetString("arg:not_object_or_class_name"));
            }

            return(PhpVariable.Dereference(ret_val));
        }
Ejemplo n.º 5
0
            public bool Parse(string name, string value, XmlNode node)
            {
                switch (name)
                {
                case "DefaultSerializer":
                {
                    Serializer serializer = Serializers.GetSerializer(value);

                    if (serializer == null)
                    {
                        throw new ConfigurationErrorsException(LibResources.GetString("unknown_serializer", value) + ".", node);
                    }

                    this.defaultSerializer = serializer;
                    break;
                }

                default:
                    return(false);
                }
                return(true);
            }
Ejemplo n.º 6
0
        public static string GetType(string path)
        {
            bool ok = StatInternal(path, false);

            if (!ok)
            {
                return(null);
            }
            FileModeFlags mode = (FileModeFlags)statCache.st_mode & FileModeFlags.FileTypeMask;

            switch (mode)
            {
            case FileModeFlags.Directory:
                return("dir");

            case FileModeFlags.File:
                return("file");

            default:
                PhpException.Throw(PhpError.Notice, LibResources.GetString("unknown_file_type"));
                return("unknown");
            }
        }
Ejemplo n.º 7
0
            public static bool BeginIO(Stream stream, PhpStream phpStream, StreamAccessOptions access, int desc_no)
            {
                if (access == StreamAccessOptions.Read && !phpStream.CanWrite ||
                    access == StreamAccessOptions.Write && !phpStream.CanRead)
                {
                    PhpException.Throw(PhpError.Warning, LibResources.GetString("descriptor_item_invalid_mode", desc_no));
                    return(false);
                }

                ActivePipe pipe = new ActivePipe();

                pipe.stream    = stream;
                pipe.phpStream = phpStream;
                pipe.access    = access;
                pipe.callback  = new AsyncCallback(pipe.Callback);

                if (access == StreamAccessOptions.Read)
                {
                    var buffer = new byte[BufferSize];
                    stream.BeginRead(buffer, 0, buffer.Length, pipe.callback, null);
                    pipe.buffer = new PhpBytes(buffer);
                }
                else
                {
                    pipe.buffer = phpStream.ReadBytes(BufferSize);
                    if (pipe.buffer != null)
                    {
                        stream.BeginWrite(pipe.buffer.ReadonlyData, 0, pipe.buffer.Length, pipe.callback, null);
                    }
                    else
                    {
                        stream.Close();
                    }
                }

                return(true);
            }
Ejemplo n.º 8
0
        public static bool SetEnvironmentVariable(string setting)
        {
            if (HttpContext.Current != null)
            {
                PhpException.Throw(PhpError.Warning, LibResources.GetString("function_disallowed_in_web_context"));
                return(false);
            }

            if (String.IsNullOrEmpty(setting))
            {
                PhpException.InvalidArgument("setting", LibResources.GetString("arg:null_or_empty"));
                return(false);
            }

            int separator_pos = setting.IndexOf('=');

            if (separator_pos == -1)
            {
                PhpException.Throw(PhpError.Warning, LibResources.GetString("arg:invalid_value", "setting", setting));
                return(false);
            }

            string name  = setting.Substring(0, separator_pos);
            string value = setting.Substring(separator_pos + 1);

            try
            {
                Environment.SetEnvironmentVariable(name, value);
            }
            catch (Exception e)
            {
                PhpException.Throw(PhpError.Warning, e.Message);
                return(false);
            }

            return(true);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Check StatInternal input parameters.
        /// </summary>
        /// <param name="path">The path passed to stat().</param>
        /// <param name="quiet">Wheter to suppress warning message if argument is empty.</param>
        /// <param name="wrapper">If passed, it will contain valid StremWrapper to the given <paramref name="path"/>.</param>
        /// <returns>True if check passed.</returns>
        private static bool StatInternalCheck(ref string path, bool quiet, out StreamWrapper wrapper)
        {
            wrapper = null;

            if (String.IsNullOrEmpty(path))
            {
                PhpException.Throw(PhpError.Warning, LibResources.GetString("arg:empty", "path"));
                return(false);
            }

            CheckAccessOptions options = CheckAccessOptions.Empty;

            if (quiet)
            {
                options |= CheckAccessOptions.Quiet;
            }
            if (!PhpStream.ResolvePath(ref path, out wrapper, CheckAccessMode.FileOrDirectory, options))
            {
                return(false);
            }

            // check passed
            return(true);
        }
Ejemplo n.º 10
0
            public bool Parse(string name, string value, XmlNode node)
            {
                switch (name)
                {
                case "Latitude":
                    Latitude = ConfigUtils.ParseDouble(value, node);
                    break;

                case "Longitude":
                    Longitude = ConfigUtils.ParseDouble(value, node);
                    break;

                case "SunsetZenith":
                    SunsetZenith = ConfigUtils.ParseDouble(value, node);
                    break;

                case "SunriseZenith":
                    SunriseZenith = ConfigUtils.ParseDouble(value, node);
                    break;

                case "TimeZone":
                    if (!string.IsNullOrEmpty(value))
                    {
                        TimeZone = PhpTimeZone.GetTimeZone(value);
                        if (TimeZone == null)
                        {
                            throw new ConfigurationErrorsException(LibResources.GetString("unknown_timezone", value) + ".", node);
                        }
                    }
                    break;

                default:
                    return(false);
                }
                return(true);
            }
Ejemplo n.º 11
0
        public static int Extract(Dictionary <string, object> localVariables, PhpArray /*!*/ vars, ExtractType type,
                                  string prefix)
        {
            if (vars == null)
            {
                PhpException.ArgumentNull("vars");
                return(0);
            }

            if (vars.Count == 0)
            {
                return(0);
            }

            // unfortunately, type contains flags are combined with enumeration:
            bool refs = (type & ExtractType.Refs) != 0;

            type &= ExtractType.NonFlags;

            //
            // construct the action used to set the variable into the locals/globals
            //
            Action <string /*name*/, object /*value*/> updateVariableFn; // function that writes the value to locals/globals
            Predicate <string /*name*/> containsFn;                      // function that checks if variable exists
            PhpArray globals = (localVariables != null) ? null : ScriptContext.CurrentContext.GlobalVariables;

            #region select function that writes the variable

            if (refs)
            {
                // makes a reference and writes it back (deep copy is not necessary, "no duplicate pointers" rule preserved):

                if (localVariables != null)
                {
                    updateVariableFn = (name, value) =>
                    {
                        localVariables[name] = vars[name] = PhpVariable.MakeReference(value);
                    };
                }
                else
                {
                    updateVariableFn = (name, value) =>
                    {
                        globals[name] = vars[name] = PhpVariable.MakeReference(value);
                    };
                }
            }
            else
            {
                if (localVariables != null)
                {
                    updateVariableFn = (name, value) =>
                    {
                        // deep copy the value
                        value = PhpVariable.DeepCopy(PhpVariable.Dereference(value));

                        // put into locals
                        object       item;
                        PhpReference ref_item;
                        if (localVariables.TryGetValue(name, out item) && (ref_item = item as PhpReference) != null)
                        {
                            ref_item.Value = value;
                        }
                        else
                        {
                            localVariables[name] = value;
                        }
                    };
                }
                else
                {
                    updateVariableFn = (name, value) =>
                    {
                        // deep copy the value
                        value = PhpVariable.DeepCopy(PhpVariable.Dereference(value));

                        // set the value to globals
                        object       item;
                        PhpReference ref_item;
                        if (globals.TryGetValue(name, out item) && (ref_item = item as PhpReference) != null)
                        {
                            ref_item.Value = value;
                        }
                        else
                        {
                            globals[name] = value;
                        }
                    };
                }
            }

            #endregion

            Debug.Assert(updateVariableFn != null);

            #region select function that checks if variable exists

            if (localVariables != null)
            {
                containsFn = (name) => localVariables.ContainsKey(name);
            }
            else
            {
                containsFn = (name) => globals.ContainsKey(name);
            }

            #endregion

            Debug.Assert(containsFn != null);

            //
            //
            //
            int extracted_count = 0;
            foreach (KeyValuePair <IntStringKey, object> entry in vars)
            {
                string name = entry.Key.ToString();
                if (String.IsNullOrEmpty(name) && type != ExtractType.PrefixInvalid)
                {
                    continue;
                }

                switch (type)
                {
                case ExtractType.Overwrite:

                    // anything is overwritten:

                    break;

                case ExtractType.Skip:

                    // skips existing name:
                    if (containsFn(name))
                    {
                        continue;
                    }

                    break;

                case ExtractType.IfExists:

                    // skips nonexistent name:
                    if (!containsFn(name))
                    {
                        continue;
                    }

                    break;

                case ExtractType.PrefixAll:

                    // prefix anything:
                    name = String.Concat(prefix, "_", name);

                    break;

                case ExtractType.PrefixInvalid:

                    // prefixes invalid, others are overwritten:
                    if (!PhpVariable.IsValidName(name))
                    {
                        name = String.Concat(prefix, "_", name);
                    }

                    break;

                case ExtractType.PrefixSame:

                    // prefixes existing, others are overwritten:
                    if (containsFn(name))
                    {
                        name = String.Concat(prefix, "_", name);
                    }

                    break;

                case ExtractType.PrefixIfExists:

                    // prefixes existing, others are skipped:
                    if (containsFn(name))
                    {
                        name = String.Concat(prefix, "_", name);
                    }
                    else
                    {
                        continue;
                    }

                    break;

                default:
                    PhpException.InvalidArgument("type", LibResources.GetString("arg:invalid_value"));
                    return(0);
                }

                // invalid names are skipped:
                if (PhpVariable.IsValidName(name))
                {
                    // write the value to locals or globals:
                    updateVariableFn(name, entry.Value);

                    extracted_count++;
                }
            }

            return(extracted_count);
        }
Ejemplo n.º 12
0
        public static PhpArray ParseUrl(string url)
        {
            Match match = ParseUrlMethods.ParseUrlRegEx.Match(url ?? string.Empty);

            if (match == null || !match.Success || match.Groups["port"].Value.Length > 5)   // not matching or port number too long
            {
                PhpException.Throw(PhpError.Warning, LibResources.GetString("invalid_url", FileSystemUtils.StripPassword(url)));
                return(null);
            }

            string scheme   = ParseUrlMethods.MatchedString(match.Groups["scheme"]);
            string user     = ParseUrlMethods.MatchedString(match.Groups["user"]);
            string pass     = ParseUrlMethods.MatchedString(match.Groups["pass"]);
            string host     = ParseUrlMethods.MatchedString(match.Groups["host"]);
            string port     = ParseUrlMethods.MatchedString(match.Groups["port"]);
            string path     = ParseUrlMethods.MatchedString(match.Groups["path"]);
            string query    = ParseUrlMethods.MatchedString(match.Groups["query"]);
            string fragment = ParseUrlMethods.MatchedString(match.Groups["fragment"]);

            string scheme_separator = match.Groups["scheme_separator"].Value;   // cannot be null

            int tmp;

            // some exceptions
            if (host != null && scheme != null && scheme_separator.Length == 0 && int.TryParse(host, out tmp))
            {   // domain:port/path
                port   = host;
                host   = scheme;
                scheme = null;
            }
            else if (scheme_separator.Length != 2 && host != null)
            {   // mailto:user@host
                // st:xx/zzz
                // mydomain.com/path
                // mydomain.com:port/path

                // dismiss user and pass
                if (user != null || pass != null)
                {
                    if (pass != null)
                    {
                        user = user + ":" + pass;
                    }
                    host = user + "@" + host;

                    user = null;
                    pass = null;
                }

                // dismiss port
                if (port != null)
                {
                    host += ":" + port;
                    port  = null;
                }

                // everything as a path
                path = scheme_separator + host + path;
                host = null;
            }

            PhpArray result = new PhpArray(0, 8);

            const char neutralChar = '_';

            // store segments into the array (same order as it is in PHP)
            if (scheme != null)
            {
                result["scheme"] = ParseUrlMethods.ReplaceControlCharset(scheme, neutralChar);
            }
            if (host != null)
            {
                result["host"] = ParseUrlMethods.ReplaceControlCharset(host, neutralChar);
            }
            if (port != null)
            {
                result["port"] = (int)unchecked ((ushort)uint.Parse(port));              // PHP overflows in this way
            }
            if (user != null)
            {
                result["user"] = ParseUrlMethods.ReplaceControlCharset(user, neutralChar);
            }
            if (pass != null)
            {
                result["pass"] = ParseUrlMethods.ReplaceControlCharset(pass, neutralChar);
            }
            if (path != null)
            {
                result["path"] = ParseUrlMethods.ReplaceControlCharset(path, neutralChar);
            }
            if (query != null)
            {
                result["query"] = ParseUrlMethods.ReplaceControlCharset(query, neutralChar);
            }
            if (fragment != null)
            {
                result["fragment"] = ParseUrlMethods.ReplaceControlCharset(fragment, neutralChar);
            }

            return(result);
        }
Ejemplo n.º 13
0
            /// <summary>
            /// Starts mail transaction and prepares the data lines from supplied message properties.
            /// Processes provided headers to determine cc, bcc and from values.
            /// All data will be send as ASCII if possible.
            /// </summary>
            /// <param name="from">Sender of the mail.</param>
            /// <param name="to">Recipients of the mail.</param>
            /// <param name="subject">Subject of the mail.</param>
            /// <param name="headers">Additional headers.</param>
            /// <param name="body">Message body.</param>
            /// <returns>List of message body lines.</returns>
            private IEnumerable <string> /*!*/ ProcessMessageHeaders(string from, string to, string subject, string headers, string body)
            {
                Dictionary <string, int> headerHashtable         = new Dictionary <string, int>(StringComparer.OrdinalIgnoreCase);
                List <KeyValuePair <string, string> > headerList = new List <KeyValuePair <string, string> >();
                List <string> recipients = new List <string>(1)
                {
                    to
                };

                //parse headers
                if (headers != null)
                {
                    using (StringReader reader = new StringReader(headers))
                    {
                        string line;
                        while ((line = reader.ReadLine()) != null)
                        {
                            int index = line.IndexOf(": ", StringComparison.Ordinal);

                            if (index > 0)
                            {
                                string name  = line.Substring(0, index);
                                string value = line.Substring(index + 2);

                                //
                                headerHashtable[name] = headerList.Count;   // remember last position of <name> header
                                headerList.Add(new KeyValuePair <string, string>(name, value));

                                // process known headers:
                                if (from == null && name.EqualsOrdinalIgnoreCase("from"))
                                {
                                    from = value;
                                }
                                if (name.EqualsOrdinalIgnoreCase("cc") || name.EqualsOrdinalIgnoreCase("bcc"))
                                {
                                    recipients.Add(value); //PostRcptTo(value); // postponed until we are discovering from address
                                }
                            }
                        }
                    }
                }

                // check from address:
                if (from == null)
                {
                    throw new SmtpException(LibResources.GetString("smtp_sendmail_from_not_set"));
                }

                // start mail transaction:
                Post(FormatEmailAddress(from, "MAIL FROM:<{0}>"));
                Ack("250");

                for (int i = 0; i < recipients.Count; i++)
                {
                    PostRcptTo(recipients[i]);
                }

                // additional message lines:
                List <string> ret = new List <string>();

                // Date:
                ret.Add("Date: " + DateTime.Now.ToString("ddd, dd MMM yyyy HH:mm:ss zz00", new CultureInfo("en-US")));

                // From: // Only add the From: field from <from> parameter if it isn't in the custom headers:
                if (!headerHashtable.ContainsKey("from") && !string.IsNullOrEmpty(from))
                {
                    ret.Add("From: " + from);
                }

                // Subject:
                ret.Add("Subject: " + (subject ?? "No Subject"));

                // To: // Only add the To: field from the <to> parameter if isn't in the custom headers:
                if (!headerHashtable.ContainsKey("to") && !string.IsNullOrEmpty(to))
                {
                    ret.Add("To: " + to);
                }

                // add headers, ignore duplicities (only accept the last occurance):
                foreach (var headerIndex in headerHashtable.Values)
                {
                    var header = headerList[headerIndex];
                    ret.Add(string.Format("{0}: {1}", header.Key, header.Value));
                }

                ret.Add("");

                // parse the <body> into lines:
                StringReader bodyReader = new StringReader(body);

                while (bodyReader.Peek() != -1)
                {
                    ret.Add(bodyReader.ReadLine());
                }

                return(ret);
            }
Ejemplo n.º 14
0
        /// <summary>
        /// Adds characters using a mask with specified interval bounds separator.
        /// </summary>
        /// <param name="mask">The mask.</param>
        /// <param name="separator">The separator.</param>
        public void AddUsingMask(string mask, string separator)
        {
            if (separator == null || separator == "")
            {
                throw new ArgumentNullException("separator");
            }

            int i, k, start;

            start = i = 0;

            for (; ;)
            {
                while (i < mask.Length && mask[i] != separator[0])
                {
                    Add(mask[i]);
                    i++;
                }

                if (i == mask.Length)
                {
                    break;
                }

                k = 1;
                while (k < separator.Length && i + k < mask.Length && mask[i + k] == separator[k])
                {
                    k++;
                }

                // entire separator read:
                if (k == separator.Length)
                {
                    // the end of the mask:
                    if (i + k == mask.Length)
                    {
                        for (int j = 0; j < separator.Length; j++)
                        {
                            Add(separator[j]);
                        }

                        if (i > start)
                        {
                            PhpException.Throw(PhpError.Warning, LibResources.GetString("char_range_no_char_on_right"));
                        }

                        return;
                    }

                    // interval has its first point behind the starting point:
                    if (i > start)
                    {
                        if (mask[i - 1] > mask[i + k])
                        {
                            PhpException.Throw(PhpError.Warning, LibResources.GetString("char_range_not_incrementing"));
                            Add(mask[i - 1]);
                        }
                        else
                        {
                            AddRange(mask[i - 1], mask[i + k]);
                        }

                        // entire interval has been read, starting from beginning:
                        start = i;
                        i    += k + 1;
                    }
                    else
                    {
                        PhpException.Throw(PhpError.Warning, LibResources.GetString("char_range_no_char_on_left"));

                        for (int j = 0; j < separator.Length; j++)
                        {
                            Add(separator[j]);
                        }

                        i += k;
                    }
                }
                else if (i + k == mask.Length)
                {
                    // part of the separator read:
                    for (int j = 0; j < k; j++)
                    {
                        Add(separator[j]);
                    }

                    return;
                }
                else
                {
                    Add(separator[0]);
                    i++;
                }
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Adds characters matching given mask.
        /// </summary>
        /// <param name="mask">The mask of characters to be added. Any collection with items convertible to the <see cref="char"/> type.</param>
        /// <remarks>
        /// <para>The <paramref name="mask"/> may contain single characters as well as intervals "a..b",
        /// where <I>a</I>, <I>b</I> are characters and <I>a</I> is less than or equal to <I>b</I>.</para>
        /// <para>There are no characters delimiting elements of the mask.</para>
        /// <para>If the mask is not valid as a whole its valid parts are processed.</para>
        /// </remarks>
        /// <example><c>"a..bA..Z0..9"</c> means alphanumeric characters, <c>"a.b..d"</c> means {'a', 'b', 'c', 'd', '.'} etc.</example>
        /// <exception cref="PhpException"><paramref name="mask"/> is not valid mask.</exception>
        /// <exception cref="InvalidCastException">An item of <paramref name="mask"/> is not convertible to character.</exception>
        /// <exception cref="IndexOutOfRangeException">Any character of <paramref name="mask"/> is not mapped by this instance.</exception>
        public void AddUsingMask(string mask)
        {
            if (mask == null)
            {
                return;
            }

            // implemented by automaton with the following states:
            const int char_empty   = 0;               // no character read - initial state and after interval read state
            const int char_read    = 1;               // one char read into buffer, no dots read
            const int dot_read     = 2;               // one char read into buffer, one dot read
            const int dot_dot_read = 3;               // one char read into buffer, two dots read

            // the interval constructing character:
            const char dot = '.';

            int  state = char_empty;                  // initial state
            char first = '\0';                        // the first character of an interval being processed
            char last;                                // the last character of an interval being processed

            for (int i = 0; i < mask.Length; i++)
            {
                last = mask[i];
                switch (state)
                {
                case char_empty:
                    first = last;
                    state = char_read;
                    break;

                case char_read:
                    if (last != dot)
                    {
                        Add(first);
                        first = last;
                        state = char_read;
                    }
                    else
                    {
                        state = dot_read;
                    }
                    break;

                case dot_read:
                    if (last != dot)
                    {
                        if (first == dot)                                  //eg: "..x" or "x.y"
                        {
                            PhpException.Throw(PhpError.Warning, LibResources.GetString("char_range_no_char_on_left", ".."));
                        }
                        else
                        {
                            Add(first);
                        }

                        // The dot will be added and the last char read may be init char of an interval:
                        Add(dot);
                        first = last;
                        state = char_read;
                    }
                    else
                    {
                        state = dot_dot_read;
                    }
                    break;

                case dot_dot_read:

                    if (first > last)                              //eg: "a..b" or "b..a"
                    {
                        PhpException.Throw(PhpError.Warning, LibResources.GetString("char_range_not_incrementing", ".."));

                        // the first character will be added and the last char read may be init char of an interval:
                        Add(first);
                        Add(dot);
                        first = last;
                        state = char_read;
                    }
                    else
                    {
                        AddRange(first, last);
                    }

                    state = char_empty;
                    break;
                }         //switch
            }             //for

            // postprocessing:
            if (state != char_empty)
            {
                Add(first);
            }
            if (state == dot_read || state == dot_dot_read)
            {
                Add(dot);
                if (state == dot_dot_read)
                {
                    PhpException.Throw(PhpError.Warning, LibResources.GetString("char_range_no_char_on_right", ".."));
                }
            }
        }
Ejemplo n.º 16
0
        public static PhpArray Unpack(string format, PhpBytes data)
        {
            if (format == null)
            {
                return(null);
            }
            byte[] buffer = (data != null) ? data.ReadonlyData : ArrayUtils.EmptyBytes;

            Encoding encoding = Configuration.Application.Globalization.PageEncoding;

            byte[] reversed = new byte[4];             // used for reversing the order of bytes in buffer

            int      i      = 0;
            int      pos    = 0;
            PhpArray result = new PhpArray();

            while (i < format.Length)
            {
                string name;
                int    repeater;
                char   specifier;

                // parses specifier, repeater, and name from the format string:
                ParseFormatToken(format, ref i, out specifier, out repeater, out name);

                int remains = buffer.Length - pos;                          // the number of bytes remaining in the buffer
                int size;                                                   // a size of data to be extracted corresponding to the specifier

                // repeater of '@' specifier has a special meaning:
                if (specifier == '@')
                {
                    if (repeater > buffer.Length || repeater == InfiniteRepeater)
                    {
                        PhpException.Throw(PhpError.Warning, LibResources.GetString("outside_string", specifier));
                    }
                    else
                    {
                        pos = repeater;
                    }

                    continue;
                }

                // number of operations:
                int op_count;

                // gets the size of the data to read and adjust repeater:
                if (!GetSizeToUnpack(specifier, remains, repeater, out op_count, out size))
                {
                    PhpException.Throw(PhpError.Warning, LibResources.GetString("unknown_format_code", specifier));
                    return(null);
                }

                // repeats operation determined by specifier "op_count" times;
                // if op_count is infinite then stops when the number of remaining characters is zero:
                for (int j = 0; j < op_count || op_count == InfiniteRepeater; j++)
                {
                    if (size > remains)
                    {
                        // infinite means "while data are available":
                        if (op_count == InfiniteRepeater)
                        {
                            break;
                        }

                        PhpException.Throw(PhpError.Warning, LibResources.GetString("not_enought_input", specifier, size, remains));
                        return(null);
                    }

                    object item;
                    switch (specifier)
                    {
                    case 'X':                             // decreases position, no value stored:
                        if (pos == 0)
                        {
                            PhpException.Throw(PhpError.Warning, LibResources.GetString("outside_string", specifier));
                        }
                        else
                        {
                            pos--;
                        }
                        continue;

                    case 'x':                             // advances position, no value stored
                        pos++;
                        continue;

                    case 'a':                             // NUL-padded string
                    case 'A':                             // SPACE-padded string
                    {
                        byte pad = (byte)(specifier == 'a' ? 0x00 : 0x20);

                        int last = pos + size - 1;
                        while (last >= pos && buffer[last] == pad)
                        {
                            last--;
                        }

                        item = encoding.GetString(buffer, pos, last - pos + 1);
                        break;
                    }

                    case 'h':                             // Hex string, low/high nibble first - converts to a string, takes n hex digits from string:
                    case 'H':
                    {
                        int p            = pos;
                        int nibble_shift = (specifier == 'h') ? 0 : 4;

                        StringBuilder sb = new StringBuilder(size);
                        for (int k = 0; k < size; k++)
                        {
                            const string hex_digits = "0123456789ABCDEF";

                            sb.Append(hex_digits[(buffer[p] >> nibble_shift) & 0x0f]);

                            // beware of odd repeaters!
                            if (repeater == InfiniteRepeater || repeater > sb.Length)
                            {
                                sb.Append(hex_digits[(buffer[p] >> (4 - nibble_shift)) & 0x0f]);
                            }
                            p++;
                        }

                        item = sb.ToString();
                        break;
                    }

                    case 'c':                             // signed char
                        item = (int)unchecked ((sbyte)buffer[pos]);
                        break;

                    case 'C':                             // unsigned char
                        item = (int)buffer[pos];
                        break;

                    case 's':                             // signed short (always 16 bit, machine byte order)
                        item = (int)BitConverter.ToInt16(buffer, pos);
                        break;

                    case 'S':                             // unsigned short (always 16 bit, machine byte order)
                        item = (int)BitConverter.ToUInt16(buffer, pos);
                        break;

                    case 'n':                             // unsigned short (always 16 bit, big endian byte order)
                        if (BitConverter.IsLittleEndian)
                        {
                            item = (int)BitConverter.ToUInt16(LoadReverseBuffer(reversed, buffer, pos, 2), 0);
                        }
                        else
                        {
                            item = (int)BitConverter.ToUInt16(buffer, pos);
                        }
                        break;

                    case 'v':                             // unsigned short (always 16 bit, little endian byte order)
                        if (!BitConverter.IsLittleEndian)
                        {
                            item = (int)BitConverter.ToUInt16(LoadReverseBuffer(reversed, buffer, pos, 2), 0);
                        }
                        else
                        {
                            item = (int)BitConverter.ToUInt16(buffer, pos);
                        }
                        break;

                    case 'i':                             // signed integer (machine dependent size and byte order - always 32 bit)
                    case 'I':                             // unsigned integer (machine dependent size and byte order - always 32 bit)
                    case 'l':                             // signed long (always 32 bit, machine byte order)
                    case 'L':                             // unsigned long (always 32 bit, machine byte order)
                        item = BitConverter.ToInt32(buffer, pos);
                        break;

                    case 'N':                             // unsigned long (always 32 bit, big endian byte order)
                        item = unchecked (((int)buffer[pos] << 24) + (buffer[pos + 1] << 16) + (buffer[pos + 2] << 8) + buffer[pos + 3]);
                        break;

                    case 'V':                             // unsigned long (always 32 bit, little endian byte order)
                        item = unchecked (((int)buffer[pos + 3] << 24) + (buffer[pos + 2] << 16) + (buffer[pos + 1] << 8) + buffer[pos + 0]);
                        break;

                    case 'f':                             // float (machine dependent size and representation - size is always 4B)
                        item = (double)BitConverter.ToSingle(buffer, pos);
                        break;

                    case 'd':                             // double (machine dependent size and representation - size is always 8B)
                        item = BitConverter.ToDouble(buffer, pos);
                        break;

                    default:
                        Debug.Fail("Invalid specifier.");
                        return(null);
                    }

                    AddValue(result, name, item, op_count, j);

                    pos     += size;
                    remains -= size;
                }
            }

            return(result);
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Packs arguments into the buffer according to given specifiers and repeaters.
        /// Count specifies the number of valid specifiers/repeaters.
        /// </summary>
        private static void PackInternal(byte[] buffer, object[] args, char[] specifiers, int[] repeaters, int count)
        {
            Encoding encoding = Configuration.Application.Globalization.PageEncoding;
            bool     le       = BitConverter.IsLittleEndian;
            int      a        = 0;            // index of the current argument
            int      pos      = 0;            // the position in the buffer

            for (int i = 0; i < count; i++)
            {
                char specifier = specifiers[i];
                int  repeater  = repeaters[i];

                switch (specifier)
                {
                case 'x':
                    // NUL byte repeated for "repeater" count:
                    ArrayUtils.Fill(buffer, 0, pos, repeater);
                    pos += repeater;
                    break;

                case '@':
                    // NUL-fill to absolute position;
                    // if it is less then the current position the result is shortened
                    if (repeater > pos)
                    {
                        ArrayUtils.Fill(buffer, 0, pos, repeater - pos);
                    }
                    pos = repeater;
                    break;

                case 'X':
                    pos = Math.Max(0, pos - repeater);
                    break;

                case 'a':                         // NUL-padded string
                case 'A':                         // SPACE-padded string
                {
                    // argument has already been converted to string:
                    string s = (string)args[a++];

                    int length     = Math.Min(s.Length, repeater);
                    int byte_count = encoding.GetBytes(s, 0, length, buffer, pos);
                    Debug.Assert(byte_count == length, "Multibyte characters not supported");

                    // padding:
                    if (repeater > length)
                    {
                        ArrayUtils.Fill(buffer, (byte)((specifier == 'a') ? 0x00 : 0x20), pos + length, repeater - length);
                    }

                    pos += repeater;
                    break;
                }

                case 'h':                         // Hex string, low/high nibble first - converts to a string, takes n hex digits from string:
                case 'H':
                {
                    // argument has already been converted to string:
                    string s = (string)args[a++];

                    int nibble_shift = (specifier == 'h') ? 0 : 4;

                    for (int j = 0; j < repeater; j++)
                    {
                        int digit = Core.Parsers.Convert.AlphaNumericToDigit(s[j]);
                        if (digit > 15)
                        {
                            PhpException.Throw(PhpError.Warning, LibResources.GetString("illegal_hex_digit", specifier, s[j]));
                            digit = 0;
                        }

                        if (j % 2 == 0)
                        {
                            buffer[pos] = unchecked ((byte)(digit << nibble_shift));
                        }
                        else
                        {
                            buffer[pos] |= unchecked ((byte)(digit << (4 - nibble_shift)));
                            pos++;
                        }
                    }

                    // odd number of hex digits (append '0' digit):
                    if (repeater % 2 == 1)
                    {
                        pos++;
                    }

                    break;
                }

                case 'c':                         // signed char
                case 'C':                         // unsigned char
                    while (repeater-- > 0)
                    {
                        buffer[pos++] = unchecked ((byte)Core.Convert.ObjectToInteger(args[a++]));
                    }
                    break;

                case 's':                         // signed short (always 16 bit, machine byte order)
                case 'S':                         // unsigned short (always 16 bit, machine byte order)
                    while (repeater-- > 0)
                    {
                        PackNumber(BitConverter.GetBytes(unchecked ((ushort)Core.Convert.ObjectToInteger(args[a++]))), le, buffer, ref pos);
                    }
                    break;

                case 'n':                         // unsigned short (always 16 bit, big endian byte order)
                case 'v':                         // unsigned short (always 16 bit, little endian byte order)
                    while (repeater-- > 0)
                    {
                        PackNumber(BitConverter.GetBytes(unchecked ((ushort)Core.Convert.ObjectToInteger(args[a++]))), specifier == 'v', buffer, ref pos);
                    }
                    break;

                case 'i':                         // signed integer (machine dependent size and byte order - always 32 bit)
                case 'I':                         // signed integer (machine dependent size and byte order - always 32 bit)
                case 'l':                         // signed long (always 32 bit, machine byte order)
                case 'L':                         // unsigned long (always 32 bit, machine byte order)
                    while (repeater-- > 0)
                    {
                        PackNumber(BitConverter.GetBytes(Core.Convert.ObjectToInteger(args[a++])), le, buffer, ref pos);
                    }
                    break;

                case 'N':                         // unsigned long (always 32 bit, big endian byte order)
                case 'V':                         // unsigned long (always 32 bit, little endian byte order)
                    while (repeater-- > 0)
                    {
                        PackNumber(BitConverter.GetBytes(Core.Convert.ObjectToInteger(args[a++])), specifier == 'V', buffer, ref pos);
                    }
                    break;

                case 'f':                         // float (machine dependent size and representation - size is always 4B)
                    while (repeater-- > 0)
                    {
                        PackNumber(BitConverter.GetBytes(unchecked ((float)Core.Convert.ObjectToDouble(args[a++]))), le, buffer, ref pos);
                    }
                    break;

                case 'd':                         // double (machine dependent size and representation - size is always 8B)
                    while (repeater-- > 0)
                    {
                        PackNumber(BitConverter.GetBytes(Core.Convert.ObjectToDouble(args[a++])), le, buffer, ref pos);
                    }
                    break;

                default:
                    Debug.Fail("Invalid specifier");
                    break;
                }
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Computes the total size of binary data according to given specifiers and repeaters.
        /// Only <c>count</c> of them are valid.
        /// </summary>
        private static void GetPackedDataSize(char[] specifiers, int[] repeaters, int count,
                                              out int resultLength, out int maxLength)
        {
            long result = 0;

            maxLength = 0;

            for (int i = 0; i < count; i++)
            {
                long repeater  = repeaters[i];
                char specifier = specifiers[i];

                switch (specifier)
                {
                case 'x':
                    // NUL byte repeated for "repeater" count:
                    result += repeater;
                    break;

                case '@':
                    // NUL-fill to absolute position;
                    // if it is less then the current position the result is shortened
                    result = repeater;
                    break;

                case 'X':
                    // shortens the result by "repeater" bytes (underflow has to be checked):
                    if (result < repeater)
                    {
                        PhpException.Throw(PhpError.Warning, LibResources.GetString("outside_string", specifier));
                        result = 0;
                    }
                    else
                    {
                        result -= repeater;
                    }
                    break;

                case 'a':                         // NUL-padded string
                case 'A':                         // SPACE-padded string
                case 'c':                         // signed char
                case 'C':                         // unsigned char
                    result += repeater;
                    break;

                case 's':                         // signed short (always 16 bit, machine byte order)
                case 'S':                         // unsigned short (always 16 bit, machine byte order)
                case 'n':                         // unsigned short (always 16 bit, big endian byte order)
                case 'v':                         // unsigned short (always 16 bit, little endian byte order)
                    result += repeater * 2;
                    break;

                case 'i':                         // signed integer (machine dependent size and byte order - always 32 bit)
                case 'I':                         // unsigned integer (machine dependent size and byte order - always 32 bit)
                case 'l':                         // signed long (always 32 bit, machine byte order)
                case 'L':                         // unsigned long (always 32 bit, machine byte order)
                case 'N':                         // unsigned long (always 32 bit, big endian byte order)
                case 'V':                         // unsigned long (always 32 bit, little endian byte order)
                case 'f':                         // float (machine dependent size and representation)
                    result += repeater * 4;
                    break;

                case 'd':                         // double (machine dependent size and representation)
                    result += repeater * 8;
                    break;

                case 'h':                         // Hex string, low/high nibble first - converts to a string, takes n hex digits from it:
                case 'H':
                    result += (repeater + 1) / 2;
                    break;

                default:
                    Debug.Fail("Invalid repeater");
                    break;
                }

                // checks for overflow:
                if (result > Int32.MaxValue)
                {
                    PhpException.Throw(PhpError.Warning, LibResources.GetString("binary_data_overflown", specifier));
                    result = Int32.MaxValue;
                }

                // expands the max length:
                if (result > maxLength)
                {
                    maxLength = unchecked ((int)result);
                }
            }

            resultLength = unchecked ((int)result);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Parses pack format. Stores specifiers and repeaters into the respective arrays.
        /// Repeaters are ensured to be finite and non-negative (infinite repeaters are converted to finite).
        /// Some arguments are also converted to another form (e.g. to string) because we will need that form later.
        /// </summary>
        /// <returns>Returns the number of parsed specifiers or 0 on error.</returns>
        private static int ParseFormat(string format, object[] args, char[] specifiers, int[] repeaters)
        {
            Encoding encoding = Configuration.Application.Globalization.PageEncoding;

            int i      = 0;              // current position in format
            int a      = 0;              // current argument index
            int result = 0;              // number of parsed specifiers

            while (i < format.Length)
            {
                char specifier = format[i++];
                int  repeater  = ParseRepeater(format, ref i);

                switch (specifier)
                {
                case 'x':                         // NUL byte
                case '@':                         // NUL-fill to absolute position
                case 'X':                         // Back up one byte

                    // consumes no arguments => repeater cannot be '*'
                    if (repeater == InfiniteRepeater)
                    {
                        PhpException.Throw(PhpError.Warning, LibResources.GetString("asterisk_ignored", specifier));
                        repeater = 1;
                    }
                    break;

                case 'a':                         // NUL-padded string
                case 'A':                         // SPACE-padded string
                case 'h':                         // Hex string, low/high nibble first - converts to a string, takes n hex digits:
                case 'H':
                {
                    // consumes one argument:
                    if (a == args.Length)
                    {
                        PhpException.Throw(PhpError.Warning, LibResources.GetString("not_enought_arguments", specifier));
                        return(0);
                    }

                    // converts the current argument to a string and stores it back:
                    string s = Core.Convert.ObjectToString(args[a]);
                    args[a] = s;
                    a++;

                    if (specifier == 'h' || specifier == 'H')
                    {
                        if (repeater > s.Length)
                        {
                            PhpException.Throw(PhpError.Warning, LibResources.GetString("not_enought_characters", specifier));
                            repeater = s.Length;
                        }
                    }
                    else
                    {
                        if (encoding.GetByteCount(s) != s.Length)
                        {
                            PhpException.Throw(PhpError.Warning, LibResources.GetString("multibyte_chars_unsupported", specifier));
                            return(0);
                        }
                    }

                    // adjusts infinite repeater to the string length:
                    if (repeater == InfiniteRepeater)
                    {
                        repeater = s.Length;
                    }

                    break;
                }

                case 'c':                         // signed char
                case 'C':                         // unsigned char
                case 's':                         // signed short (always 16 bit, machine byte order)
                case 'S':                         // unsigned short (always 16 bit, machine byte order)
                case 'n':                         // unsigned short (always 16 bit, big endian byte order)
                case 'v':                         // unsigned short (always 16 bit, little endian byte order)
                case 'i':                         // signed integer (machine dependent size and byte order)
                case 'I':                         // unsigned integer (machine dependent size and byte order)
                case 'l':                         // signed long (always 32 bit, machine byte order)
                case 'L':                         // unsigned long (always 32 bit, machine byte order)
                case 'N':                         // unsigned long (always 32 bit, big endian byte order)
                case 'V':                         // unsigned long (always 32 bit, little endian byte order)
                case 'f':                         // float (machine dependent size and representation)
                case 'd':                         // double (machine dependent size and representation)

                    if (repeater == InfiniteRepeater)
                    {
                        // infinite repeater is converted to the number of remaining arguments (can be zero):
                        repeater = args.Length - a;
                    }
                    else if (repeater > args.Length - a)
                    {
                        PhpException.Throw(PhpError.Warning, LibResources.GetString("not_enought_arguments", specifier));
                        return(0);
                    }

                    // consume arguments:
                    a += repeater;
                    break;

                default:
                    PhpException.Throw(PhpError.Warning, LibResources.GetString("unknown_format_code", specifier));
                    return(0);
                }

                specifiers[result] = specifier;
                repeaters[result]  = repeater;
                result++;
            }

            // reports unused arguments:
            if (a < args.Length)
            {
                PhpException.Throw(PhpError.Warning, LibResources.GetString("unused_arguments", args.Length - a));
            }

            return(result);
        }
Ejemplo n.º 20
0
        private static bool RedirectStreams(Process /*!*/ process, PhpArray /*!*/ descriptors, PhpArray /*!*/ pipes)
        {
            using (var descriptors_enum = descriptors.GetFastEnumerator())
                while (descriptors_enum.MoveNext())
                {
                    int desc_no = descriptors_enum.CurrentKey.Integer;

                    StreamAccessOptions access;
                    Stream stream;
                    switch (desc_no)
                    {
                    case 0: stream = process.StandardInput.BaseStream; access = StreamAccessOptions.Write; break;

                    case 1: stream = process.StandardOutput.BaseStream; access = StreamAccessOptions.Read; break;

                    case 2: stream = process.StandardError.BaseStream; access = StreamAccessOptions.Read; break;

                    default: Debug.Fail(); return(false);
                    }

                    object      value = PhpVariable.Dereference(descriptors_enum.CurrentValue);
                    PhpResource resource;
                    PhpArray    array;

                    if ((array = PhpArray.AsPhpArray(value)) != null)
                    {
                        if (!array.Contains(0))
                        {
                            // value must be either a resource or an array:
                            PhpException.Throw(PhpError.Warning, LibResources.GetString("descriptor_item_missing_qualifier", desc_no));
                            return(false);
                        }

                        string qualifier = Core.Convert.ObjectToString(array[0]);

                        switch (qualifier)
                        {
                        case "pipe":
                        {
                            // mode is ignored (it's determined by the stream):
                            PhpStream php_stream = new NativeStream(stream, null, access, String.Empty, StreamContext.Default);
                            pipes.Add(desc_no, php_stream);
                            break;
                        }

                        case "file":
                        {
                            if (!array.Contains(1))
                            {
                                PhpException.Throw(PhpError.Warning, LibResources.GetString("descriptor_item_missing_file_name", desc_no));
                                return(false);
                            }

                            if (!array.Contains(2))
                            {
                                PhpException.Throw(PhpError.Warning, LibResources.GetString("descriptor_item_missing_mode", desc_no));
                                return(false);
                            }

                            string path = Core.Convert.ObjectToString(array[1]);
                            string mode = Core.Convert.ObjectToString(array[2]);

                            PhpStream php_stream = PhpStream.Open(path, mode, StreamOpenOptions.Empty, StreamContext.Default);
                            if (php_stream == null)
                            {
                                return(false);
                            }

                            if (!ActivePipe.BeginIO(stream, php_stream, access, desc_no))
                            {
                                return(false);
                            }
                            break;
                        }

                        default:
                            PhpException.Throw(PhpError.Warning, LibResources.GetString("invalid_handle_qualifier", qualifier));
                            return(false);
                        }
                    }
                    else if ((resource = value as PhpResource) != null)
                    {
                        PhpStream php_stream = PhpStream.GetValid(resource);
                        if (php_stream == null)
                        {
                            return(false);
                        }

                        if (!ActivePipe.BeginIO(stream, php_stream, access, desc_no))
                        {
                            return(false);
                        }
                    }
                    else
                    {
                        // value must be either a resource or an array:
                        PhpException.Throw(PhpError.Warning, LibResources.GetString("descriptor_item_not_array_nor_resource", desc_no));
                        return(false);
                    }
                }

            return(true);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Opens a new SocketStream
        /// </summary>
        internal static SocketStream Connect(string remoteSocket, int port, out int errno, out string errstr,
                                             double timeout, SocketOptions flags, StreamContext /*!*/ context)
        {
            errno  = 0;
            errstr = null;

            if (remoteSocket == null)
            {
                PhpException.ArgumentNull("remoteSocket");
                return(null);
            }

            // TODO: extract schema (tcp://, udp://) and port from remoteSocket
            // Uri uri = Uri.TryCreate(remoteSocket);
            ProtocolType protocol = ProtocolType.Tcp;

            if (remoteSocket.Contains("://"))
            {
                String[] separator   = { "://" };
                String[] socketParts = remoteSocket.Split(separator, 2, StringSplitOptions.None);
                switch (socketParts[0])
                {
                case "udp":
                    protocol = ProtocolType.Udp;
                    break;

                case "tcp":
                default:
                    protocol = ProtocolType.Tcp;
                    break;
                }
                remoteSocket = socketParts[1];
            }

            if (remoteSocket.Contains(":"))
            {
                Char[]   separator   = { ':' };
                String[] socketParts = remoteSocket.Split(separator, 2, StringSplitOptions.None);
                remoteSocket = socketParts[0];

                int result = 0;
                if (socketParts[1] != "" && int.TryParse(socketParts[1], out result) &&
                    (0 < result && result < 65536))
                {
                    port = result;
                }
            }

            if (Double.IsNaN(timeout))
            {
                timeout = Configuration.Local.FileSystem.DefaultSocketTimeout;
            }

            // TODO:
            if (flags != SocketOptions.None && flags != SocketOptions.Asynchronous)
            {
                PhpException.ArgumentValueNotSupported("flags", (int)flags);
            }

            try
            {
                // workitem 299181; for remoteSocket as IPv4 address it results in IPv6 address
                //IPAddress address = System.Net.Dns.GetHostEntry(remoteSocket).AddressList[0];

                IPAddress address;
                if (!IPAddress.TryParse(remoteSocket, out address)) // if remoteSocket is not a valid IP address then lookup the DNS
                {
                    address = System.Net.Dns.GetHostEntry(remoteSocket).AddressList[0];
                }

                Socket socket = new Socket(address.AddressFamily, SocketType.Stream, protocol);

                IAsyncResult res = socket.BeginConnect(
                    new IPEndPoint(address, port),
                    new AsyncCallback(StreamSocket.ConnectResultCallback),
                    socket);

                int msec = 0;
                while (!res.IsCompleted)
                {
                    Thread.Sleep(100);
                    msec += 100;
                    if (msec / 1000.0 > timeout)
                    {
                        PhpException.Throw(PhpError.Warning, LibResources.GetString("socket_open_timeout",
                                                                                    FileSystemUtils.StripPassword(remoteSocket)));
                        return(null);
                    }
                }
                socket.EndConnect(res);

                //        socket.Connect(new IPEndPoint(address, port));
                return(new SocketStream(socket, remoteSocket, context, (flags & SocketOptions.Asynchronous) == SocketOptions.Asynchronous));
            }
            catch (SocketException e)
            {
                errno  = e.ErrorCode;
                errstr = e.Message;
            }
            catch (System.Exception e)
            {
                errno  = -1;
                errstr = e.Message;
            }

            PhpException.Throw(PhpError.Warning, LibResources.GetString("socket_open_error",
                                                                        FileSystemUtils.StripPassword(remoteSocket), errstr));
            return(null);
        }
Ejemplo n.º 22
0
            public bool Parse(string name, string value, XmlNode node)
            {
                switch (name)
                {
                case "Serializer":
                {
                    Serializer serializer = Serializers.GetSerializer(value);

                    if (serializer == null)
                    {
                        throw new ConfigurationErrorsException(LibResources.GetString("unknown_serializer", value) + ".", node);
                    }

                    this.serializer = serializer;
                    break;
                }

                case "GcProbability":
                    GcProbability = ConfigUtils.ParseInteger(value, 0, Int32.MaxValue, node);
                    break;

                case "GcDivisor":
                    GcDivisor = ConfigUtils.ParseInteger(value, 1, Int32.MaxValue, node);
                    break;

                case "GcMaxLifetime":
                    GcMaxLifetime = ConfigUtils.ParseInteger(value, Int32.MinValue, Int32.MaxValue, node);
                    break;

                case "SavePath":
                    if (value != "")
                    {
                        SavePath = value;
                    }
                    break;

                case "CacheExpire":
                    CacheExpire = ConfigUtils.ParseInteger(value, 0, Int32.MaxValue, node);
                    break;

                case "CacheLimiter":
                    CacheLimiter = value;
                    break;

                case "CookieLifetime":
                    CookieLifetime = ConfigUtils.ParseInteger(value, 0, Int32.MaxValue, node);
                    break;

                case "CookiePath":
                    CookiePath = value;
                    break;

                case "CookieDomain":
                    CookieDomain = value;
                    break;

                case "CookieSecure":
                    CookieSecure = value == "true";
                    break;

                default:
                    return(false);
                }
                return(true);
            }
Ejemplo n.º 23
0
 public static bool LoadExtension(string library)
 {
     PhpException.Throw(PhpError.Warning, LibResources.GetString("dl_not_supported"));
     return(false);
 }
Ejemplo n.º 24
0
 /// <summary>
 /// Serializes null and throws an exception.
 /// </summary>
 /// <param name="TypeName"></param>
 private void WriteUnsupported(string TypeName)
 {
     PhpException.Throw(PhpError.Warning, LibResources.GetString("serialization_unsupported_type", TypeName));
     WriteNull();
 }
Ejemplo n.º 25
0
        public static object filter_var(object variable, int filter /*= FILTER_DEFAULT*/, object options)
        {
            switch (filter)
            {
            //
            // SANITIZE
            //

            case (int)FilterSanitize.FILTER_DEFAULT:
                return(Core.Convert.ObjectToString(variable));

            case (int)FilterSanitize.EMAIL:
                // Remove all characters except letters, digits and !#$%&'*+-/=?^_`{|}~@.[].
                return(FilterSanitizeString(PHP.Core.Convert.ObjectToString(variable), (c) =>
                                            (int)c <= 0x7f && (Char.IsLetterOrDigit(c) ||
                                                               c == '!' || c == '#' || c == '$' || c == '%' || c == '&' || c == '\'' ||
                                                               c == '*' || c == '+' || c == '-' || c == '/' || c == '=' || c == '!' ||
                                                               c == '?' || c == '^' || c == '_' || c == '`' || c == '{' || c == '|' ||
                                                               c == '}' || c == '~' || c == '@' || c == '.' || c == '[' || c == ']')));

            //
            // VALIDATE
            //

            case (int)FilterValidate.EMAIL:
            {
                var str = PHP.Core.Convert.ObjectToString(variable);
                return(RegexUtilities.IsValidEmail(str) ? str : (object)false);
            }

            case (int)FilterValidate.INT:
            {
                int result;
                if (int.TryParse((PhpVariable.AsString(variable) ?? string.Empty).Trim(), out result))
                {
                    if (options != null)
                    {
                        PhpException.ArgumentValueNotSupported("options", "!null");
                    }
                    return(result);         // TODO: options: min_range, max_range
                }
                else
                {
                    return(false);
                }
            }

            case (int)FilterValidate.REGEXP:
            {
                PhpArray optarray;
                // options = options['options']['regexp']
                if ((optarray = PhpArray.AsPhpArray(options)) != null &&
                    optarray.TryGetValue("options", out options) && (optarray = PhpArray.AsPhpArray(options)) != null &&
                    optarray.TryGetValue("regexp", out options))
                {
                    if (PerlRegExp.Match(options, variable) > 0)
                    {
                        return(variable);
                    }
                }
                else
                {
                    PhpException.InvalidArgument("options", LibResources.GetString("option_missing", "regexp"));
                }
                return(false);
            }

            default:
                PhpException.ArgumentValueNotSupported("filter", filter);
                break;
            }

            return(false);
        }