public async void Start(string szUrl, IInternetProtocolSink pOIProtSink, IInternetBindInfo pOIBindInfo, PI_FLAGS grfPI, int dwReserved)
        {
            var bytes = new byte[4096];

            try
            {
                using (var ms = new MemoryStream())
                    using (var stream = await _protocol.GetStreamAsync(szUrl))
                    {
                        while (true)
                        {
                            var n = await stream.ReadAsync(bytes, 0, bytes.Length);

                            if (n == 0)
                            {
                                data    = ms.ToArray();
                                readPos = 0;
                                pOIProtSink.ReportData(BSCF.BSCF_DATAFULLYAVAILABLE, (uint)ms.Length, 0);
                                pOIProtSink.ReportResult(NativeConstants.S_OK, 0, "");
                                break;
                            }

                            ms.Write(bytes, 0, n);
                        }
                    }
            }
            catch (Exception ex)
            {
                pOIProtSink.ReportResult(NativeConstants.E_FAIL, 0, ex.Message);
            }
        }
Beispiel #2
0
        public void Start(string szURL, IInternetProtocolSink Sink, IInternetBindInfo pOIBindInfo, uint grfPI, uint dwReserved)
        {
            //System.Diagnostics.Debugger.Launch();
            AspNetRequestData RequestData = new AspNetRequestData(Stream);

            try
            {
                BINDINFO BindInfo = GetBindInfo(pOIBindInfo);
                RequestData.Verb     = GetVerb(BindInfo);
                RequestData.PostData = GetPostData(BindInfo);

                IHttpNegotiate Negotiate = GetHttpNegotiate(Sink);
                string         strRequestHeaders;
                Negotiate.BeginningTransaction(szURL, string.Empty, 0, out strRequestHeaders);
                RequestData.SetRequestHeaders(strRequestHeaders);

                ProcessRequest(RequestData, szURL);

                string strNewResponseHeaders;
                Negotiate.OnResponse(200, RequestData.GetResponseHeaders(), strRequestHeaders, out strNewResponseHeaders);

                //This must be the size of the buffer.
                Sink.ReportData(BSCF.BSCF_LASTDATANOTIFICATION, (uint)Stream.Length, (uint)Stream.Length);

                Sink.ReportResult(0, RequestData.Status, RequestData.StatusDescription);
            }
            catch (Exception e)
            {
                WriteBasicMessage(e.Message + "<hr>" + e.StackTrace, "Error");
            }
        }
Beispiel #3
0
        public void Start(string szURL, IInternetProtocolSink sink, IInternetBindInfo pOIBindInfo, uint grfPI, uint dwReserved)
        {
            //Console.WriteLine("Start: {0}", szURL);
            var data = Reader(szURL, ReaderContext);

            if (data != null)
            {
                this.data = data;
                this.seek = 0;
                this.Sink = sink;
                sink.ReportData(8, 1, 1);
            }
            else
            {
                data = null;
                System.Runtime.InteropServices.Marshal.ThrowExceptionForHR(unchecked ((int)0x800C0007));
            }
            //var prefix = "nres://";
            //if (szURL != null && szURL.StartsWith(prefix))
            //{
            //  var name = szURL.Substring(prefix.Length).Trim('/', '\\').Replace('.', '_');

            //  data = (byte[])StarResource.ResourceManager.GetObject(name);
            //  seek = 0;
            //
            //  Sink.ReportData(8, 1, 1);
            //}
            //else
            //  data = null;
        }
        int IInternetProtocolEx.StartEx(IUri uri, IInternetProtocolSink protocolSink, IInternetBindInfo bindInfo, PI_FLAGS grfPI, uint dwReserved)
        {
            string szUrl;

            if (uri.GetAbsoluteUri(out szUrl) != NativeConstants.S_OK)
            {
                return(NativeConstants.INET_E_INVALID_URL);
            }

            return(Start(szUrl, protocolSink, bindInfo, grfPI, dwReserved));
        }
Beispiel #5
0
 public void Start(string szURL, IInternetProtocolSink Sink, IInternetBindInfo pOIBindInfo, uint grfPI, uint dwReserved)
 {
     Debug.WriteLine("#" + _id + " URL: " + "\t" + szURL);
     _dispatcher.Dispatcher.Invoke(
         () =>
     {
         Debug.WriteLine(
             "#" + _id + " original thread: " + _creatingTID + " calling thread " + Thread.CurrentThread.ManagedThreadId
             + " Start() "
             + Thread.CurrentThread.GetApartmentState());
         _wrapped.Start(szURL, Sink, pOIBindInfo, grfPI, dwReserved);
     });
 }
        public static IHttpNegotiate GetHttpNegotiate(IInternetProtocolSink Sink)
        {
            if ((Sink is IServiceProvider) == false)
            {
                throw new Exception("Error ProtocolSink does not support IServiceProvider.");
            }
            Debug.WriteLine("ServiceProvider");

            IServiceProvider Provider      = (IServiceProvider)Sink;
            object           obj_Negotiate = new object();

            Provider.QueryService(ref Guids.IID_IHttpNegotiate, ref Guids.IID_IHttpNegotiate, out obj_Negotiate);
            return((IHttpNegotiate)obj_Negotiate);
        }
