Example #1
0
        public override PhpStream Open(ref string path, string mode, StreamOpenOptions options, StreamContext context)
        {
            int level = -1;
            DeflateFilterMode deflateMode = DeflateFilterMode.Normal;

            #region Parse mode options
            // PHP just looks whether there are mode flags in the mode string (skip the first character)
            // last flag is the valid one

            for (int i = 1; i < mode.Length; i++)
            {
                if (Char.IsDigit(mode[i]))
                {
                    level = mode[i] - '0';
                }
                else if (mode[i] == 'f')
                {
                    deflateMode = DeflateFilterMode.Filter;
                }
                else if (mode[i] == 'h')
                {
                    deflateMode = DeflateFilterMode.Huffman;
                }
            }

            #endregion

            #region Path correction

            if (path.StartsWith("compress.zlib://"))
            {
                path = path.Substring(16);
            }
            else if (path.StartsWith("zlib:"))
            {
                path = path.Substring(5);
            }

            #endregion

            PhpStream stream = PhpStream.Open(path, mode, options);

            if (stream != null && stream.CanRead)
            {
                stream.AddFilter(new GzipUncompressionFilter(), FilterChainOptions.Read);
            }

            if (stream != null && stream.CanWrite)
            {
                stream.AddFilter(new GzipCompresionFilter(level, deflateMode), FilterChainOptions.Write);
            }

            return stream;
        }
Example #2
0
		public SocketStream(Socket socket, string openedPath, StreamContext context, bool isAsync = false)
			: base(null, StreamAccessOptions.Read | StreamAccessOptions.Write, openedPath, context)
		{
			Debug.Assert(socket != null);
			this.socket = socket;
			this.IsWriteBuffered = false;
			this.eof = false;
			this.isAsync = isAsync;
			this.IsReadBuffered = false;
		}
Example #3
0
		/// <summary>
		/// Creates a new <see cref="ExternalStream"/> with the given proxy object.
		/// </summary>
		/// <param name="proxy">Instance of a class derived from <see cref="MarshalByRefObject"/> that should
		/// serve as a proxy for this <see cref="ExternalStream"/>.</param>
		/// <param name="openingWrapper">The parent instance.</param>
		/// <param name="accessOptions">The additional options parsed from the <c>fopen()</c> mode.</param>
		/// <param name="openedPath">The absolute path to the opened resource.</param>
		/// <param name="context">The stream context passed to fopen().</param>
		internal ExternalStream(IExternalStream proxy, StreamWrapper openingWrapper, StreamAccessOptions accessOptions, string openedPath, StreamContext context)
			: base(openingWrapper, accessOptions, openedPath, context)
		{
			this.proxy = proxy;
		}
		/// <include file='Doc/Wrappers.xml' path='docs/method[@name="Open"]/*'/>
		public override PhpStream Open(ref string path, string mode, StreamOpenOptions options, StreamContext context)
		{
			Debug.Assert(path != null);
			//Debug.Assert(PhpPath.IsLocalFile(path));

			// Get the File.Open modes from the mode string
			FileMode fileMode;
			FileAccess fileAccess;
			StreamAccessOptions ao;

			if (!ParseMode(mode, options, out fileMode, out fileAccess, out ao)) return null;

			// Open the native stream
			this.storageFile = IsolatedStorageFile.GetUserStoreForApplication();
			FileStream stream = null;
			try
			{
				stream = new IsolatedStorageFileStream(path, fileMode, fileAccess, FileShare.ReadWrite | FileShare.Delete, storageFile);
			}
			catch (FileNotFoundException)
			{
				// Note: There may still be an URL in the path here.
				PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_file_not_exists",
					FileSystemUtils.StripPassword(path)));
				return null;
			}
			catch (IOException e)
			{
				if ((ao & StreamAccessOptions.Exclusive) > 0)
				{
					PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_file_exists",
						FileSystemUtils.StripPassword(path)));
				}
				else
				{
					PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_file_io_error",
						FileSystemUtils.StripPassword(path), PhpException.ToErrorMessage(e.Message)));
				}
				return null;
			}
			catch (UnauthorizedAccessException)
			{
				PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_file_access_denied",
					FileSystemUtils.StripPassword(path)));
				return null;
			}
			catch (Exception)
			{
				PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_file_invalid",
					FileSystemUtils.StripPassword(path)));
				return null;
			}

			if ((ao & StreamAccessOptions.SeekEnd) > 0)
			{
				// Read/Write Append is not supported. Seek to the end of file manually.
				stream.Seek(0, SeekOrigin.End);
			}

			if ((ao & StreamAccessOptions.Temporary) > 0)
			{
				// Set the file attributes to Temporary too.
				File.SetAttributes(path, FileAttributes.Temporary);
			}

			return new NativeStream(stream, this, ao, path, context);
		}