Beispiel #7
0
        /// <summary>
        /// Initialize the content stream
        /// </summary>
        /// <param name="szURL">URL called</param>
        /// <param name="sink"></param>
        /// <param name="pOIBindInfo"></param>
        /// <param name="grfPI"></param>
        /// <param name="dwReserved"></param>
        /// <remarks>
        /// The name of the resource is defined from the url. content stream is filled with resource stream. content-type is defined from file extension.
        /// </remarks>
        public void Start(string szURL, IInternetProtocolSink sink, IInternetBindInfo pOIBindInfo, uint grfPI, uint dwReserved)
        {
            try
            {
                Assembly     assembly     = Assembly.GetExecutingAssembly();
                AssemblyName assemblyName = assembly.GetName();

                UriBuilder uriBuilder = new UriBuilder(szURL);

                string resourcePath = assemblyName.Name + ".Resources" + uriBuilder.Path.Replace("/", ".");

                Stream s = assembly.GetManifestResourceStream(resourcePath);

                byte[] buffer = new byte[s.Length];
                int    nb     = s.Read(buffer, 0, buffer.Length);
                this._stream.Write(buffer, 0, nb);
                this._stream.Position = 0;

                string contentType = "text/html";
                switch (uriBuilder.Path.Substring(uriBuilder.Path.Length - 3))
                {
                case "png":
                    contentType = "image/png";
                    break;

                case "gif":
                    contentType = "image/gif";
                    break;

                case "css":
                    contentType = "text/css";
                    break;

                case "eot":
                    contentType = "application/font-woff";
                    break;
                }

                sink.ReportProgress((uint)BINDSTATUS.VERFIEDMIMETYPEAVAILABLE, contentType);

                sink.ReportData(BSCF.BSCF_LASTDATANOTIFICATION, (uint)this._stream.Length, (uint)this._stream.Length);
                sink.ReportResult(0, 200, null);
            }
            catch (Exception ex)
            {
                sink.ReportResult(E_FAIL, 0, ex.Message);
            }
        }
        public void Start(string szURL, IInternetProtocolSink Sink, IInternetBindInfo pOIBindInfo, uint grfPI, uint dwReserved)
        {
            Debug.WriteLine("Start:" + szURL, "Info");
            try
            {
                if (Sink is IServiceProvider)
                {
                    Debug.WriteLine("ServiceProvider");
                    IServiceProvider Provider      = (IServiceProvider)Sink;
                    object           obj_Negotiate = new object();
                    Provider.QueryService(ref Guids.IID_IHttpNegotiate, ref Guids.IID_IHttpNegotiate, out obj_Negotiate);
                    IHttpNegotiate Negotiate = (IHttpNegotiate)obj_Negotiate;

                    string strNewHeaders;
                    Negotiate.BeginningTransaction(szURL, string.Empty, 0, out strNewHeaders);
                    Debug.WriteLine(strNewHeaders);

                    using (var resourceStream = _embeddedResourceMap.GetStream(szURL))
                    {
                        if (resourceStream == null)
                        {
                            StreamWriter Writer = new StreamWriter(Stream);
                            Writer.Write("<html><body><p>Cannot find resource: {0}</p></body></html>", szURL);
                            Writer.Flush();
                            Stream.Position = 0;
                        }
                        else
                        {
                            resourceStream.CopyTo(Stream);
                            Stream.Position = 0;
                        }
                    }

                    string StrResponseHeaders = string.Format("HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length:{0}\r\n\r\n", Stream.Length);
                    string strNewResponseHeaders;
                    Negotiate.OnResponse(200, StrResponseHeaders, strNewHeaders, out strNewResponseHeaders);
                    Debug.WriteLine(strNewResponseHeaders);
                }

                Sink.ReportData(BSCF.BSCF_LASTDATANOTIFICATION, (uint)Stream.Length, (uint)Stream.Length);
                Sink.ReportResult(0, 200, null);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
            }
        }
		public void Start(string szURL, IInternetProtocolSink Sink, IInternetBindInfo pOIBindInfo, uint grfPI, uint dwReserved)
		{
			Debug.WriteLine("Start:" + szURL, "Info");
			try
			{
				if (Sink is IServiceProvider)
				{
					Debug.WriteLine("ServiceProvider");
					IServiceProvider Provider = (IServiceProvider)Sink;
					object obj_Negotiate = new object();
					Provider.QueryService(ref Guids.IID_IHttpNegotiate, ref Guids.IID_IHttpNegotiate, out obj_Negotiate);
					IHttpNegotiate Negotiate = (IHttpNegotiate)obj_Negotiate;

					string strNewHeaders;
					Negotiate.BeginningTransaction(szURL, string.Empty, 0, out strNewHeaders);
					Debug.WriteLine(strNewHeaders);

					using (var resourceStream = _embeddedResourceMap.GetStream(szURL))
					{
						if (resourceStream == null)
						{
							StreamWriter Writer = new StreamWriter(Stream);
							Writer.Write("<html><body><p>Cannot find resource: {0}</p></body></html>", szURL);
							Writer.Flush();
							Stream.Position = 0;
						}
						else
						{
							resourceStream.CopyTo(Stream);
							Stream.Position = 0;
						}
					}

					string StrResponseHeaders = string.Format("HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length:{0}\r\n\r\n", Stream.Length);
					string strNewResponseHeaders;
					Negotiate.OnResponse(200, StrResponseHeaders, strNewHeaders, out strNewResponseHeaders);
					Debug.WriteLine(strNewResponseHeaders);
				}

				Sink.ReportData(BSCF.BSCF_LASTDATANOTIFICATION, (uint)Stream.Length, (uint)Stream.Length);
				Sink.ReportResult(0, 200, null);
			}
			catch (Exception e)
			{
				Debug.WriteLine(e.Message);
			}
		}
        public void Start(string szURL, IInternetProtocolSink Sink, IInternetBindInfo pOIBindInfo, uint grfPI, uint dwReserved)
        {
            Debug.WriteLine("Start:" + szURL, "Info");
            try
            {
                if (Sink is IServiceProvider)
                {
                    Debug.WriteLine("ServiceProvider");
                    IServiceProvider Provider      = (IServiceProvider)Sink;
                    object           obj_Negotiate = new object();
                    Provider.QueryService(ref Guids.IID_IHttpNegotiate, ref Guids.IID_IHttpNegotiate, out obj_Negotiate);
                    IHttpNegotiate Negotiate = (IHttpNegotiate)obj_Negotiate;

                    string strNewHeaders;
                    Negotiate.BeginningTransaction(szURL, string.Empty, 0, out strNewHeaders);
                    Debug.WriteLine(strNewHeaders);

                    StreamWriter Writer = new StreamWriter(Stream);
                    int          loc    = szURL.IndexOf(':');
                    if (loc >= 0)
                    {
                        Writer.Write(string.Format("<HTML><BODY>{0}</BODY></HTML>", System.Web.HttpUtility.UrlDecode(szURL.Remove(0, loc + 1))));
                    }
                    else
                    {
                        Writer.Write(string.Format("<HTML><BODY>{0}</BODY></HTML>", System.Web.HttpUtility.UrlDecode(szURL)));
                    }
                    Writer.Flush();
                    Stream.Position = 0;

                    string StrResponseHeaders = string.Format("HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length:{0}\r\n\r\n", Stream.Length);
                    string strNewResponseHeaders;
                    Negotiate.OnResponse(200, StrResponseHeaders, strNewHeaders, out strNewResponseHeaders);
                    Debug.WriteLine(strNewResponseHeaders);
                }

                Sink.ReportData(BSCF.BSCF_LASTDATANOTIFICATION, (uint)Stream.Length, (uint)Stream.Length);
                Sink.ReportResult(0, 200, null);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
            }
        }