Example #5
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 (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;
		}
Example #6
0
		/// <summary>
		/// PhpStream is created by a StreamWrapper together with the
		/// encapsulated RawStream (the actual file opening is handled 
		/// by the wrapper).
		/// </summary>
		/// <remarks>
		/// This class newly implements the auto-remove behavior too
		/// (see <see cref="StreamAccessOptions.Temporary"/>).
		/// </remarks>
		/// <param name="openingWrapper">The parent instance.</param>
		/// <param name="accessOptions">The additional options parsed from the <c>fopen()</c> mode.</param>
		/// <param name="openedPath">The absolute path to the opened resource.</param>
		/// <param name="context">The stream context passed to fopen().</param>
		public PhpStream(StreamWrapper openingWrapper, StreamAccessOptions accessOptions, string openedPath, StreamContext context)
			: base(PhpStreamTypeName)
		{
			Debug.Assert(context != null);

			this.context = context;
			this.Wrapper = openingWrapper;
			this.OpenedPath = openedPath;

			// Stream modifiers (defined in open-time).
			this.Options = accessOptions;

			// Allocate the text conversion filters for this stream.
			if ((accessOptions & StreamAccessOptions.UseText) > 0)
			{
				if ((accessOptions & StreamAccessOptions.Read) > 0)
				{
					textReadFilter = new TextReadFilter();
				}
				if ((accessOptions & StreamAccessOptions.Write) > 0)
				{
					textWriteFilter = new TextWriteFilter();
				}
			}

			this.readTimeout = ScriptContext.CurrentContext.Config.FileSystem.DefaultSocketTimeout;
		}
Example #7
0
		/// <summary>
		/// Openes a PhpStream using the appropriate StreamWrapper.
		/// </summary>
		/// <param name="path">URI or filename of the resource to be opened.</param>
		/// <param name="mode">A file-access mode as passed to the PHP function.</param>
		/// <param name="options">A combination of <see cref="StreamOpenOptions"/>.</param>
		/// <param name="context">A valid StreamContext. Must not be <c>null</c>.</param>
		/// <returns></returns>
		public static PhpStream Open(string path, string mode, StreamOpenOptions options, StreamContext context)
		{
			if (context == null)
				throw new ArgumentNullException("context");

			StreamWrapper wrapper;
			if (!PhpStream.ResolvePath(ref path, out wrapper, CheckAccessMode.FileMayExist, (CheckAccessOptions)options))
				return null;

			return wrapper.Open(ref path, mode, options, context);

		}
Example #8
0
 public PhpUserStream(UserStreamWrapper/*!*/openingWrapper, StreamAccessOptions accessOptions, string openedPath, StreamContext context)
     : base(openingWrapper, accessOptions, openedPath, context)
 {
 }
Example #9
0
		public NativeStream(Stream nativeStream, StreamWrapper openingWrapper, StreamAccessOptions accessOptions, string openedPath, StreamContext context)
			: base(openingWrapper, accessOptions, openedPath, context)
		{
			Debug.Assert(nativeStream != null);
			this.stream = nativeStream;
		}
Example #10
0
			public override PhpStream Open(ref string path, string mode, StreamOpenOptions options, StreamContext context)
			{
				return null;
			}