Beispiel #11
0
		public void Start(string url, IInternetProtocolSink protSink,
			IInternetBindInfo pOIBindInfo, uint grfPI, uint dwReserved)
		{
			Resource resource;
			try
			{
				resource = _provider.GetData(url);
			}
			catch (Exception e)
			{
				resource = new Resource(MediaTypeNames.Text.Html, e.ToString());
			}

			_resourceReader = resource.GetReader();

			protSink.ReportProgress(BINDSTATUS.BINDSTATUS_VERIFIEDMIMETYPEAVAILABLE, resource.MimeType);
			protSink.ReportData(BSCF.BSCF_DATAFULLYAVAILABLE, 1, 1);
			protSink.ReportResult(InteropConstants.S_OK, 0, null);
		}
Beispiel #12
0
        public void Start(string url, IInternetProtocolSink protSink,
                          IInternetBindInfo pOIBindInfo, uint grfPI, uint dwReserved)
        {
            Resource resource;

            try
            {
                resource = _provider.GetData(url);
            }
            catch (Exception e)
            {
                resource = new Resource(MediaTypeNames.Text.Html, e.ToString());
            }

            _resourceReader = resource.GetReader();

            protSink.ReportProgress(BINDSTATUS.BINDSTATUS_VERIFIEDMIMETYPEAVAILABLE, resource.MimeType);
            protSink.ReportData(BSCF.BSCF_DATAFULLYAVAILABLE, 1, 1);
            protSink.ReportResult(InteropConstants.S_OK, 0, null);
        }
Beispiel #13
0
        public void Start(string url, IInternetProtocolSink sink, IInternetBindInfo pOIBindInfo, uint grfPI, uint dwReserved)
        {
            //var bindInfo = GetBindInfo(pOIBindInfo);
            var    neg = GetHttpNegotiate(sink);
            string requestHeaders;

            neg.BeginningTransaction(url, string.Empty, 0, out requestHeaders);
            Debug.WriteLine(requestHeaders);

            string contentType;
            var    data = this.GetUrlData(url, out contentType);

            if (data != null)
            {
                //var buff = new byte[responseStream.Length];
                //responseStream.Read(buff, 0, buff.Length);
                //this.Stream.Position = 0;
                //this.Stream.Write(buff, 0, buff.Length);
                this.Data = data;
            }
            else
            {
                Data = Encoding.UTF8.GetBytes("Page not found!");
            }

            var responseHeaders = string.Format("HTTP/1.1 200 OK\r\n" +
                                                "Content-Type: {0}\r\n" +
                                                "Content-Length:{1}\r\n\r\n", contentType, Data.Length);
            string newResponseHeaders;
            var    hresult = neg.OnResponse(200, responseHeaders, requestHeaders, out newResponseHeaders);

            if (hresult != 0)
            {
                Debug.Write("IHttpNegotiate::OnResponse result = " + hresult);
            }
            sink.ReportData(BSCF.BSCF_LASTDATANOTIFICATION, (uint)Data.Length, (uint)Data.Length);
            sink.ReportResult(0, 200, null);
        }
        private int Start(string szUrl, IInternetProtocolSink protocolSink, IInternetBindInfo bindInfo, PI_FLAGS grfPI, uint dwReserved)
        {
            ClearData();

            currentProtocolSink = protocolSink;
            currentUrl          = szUrl;

            BINDINFO bindInfoData = new BINDINFO();

            bindInfoData.cbSize = (uint)Marshal.SizeOf(bindInfoData);
            bindInfo.GetBindInfo(out currentBindFlags, ref bindInfoData);

            if ((grfPI & PI_FLAGS.PI_FORCE_ASYNC) != 0)
            {
                PROTOCOLDATA protocolData = new PROTOCOLDATA();
                protocolData.grfFlags = PI_FLAGS.PI_FORCE_ASYNC;
                protocolSink.Switch(ref protocolData);
                return(NativeConstants.E_PENDING);
            }
            else
            {
                return(DoBind());
            }
        }
        private int Start(string szUrl, IInternetProtocolSink protocolSink, IInternetBindInfo bindInfo, PI_FLAGS grfPI, uint dwReserved)
        {
            ClearData();

            currentProtocolSink = protocolSink;
            currentUrl = szUrl;

            BINDINFO bindInfoData = new BINDINFO();
            bindInfoData.cbSize = (uint)Marshal.SizeOf(bindInfoData);
            bindInfo.GetBindInfo(out currentBindFlags, ref bindInfoData);

            if ((grfPI & PI_FLAGS.PI_FORCE_ASYNC) != 0)
            {
                PROTOCOLDATA protocolData = new PROTOCOLDATA();
                protocolData.grfFlags = PI_FLAGS.PI_FORCE_ASYNC;
                protocolSink.Switch(ref protocolData);
                return NativeConstants.E_PENDING;
            }
            else
            {
                return DoBind();
            }
        }
        int IInternetProtocolEx.StartEx(IUri uri, IInternetProtocolSink protocolSink, IInternetBindInfo bindInfo, PI_FLAGS grfPI, uint dwReserved)
        {
            string szUrl;
            if (uri.GetAbsoluteUri(out szUrl) != NativeConstants.S_OK)
                return NativeConstants.INET_E_INVALID_URL;

            return Start(szUrl, protocolSink, bindInfo, grfPI, dwReserved);
        }
 int IInternetProtocolEx.Start(string szUrl, IInternetProtocolSink protocolSink, IInternetBindInfo bindInfo, PI_FLAGS grfPI, uint dwReserved)
 {
     return Start(szUrl, protocolSink, bindInfo, grfPI, dwReserved);
 }
        public void Start(string szURL, IInternetProtocolSink Sink, IInternetBindInfo pOIBindInfo, uint grfPI, uint dwReserved)
        {
            // How to do more complex stuff: http://www.codeproject.com/Articles/6120/A-Simple-protocol-to-view-aspx-pages-without-IIS-i
              var isAllowed = _urlFilter.IsAllowed (szURL);
              if (!isAllowed)
              {
            Debug.WriteLine ("is not allowed", szURL);
            Sink.ReportResult (0, 403, "Forbidden");
            LockRequest (0);
            Terminate (0);
            UnlockRequest();
              }

             //Sink.ReportProgress(tagBINDSTATUS.BINDSTATUS_MIMETYPEAVAILABLE, "text/html");
             // Sink.ReportResult (HResult.INET_E_REDIRECT_FAILED, 0,   );
              _dispatcher.Dispatcher.Invoke (() => _wrapped.Start (szURL, Sink, pOIBindInfo, grfPI, dwReserved));
        }
        public void Start(string szURL, IInternetProtocolSink Sink, IInternetBindInfo pOIBindInfo, uint grfPI, uint dwReserved)
        {
            if (_size != 0)
            throw new InvalidOperationException ("nope");

              #region HTTPCLIENT

              //_currentUrl = szURL;
              //Uri uri;
              //if (!(Uri.TryCreate (szURL, UriKind.RelativeOrAbsolute, out uri) && _urlFilter.IsAllowed (uri)))
              //{
              //  Sink.ReportResult (0, (uint) HttpStatusCode.NotFound, HttpStatusCode.NotFound.ToString());
              //  return;
              //}
              //var httpClient = new HttpClient();
              //var httpRequestMessage = new HttpRequestMessage { RequestUri = uri };
              //var bindInfo = GetBindInfo (pOIBindInfo);
              //var negotiate = GetHttpNegotiate (Sink);

              ////"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)";
              //var postData = GetPostData (bindInfo);

              //string strRequestHeaders;
              //negotiate.BeginningTransaction (szURL, string.Empty, 0, out strRequestHeaders);
              //foreach (
              //    var header in
              //        Regex.Split (strRequestHeaders, c_httpHeaderSplitCharacters).Where (
              //            s => !string.IsNullOrEmpty (s)
              //                 && !s_restrictedHeaders.Contains (s.Split (':').First())))
              //{
              //  var splitHeader = header.Split (':');
              //  var key = splitHeader[0];
              //  var value = splitHeader[1];
              //  httpRequestMessage.Headers.Add (key, value);
              //}

              //switch (bindInfo.dwBindVerb)
              //{
              //  case BINDVERB.BINDVERB_GET:
              //    httpRequestMessage.Method = HttpMethod.Get;
              //    break;

              //  case BINDVERB.BINDVERB_POST:
              //    httpRequestMessage.Method = HttpMethod.Post;
              //    httpRequestMessage.Content = new ByteArrayContent (postData);
              //    break;

              //  case BINDVERB.BINDVERB_PUT:
              //    httpRequestMessage.Method = HttpMethod.Put;
              //    break;
              //    //case BINDVERB.BINDVERB_CUSTOM: // ???
              //    //  break;
              //  default:
              //    throw new ArgumentOutOfRangeException();
              //}

              //var response = httpClient.SendAsync (httpRequestMessage, HttpCompletionOption.ResponseHeadersRead);
              ////response.ContinueWith (
              ////    task =>
              ////    {

              //var task = response;
              //task.Wait();
              //      var status = (uint)HttpStatusCode.NotFound;
              //      var message = HttpStatusCode.NotFound.ToString();

              //      if (!task.IsFaulted)
              //      {
              //        var result = task.Result;
              //        string strNewResponseHeaders;
              //        negotiate.OnResponse (0, result.Headers.ToString(), result.Headers.ToString(), out strNewResponseHeaders);
              //        if (result.IsSuccessStatusCode)
              //        {
              //          result.Content.ReadAsStreamAsync().ContinueWith(t => ResponseStream = t.Result);
              //          Sink.ReportData (BSCF.BSCF_LASTDATANOTIFICATION, (uint)result.Content.Headers.ContentLength, (uint)result.Content.Headers.ContentLength);
              //        }
              //        status = (uint) result.StatusCode;
              //        message = result.ReasonPhrase;
              //      }

              //      Sink.ReportResult (0, status, message);
              //    //});

              //if (!_urlFilter.IsAllowed (_httpResponse.ResponseUri))
              //  throw new Exception ("not allowed!"); // TODO - do something useful here

              #endregion

              #region WebRequest

              Debug.WriteLine ("starting url: " + szURL);

              _currentUrl = szURL;
              // How to do more complex stuff: http://www.codeproject.com/Articles/6120/A-Simple-protocol-to-view-aspx-pages-without-IIS-i
              Uri uri;

              if (!(Uri.TryCreate (szURL, UriKind.RelativeOrAbsolute, out uri) && _urlFilter.IsAllowed (uri)))
              {
            Sink.ReportResult (0, (uint) HttpStatusCode.NotFound, HttpStatusCode.NotFound.ToString());
            return;
              }
              var bindInfo = GetBindInfo (pOIBindInfo);
              var postData = GetPostData (bindInfo);

              string method;

              //_webRequest = (HttpWebRequest) WebRequest.Create (uri);
              switch (bindInfo.dwBindVerb)
              {
            case BINDVERB.BINDVERB_GET:
              method = HttpMethod.Get.Method;
              break;

            case BINDVERB.BINDVERB_POST:
              method = HttpMethod.Post.Method;
              break;

            case BINDVERB.BINDVERB_PUT:
              method = HttpMethod.Put.Method;
              break;
              //case BINDVERB.BINDVERB_CUSTOM: // ???
              //  break;
            default:
              throw new ArgumentOutOfRangeException();
              }

              //_webRequest.KeepAlive = false;
              ThreadPool.QueueUserWorkItem (
              obj =>
              {
            if (postData.Length > 0)
            {
              using (var requestStream = _webRequest.GetRequestStream())
              {
                requestStream.Write (postData, 0, postData.Length);
              }
              _webRequest.ContentLength = postData.Length;
            }
            _webRequest = (HttpWebRequest) WebRequest.Create (uri);
            _webRequest.Method = method;
            _webRequest.UserAgent = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)";
            _webRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

            var negotiate = GetHttpNegotiate (Sink);

            string strRequestHeaders;
            negotiate.BeginningTransaction (szURL, string.Empty, 0, out strRequestHeaders);
            foreach (
                var header in
                    Regex.Split (strRequestHeaders, c_httpHeaderSplitCharacters).Where (
                        s => !string.IsNullOrEmpty (s)
                             && !s_restrictedHeaders.Contains (s.Split (':').First())))
            {
              _webRequest.Headers.Add (header);
            }

            try
            {
              Debug.WriteLine ("Waiting for respsonse from " + _currentUrl);
              _httpResponse = (HttpWebResponse) _webRequest.GetResponse();

              Sink.ReportProgress (tagBINDSTATUS.BINDSTATUS_FINDINGRESOURCE, _currentUrl);
              Sink.ReportProgress (tagBINDSTATUS.BINDSTATUS_CONNECTING, _currentUrl);
              Sink.ReportProgress (tagBINDSTATUS.BINDSTATUS_SENDINGREQUEST, _currentUrl);
              Sink.ReportProgress (tagBINDSTATUS.BINDSTATUS_VERIFIEDMIMETYPEAVAILABLE, _httpResponse.ContentType);

              //_httpResponse.
              //if (!_urlFilter.IsAllowed (_httpResponse.ResponseUri))
              //  throw new Exception ("not allowed!"); // TODO - do something useful here

              Sink.ReportData (BSCF.BSCF_FIRSTDATANOTIFICATION, 0, (uint) _httpResponse.ContentLength);
              string strNewResponseHeaders;
              negotiate.OnResponse (0, _httpResponse.Headers.ToString(), strRequestHeaders, out strNewResponseHeaders);
              _responseStream = _httpResponse.GetResponseStream();
              Sink.ReportData (BSCF.BSCF_AVAILABLEDATASIZEUNKNOWN, (uint) _httpResponse.ContentLength, (uint) _httpResponse.ContentLength);
              Sink.ReportResult (0, (uint) _httpResponse.StatusCode, _httpResponse.StatusDescription);
            }
            catch (Exception ex)
            {
              Debug.WriteLine ("exception while retrieving " + _currentUrl + " " + ex);
              Sink.ReportResult (0, (uint) HttpStatusCode.NotFound, HttpStatusCode.NotFound.ToString());
              Dispose();
            }
              });

              #endregion
        }
 public void Start(string szURL, IInternetProtocolSink Sink, IInternetBindInfo pOIBindInfo, uint grfPI, uint dwReserved)
 {
     // How to do more complex stuff: http://www.codeproject.com/Articles/6120/A-Simple-protocol-to-view-aspx-pages-without-IIS-i
       _currentUrl = szURL;
       _isAllowed = _urlFilter.IsAllowed (szURL);
       if (!_isAllowed)
       {
     Sink.ReportResult (HResult.INET_E_RESOURCE_NOT_FOUND, (uint) HttpStatusCode.NotFound, HttpStatusCode.NotFound.ToString());
     return;
       }
       _dispatcher.Invoke (() => _wrapped.Start (szURL, Sink, pOIBindInfo, grfPI, dwReserved), new TimeSpan (0, 0, 0, 30));
 }
        private IHttpNegotiate GetHttpNegotiate(IInternetProtocolSink Sink)
        {
            if ((Sink is IServiceProvider) == false)
            throw new Exception ("Error ProtocolSink does not support IServiceProvider.");

              Debug.WriteLine ("ServiceProvider");

              IServiceProvider Provider = (IServiceProvider) Sink;
              object obj_Negotiate = new object();
              Provider.QueryService (ref Guids.IID_IHttpNegotiate, ref Guids.IID_IHttpNegotiate, out obj_Negotiate);
              return (IHttpNegotiate) obj_Negotiate;
        }
        public void Start(string szURL, IInternetProtocolSink sink, IInternetBindInfo pOIBindInfo, uint grfPI, uint dwReserved)
        {
            //Debug.WriteLine("xxHelpAsyncPluggableProtocolHandler.Start(" + szURL + ")");

            String mimeType = "text/html";
                // type = "text" / "image" / "audio" / "video" / "application" / extension-token
                //type/subtype eg. "text/html", "image/png", "image/gif", "video/mpeg", "text/css", and "audio/basic"

            if (MsxhelpProtocol.Catalog == null || !MsxhelpProtocol.Catalog.IsOpen)
            {
                _stream = null;
            }
            else
            {
                try
                {
                    if (_customRenderer == null)
                        _customRenderer = CustomRenderer.Create();

                    String topicID;
                    Boolean isTopicUrl = _customRenderer.IsTopicUrl(szURL, out topicID);

                    // -----------------------------------------------------------------------
                    // debug - Host wants to see raw HTML from .mshc

                    if (MsxhelpProtocol .RawCodeHandler != null)
                    {
                        try
                        {
                            if (isTopicUrl && String.IsNullOrEmpty(MsxhelpProtocol.UserTopicText))  // Topic with no text overload
                            {
                                _stream = _customRenderer.UrlToStream(szURL, false);  // false = No Render.
                                if (this._stream != null)
                                {
                                    _stream.Position = 0;
                                    StreamReader reader = new StreamReader(_stream);
                                    String text = reader.ReadToEnd();
                                    MsxhelpProtocol.RawCodeHandler(text);    //send text to main form
                                    this._stream.Close();
                                    this._stream = null;
                                }
                            }
                        }
                        catch
                        {
                            //suck it up.. the next bit is the important part
                        }
                    }

                    // -----------------------------------------------------------------------
                    // render - Web browser wants rendered code

            //                    if (MsxhelpProtocol.RenderUsingVS)  // Requires VS 11 DLL (Microsoft.VisualStudio.Help.DLL)
            //                    {
            //                        if (_vsRenderer == null)                      //will crash if VS not installed
            //                            _vsRenderer = new TopicRenderer();

             //                       _stream = (Stream)_vsRenderer.ProcessLink(szURL, (ICatalog)MsxhelpProtocol.Catalog, null/*_renderParameters*/);
            //                    }
            //                    else  // basic render code supplied with this SDK -- Good for Win 8 where VS 11 not installed
                    {
                        _stream = _customRenderer.UrlToStream(szURL);
                        _stream.Position = 0;
                    }
                }
                catch
                {
                    _stream = null;
                }
            }

            if (_stream != null)
            {
                //Set Mime type
                uint BINDSTATUS_MIMETYPEAVAILABLE = 13;
                if (mimeType != "")
                    sink.ReportProgress(BINDSTATUS_MIMETYPEAVAILABLE, mimeType);

                sink.ReportData(BSCF.LASTDATANOTIFICATION | BSCF.DATAFULLYAVAILABLE, (uint)_stream.Length, (uint)_stream.Length);
                sink.ReportResult((uint)HRESULT.S_OK, 200, null);
            }
            else
                sink.ReportResult((uint)HRESULT.INET_E_OBJECT_NOT_FOUND, 404, "Cannot find the goods");
        }
    public void Start(string szURL, IInternetProtocolSink sink, IInternetBindInfo pOIBindInfo, uint grfPI, uint dwReserved)
    {
      //Console.WriteLine("Start: {0}", szURL);
      var data = Reader(szURL, ReaderContext);
      if (data != null)
      {
        this.data = data;
        this.seek = 0;
        this.Sink = sink;
        sink.ReportData(8, 1, 1);
      }
      else
      {
        data = null;
        System.Runtime.InteropServices.Marshal.ThrowExceptionForHR(unchecked((int)0x800C0007));
      }
      //var prefix = "nres://";
      //if (szURL != null && szURL.StartsWith(prefix))
      //{
      //  var name = szURL.Substring(prefix.Length).Trim('/', '\\').Replace('.', '_');

      //  data = (byte[])StarResource.ResourceManager.GetObject(name);
      //  seek = 0;
      //  
      //  Sink.ReportData(8, 1, 1);
      //}
      //else
      //  data = null;
    }
 int IInternetProtocolEx.Start(string szUrl, IInternetProtocolSink protocolSink, IInternetBindInfo bindInfo, PI_FLAGS grfPI, uint dwReserved)
 {
     return(Start(szUrl, protocolSink, bindInfo, grfPI, dwReserved));
 }