Example #11
0
		/// <summary>
		/// Get the StreamContext from a handle representing either an isolated context or a PhpStream.
		/// </summary>
		/// <param name="stream_or_context">The PhpResource of either PhpStream or StreamContext type.</param>
		/// <param name="createContext">If true then a new context will be created at the place of <see cref="StreamContext.Default"/>.</param>
		/// <returns>The respective StreamContext.</returns>
		/// <exception cref="PhpException">If the first argument is neither a stream nor a context.</exception>
		private static StreamContext FromResource(PhpResource stream_or_context, bool createContext)
		{
			if ((stream_or_context != null) && (stream_or_context.IsValid))
			{
				// Get the context out of the stream
				PhpStream stream = stream_or_context as PhpStream;
				if (stream != null)
				{
					Debug.Assert(stream.Context != null);
					stream_or_context = stream.Context;
				}

				StreamContext context = stream_or_context as StreamContext;
				if (context == StreamContext.Default)
				{
					if (!createContext) return null;
					context = new StreamContext();
				}
				return context;
			}
			PhpException.Throw(PhpError.Warning, CoreResources.GetString("context_expected"));
			return null;
		}
Example #12
0
        public override PhpStream Open(ref string path, string mode, StreamOpenOptions options, StreamContext context)
        {
            //From filestreamwrapper
            Debug.Assert(path != null);
            //Debug.Assert(PhpPath.IsLocalFile(path));

            // Get the File.Open modes from the mode string
            FileMode fileMode;
            FileAccess fileAccess;
            StreamAccessOptions ao;

            if (!ParseMode(mode, options, out fileMode, out fileAccess, out ao)) return null;

            string[] arr = path.Split('#');
            string archive = arr[0];
            string entry = arr[1];

            // Open the native stream
            ZipFile zip = null;
            try
            {
                // stream = File.Open(path, fileMode, fileAccess, FileShare.ReadWrite);
                zip = new ZipFile(File.Open(archive, FileMode.Open, FileAccess.Read, FileShare.Read));
            }
            catch (FileNotFoundException)
            {
                // Note: There may still be an URL in the path here.
                PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_file_not_exists",
                    FileSystemUtils.StripPassword(path)));

                return null;
            }
            catch (IOException e)
            {
                if ((ao & StreamAccessOptions.Exclusive) > 0)
                {
                    PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_file_exists",
                        FileSystemUtils.StripPassword(path)));
                }
                else
                {
                    PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_file_io_error",
                        FileSystemUtils.StripPassword(path), PhpException.ToErrorMessage(e.Message)));
                }
                return null;
            }
            catch (UnauthorizedAccessException)
            {
                PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_file_access_denied",
                    FileSystemUtils.StripPassword(path)));
                return null;
            }
            catch (Exception)
            {
                PhpException.Throw(PhpError.Warning, CoreResources.GetString("stream_file_invalid",
                    FileSystemUtils.StripPassword(path)));
                return null;
            }

            if ((ao & StreamAccessOptions.SeekEnd) > 0)
            {
                throw new NotSupportedException();
            }

            if ((ao & StreamAccessOptions.Temporary) > 0)
            {
                // Set the file attributes to Temporary too.
                throw new NotSupportedException();
            }

            if (zip == null)
            {
                return null;
            }
            ZipEntry zEntry = zip.GetEntry(entry);
            if (zEntry == null)
            {
                return null;
            }
            Stream s = zip.GetInputStream(zEntry);
            return new NativeStream(s, this, ao, path, context);
        }
Example #13
0
		public static bool RemoveDirectory(string dirname, StreamContext context)
		{
			StreamWrapper wrapper;
			if (!PhpStream.ResolvePath(ref dirname, out wrapper, CheckAccessMode.Directory, CheckAccessOptions.Empty))
				return false;

			return wrapper.RemoveDirectory(dirname, StreamRemoveDirectoryOptions.Empty, StreamContext.Default);
		}