Beispiel #25
0
        public void Start(string szURL, IInternetProtocolSink sink, IInternetBindInfo pOIBindInfo, uint grfPI, uint dwReserved)
        {
            //Debug.WriteLine("xxHelpAsyncPluggableProtocolHandler.Start(" + szURL + ")");

            String mimeType = "text/html";

            // type = "text" / "image" / "audio" / "video" / "application" / extension-token
            //type/subtype eg. "text/html", "image/png", "image/gif", "video/mpeg", "text/css", and "audio/basic"

            if (MsxhelpProtocol.Catalog == null || !MsxhelpProtocol.Catalog.IsOpen)
            {
                _stream = null;
            }
            else
            {
                try
                {
                    if (_customRenderer == null)
                    {
                        _customRenderer = CustomRenderer.Create();
                    }

                    String  topicID;
                    Boolean isTopicUrl = _customRenderer.IsTopicUrl(szURL, out topicID);

                    // -----------------------------------------------------------------------
                    // debug - Host wants to see raw HTML from .mshc

                    if (MsxhelpProtocol.RawCodeHandler != null)
                    {
                        try
                        {
                            if (isTopicUrl && String.IsNullOrEmpty(MsxhelpProtocol.UserTopicText)) // Topic with no text overload
                            {
                                _stream = _customRenderer.UrlToStream(szURL, false);               // false = No Render.
                                if (this._stream != null)
                                {
                                    _stream.Position = 0;
                                    StreamReader reader = new StreamReader(_stream);
                                    String       text   = reader.ReadToEnd();
                                    MsxhelpProtocol.RawCodeHandler(text);    //send text to main form
                                    this._stream.Close();
                                    this._stream = null;
                                }
                            }
                        }
                        catch
                        {
                            //suck it up.. the next bit is the important part
                        }
                    }

                    // -----------------------------------------------------------------------
                    // render - Web browser wants rendered code

//                    if (MsxhelpProtocol.RenderUsingVS)  // Requires VS 11 DLL (Microsoft.VisualStudio.Help.DLL)
//                    {
//                        if (_vsRenderer == null)                      //will crash if VS not installed
//                            _vsRenderer = new TopicRenderer();

                    //                       _stream = (Stream)_vsRenderer.ProcessLink(szURL, (ICatalog)MsxhelpProtocol.Catalog, null/*_renderParameters*/);
//                    }
//                    else  // basic render code supplied with this SDK -- Good for Win 8 where VS 11 not installed
                    {
                        _stream          = _customRenderer.UrlToStream(szURL);
                        _stream.Position = 0;
                    }
                }
                catch
                {
                    _stream = null;
                }
            }

            if (_stream != null)
            {
                //Set Mime type
                uint BINDSTATUS_MIMETYPEAVAILABLE = 13;
                if (mimeType != "")
                {
                    sink.ReportProgress(BINDSTATUS_MIMETYPEAVAILABLE, mimeType);
                }

                sink.ReportData(BSCF.LASTDATANOTIFICATION | BSCF.DATAFULLYAVAILABLE, (uint)_stream.Length, (uint)_stream.Length);
                sink.ReportResult((uint)HRESULT.S_OK, 200, null);
            }
            else
            {
                sink.ReportResult((uint)HRESULT.INET_E_OBJECT_NOT_FOUND, 404, "Cannot find the goods");
            }
        }
        private int DoBind()
        {
            currentProtocolSink.ReportProgress(BINDSTATUS.BINDSTATUS_FINDINGRESOURCE, currentUrl);
            currentProtocolSink.ReportProgress(BINDSTATUS.BINDSTATUS_CONNECTING, "Gallio Navigator.");

            bool success = false;
            try
            {
                GallioNavigatorCommand command = GallioNavigatorCommand.ParseUri(currentUrl);
                if (command != null)
                {

                    if (command.Name == "openAttachment")
                    {
                        string path = command.Arguments["path"];
                        if (!string.IsNullOrEmpty(path))
                        {
                            currentProtocolSink.ReportProgress(BINDSTATUS.BINDSTATUS_SENDINGREQUEST, Path.GetFileName(path));
                            success = StartOpenAttachmentCommand(path);
                        }
                    }
                    else
                    {
                        currentProtocolSink.ReportProgress(BINDSTATUS.BINDSTATUS_SENDINGREQUEST, command.Name);

                        var engine = new GallioNavigatorEngine(true);
                        success = command.Execute(engine);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(String.Format("Failed to process Uri '{0}' due to an exception: {1}.", currentUrl, ex));
            }

            LockData();

            int hr;
            if (success)
            {
                if (data != null && (currentBindFlags & BINDF.BINDF_NOWRITECACHE) == 0)
                {
                    uint dataLength = (uint)data.Length;

                    // Provide mime type.
                    if (dataMimeType != null)
                    {
                        currentProtocolSink.ReportProgress(BINDSTATUS.BINDSTATUS_VERIFIEDMIMETYPEAVAILABLE, dataMimeType);
                    }

                    // Determine whether we need to provide the path to the local file.
                    if ((currentBindFlags & BINDF.BINDF_NEEDFILE) != 0 && dataPath != null)
                    {
#if false // Not needed at the moment since the file we provide does not need to be in the cache.
          // Keeping this code in case we decide to provide dynamic content later.
                        StringBuilder cacheFilePathBuilder = new StringBuilder(NativeConstants.MAX_PATH);
                        string extension = Path.GetExtension(dataPath);
                        if (extension.Length != 0)
                            extension = extension.Substring(1); // strip leading '.'

                        NativeMethods.CreateUrlCacheEntry(currentUrl, dataLength, extension, cacheFilePathBuilder, 0);
                        string cacheFilePath = cacheFilePathBuilder.ToString();

                        DateTime now = DateTime.Now;
                        var nowTime = new System.Runtime.InteropServices.ComTypes.FILETIME()
                        {
                            dwHighDateTime = (int) (now.Ticks >> 32),
                            dwLowDateTime = (int) now.Ticks
                        };

                        const string headers = "HTTP/1.0 200 OK\r\n\r\n";
                        File.Copy(dataPath, cacheFilePath, true);
                        NativeMethods.CommitUrlCacheEntry(currentUrl, cacheFilePath,
                            nowTime,
                            nowTime,
                            NativeConstants.NORMAL_CACHE_ENTRY,
                            headers, (uint)headers.Length,
                            extension, null);

                        currentProtocolSink.ReportProgress(BINDSTATUS.BINDSTATUS_CACHEFILENAMEAVAILABLE, cacheFilePath);
#else
                        currentProtocolSink.ReportProgress(BINDSTATUS.BINDSTATUS_CACHEFILENAMEAVAILABLE, dataPath);
#endif
                    }

                    // Report all data available.
                    currentProtocolSink.ReportData(BSCF.BSCF_FIRSTDATANOTIFICATION | BSCF.BSCF_LASTDATANOTIFICATION | BSCF.BSCF_DATAFULLYAVAILABLE, dataLength, dataLength);

                    hr = NativeConstants.S_OK;
                }
                else
                {
                    // Aborts the navigation.
                    hr = NativeConstants.INET_E_DATA_NOT_AVAILABLE;
                }
            }
            else
            {
                // Reports an invalid Url.
                hr = NativeConstants.INET_E_INVALID_URL;
            }

            currentProtocolSink.ReportResult(hr, 0, null);
            currentProtocolSink = null;

            UnlockData();
            return hr;
        }
Beispiel #27
0
        public async void Start(string szUrl, IInternetProtocolSink pOIProtSink, IInternetBindInfo pOIBindInfo, PI_FLAGS grfPI, int dwReserved)
        {
            var bytes = new byte[4096];

            try
            {
                using (var ms = new MemoryStream())
                using (var stream = await _protocol.GetStreamAsync(szUrl))
                {
                    while (true)
                    {
                        var n = await stream.ReadAsync(bytes, 0, bytes.Length);
                        if (n == 0)
                        {
                            data = ms.ToArray();
                            readPos = 0;
                            pOIProtSink.ReportData(BSCF.BSCF_DATAFULLYAVAILABLE, (uint)ms.Length, 0);
                            pOIProtSink.ReportResult(NativeConstants.S_OK, 0, "");
                            break;
                        }

                        ms.Write(bytes, 0, n);
                    }
                }
            }
            catch (Exception ex)
            {
                pOIProtSink.ReportResult(NativeConstants.E_FAIL, 0, ex.Message);
            }
        }
        private int DoBind()
        {
            currentProtocolSink.ReportProgress(BINDSTATUS.BINDSTATUS_FINDINGRESOURCE, currentUrl);
            currentProtocolSink.ReportProgress(BINDSTATUS.BINDSTATUS_CONNECTING, "Gallio Navigator.");

            bool success = false;

            try
            {
                GallioNavigatorCommand command = GallioNavigatorCommand.ParseUri(currentUrl);
                if (command != null)
                {
                    if (command.Name == "openAttachment")
                    {
                        string path = command.Arguments["path"];
                        if (!string.IsNullOrEmpty(path))
                        {
                            currentProtocolSink.ReportProgress(BINDSTATUS.BINDSTATUS_SENDINGREQUEST, Path.GetFileName(path));
                            success = StartOpenAttachmentCommand(path);
                        }
                    }
                    else
                    {
                        currentProtocolSink.ReportProgress(BINDSTATUS.BINDSTATUS_SENDINGREQUEST, command.Name);

                        var engine = new GallioNavigatorEngine(true);
                        success = command.Execute(engine);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(String.Format("Failed to process Uri '{0}' due to an exception: {1}.", currentUrl, ex));
            }

            LockData();

            int hr;

            if (success)
            {
                if (data != null && (currentBindFlags & BINDF.BINDF_NOWRITECACHE) == 0)
                {
                    uint dataLength = (uint)data.Length;

                    // Provide mime type.
                    if (dataMimeType != null)
                    {
                        currentProtocolSink.ReportProgress(BINDSTATUS.BINDSTATUS_VERIFIEDMIMETYPEAVAILABLE, dataMimeType);
                    }

                    // Determine whether we need to provide the path to the local file.
                    if ((currentBindFlags & BINDF.BINDF_NEEDFILE) != 0 && dataPath != null)
                    {
#if false // Not needed at the moment since the file we provide does not need to be in the cache.
          // Keeping this code in case we decide to provide dynamic content later.
                        StringBuilder cacheFilePathBuilder = new StringBuilder(NativeConstants.MAX_PATH);
                        string        extension            = Path.GetExtension(dataPath);
                        if (extension.Length != 0)
                        {
                            extension = extension.Substring(1); // strip leading '.'
                        }
                        NativeMethods.CreateUrlCacheEntry(currentUrl, dataLength, extension, cacheFilePathBuilder, 0);
                        string cacheFilePath = cacheFilePathBuilder.ToString();

                        DateTime now     = DateTime.Now;
                        var      nowTime = new System.Runtime.InteropServices.ComTypes.FILETIME()
                        {
                            dwHighDateTime = (int)(now.Ticks >> 32),
                            dwLowDateTime  = (int)now.Ticks
                        };

                        const string headers = "HTTP/1.0 200 OK\r\n\r\n";
                        File.Copy(dataPath, cacheFilePath, true);
                        NativeMethods.CommitUrlCacheEntry(currentUrl, cacheFilePath,
                                                          nowTime,
                                                          nowTime,
                                                          NativeConstants.NORMAL_CACHE_ENTRY,
                                                          headers, (uint)headers.Length,
                                                          extension, null);

                        currentProtocolSink.ReportProgress(BINDSTATUS.BINDSTATUS_CACHEFILENAMEAVAILABLE, cacheFilePath);
#else
                        currentProtocolSink.ReportProgress(BINDSTATUS.BINDSTATUS_CACHEFILENAMEAVAILABLE, dataPath);
#endif
                    }

                    // Report all data available.
                    currentProtocolSink.ReportData(BSCF.BSCF_FIRSTDATANOTIFICATION | BSCF.BSCF_LASTDATANOTIFICATION | BSCF.BSCF_DATAFULLYAVAILABLE, dataLength, dataLength);

                    hr = NativeConstants.S_OK;
                }
                else
                {
                    // Aborts the navigation.
                    hr = NativeConstants.INET_E_DATA_NOT_AVAILABLE;
                }
            }
            else
            {
                // Reports an invalid Url.
                hr = NativeConstants.INET_E_INVALID_URL;
            }

            currentProtocolSink.ReportResult(hr, 0, null);
            currentProtocolSink = null;

            UnlockData();
            return(hr);
        }