Пример #1
0
 internal RouteMapper(string route, HTTPMethod methods, IHTTPRouteHandler handler)
 {
     _route = WoopsaConst.UrlSeparator + route.Trim(WoopsaConst.UrlSeparator);
     _methods = methods;
     _handler = handler;
     _processors = new List<PostRouteProcessor>();
 }
Пример #2
0
 internal HTTPRequest(HTTPMethod method, string fullURL)
 {
     _fullURL = fullURL;
     _baseURL = _fullURL;
     _method = method;
     _headers = new Dictionary<string, string>();
 }
Пример #3
0
 /**
  * Default Constructor
  *
  * @param ConsumerKey
  *            - Consumer key shared between PayPal and OAuth consumer
  * @param ConsumerSecret
  *            - Secret shared between PayPal and OAuth consumer
  */
 public OAuthGenerator(String consumerKey, string consumerSecret)
 {
     this.QueryParams = new ArrayList();
     this.ConsumerKey = consumerKey;
     this.ConsumerSecret = System.Text.Encoding.ASCII.GetBytes(consumerSecret);
     this.HttpMethod = HTTPMethod.POST;
 }
 /// <summary>
 /// Default Constructor
 /// </summary>
 /// <param name="consumerKey"></param>
 /// <param name="consumerSecret"></param>        
 public OAuthGenerator(string consumerKey, string consumerSecret)
 {
     this.queryParameters = new ArrayList();
     this.consumerKey = consumerKey;
     this.consumerSecret = System.Text.Encoding.ASCII.GetBytes(consumerSecret);
     this.methodHTTP = HTTPMethod.POST;
 }
Пример #5
0
 public SOAServiceManager (string url, string session, HTTPMethod httpMethod)
 {
     URL = url;
     Session = session;
     _HttpMethod = httpMethod;
     _Fieldnames = new List<string> ();
     _Values = new List<string> ();
 }
        public HTTPRequestHandle CreateHTTPRequest(HTTPMethod HTTPRequestMethod, string absoluteURL)
        {
            CheckIfUsable();

            using (NativeString nativeString = new NativeString(absoluteURL))
            {
                return new HTTPRequestHandle(NativeMethods.HTTP_CreateHTTPRequest((int)HTTPRequestMethod, nativeString.ToNativeAsUtf8()));
            }
        }
Пример #7
0
 /// <summary>
 /// Adds a route handler for the specified route and HTTP methods, using a delegate.
 /// <para>
 /// This is useful for quick, one-off serving of pages. For more complex cases, such as
 /// serving files from the file system, it is recommended to use the slightly more complex
 /// <see cref="IHTTPRouteHandler"/> interface.
 /// </para>
 /// </summary>
 /// <param name="route">The route, for example "/hello_world"</param>
 /// <param name="methods">
 /// The HTTP Methods to support. HTTPMethod has the <c>[Flag]</c> metadata,
 /// which makes it possible to support multiple methods in a single page.
 /// </param>
 /// <param name="handlerMethod">A method delegate. See <see cref="HandleRequestDelegate"/> for usage.</param>
 public RouteMapper Add(string route, HTTPMethod methods, HandleRequestDelegate handlerMethod, bool acceptSubroutes = false)
 {
     lock (_lock)
     {
         RouteHandlerDelegate newHandler = new RouteHandlerDelegate(handlerMethod, acceptSubroutes);
         RouteMapper mapper = new RouteMapper(route, methods, newHandler);
         _routes.Add(mapper);
         return mapper;
     }
 }
Пример #8
0
    public HTTPRequest(string newMethod, string newUrl) {
      url = newUrl;

      method = HTTPMethod.GET;

      if(newMethod.Equals("POST")) {
        method = HTTPMethod.POST;
        headers = new Dictionary<string, string>();
      }
    }
Пример #9
0
        /// <summary>
        /// Creates a new HTTPMethodNode.
        /// </summary>
        /// <param name="HTTPMethod">The http method for this service.</param>
        /// <param name="MethodHandler">The method handler.</param>
        /// <param name="HTTPMethodAuthentication">This and all subordinated nodes demand an explicit http method authentication.</param>
        /// <param name="HTTPMethodErrorHandler">A general error handling method.</param>
        public HTTPMethodNode(HTTPMethod HTTPMethod, MethodInfo MethodHandler = null, Boolean HTTPMethodAuthentication = false, MethodInfo HTTPMethodErrorHandler = null, Boolean HandleContentTypes = false)
        {
            this.HTTPMethod                = HTTPMethod;
            this.MethodHandler             = MethodHandler;
            this.HTTPMethodAuthentication  = HTTPMethodAuthentication;
            this.HTTPMethodErrorHandler    = HTTPMethodErrorHandler;
            this.HTTPMethodErrorHandlers   = new ConcurrentDictionary<HTTPStatusCode, MethodInfo>();
            this.MethodHandler             = MethodHandler;

            if (HandleContentTypes)
                HTTPContentTypes = new ConcurrentDictionary<HTTPContentType, ContentTypeNode>();
        }
Пример #10
0
        /// <summary>
        /// Creates a new HTTPMethodNode.
        /// </summary>
        /// <param name="HTTPMethod">The http method for this service.</param>
        /// <param name="HTTPMethodAuthentication">This and all subordinated nodes demand an explicit HTTP method authentication.</param>
        /// <param name="RequestHandler">The default delegate to call for any request to this URI template.</param>
        /// <param name="DefaultErrorHandler">The default error handling delegate.</param>
        internal HTTPMethodNode(HTTPMethod          HTTPMethod,
                                HTTPAuthentication  HTTPMethodAuthentication    = null,
                                HTTPDelegate        RequestHandler              = null,
                                HTTPDelegate        DefaultErrorHandler         = null)
        {
            if (HTTPMethod == null)
                throw new ArgumentException("HTTPMethod == null!");

            this.HTTPMethod                = HTTPMethod;
            this.HTTPMethodAuthentication  = HTTPMethodAuthentication;
            this.RequestHandler            = RequestHandler;
            this.DefaultErrorHandler       = DefaultErrorHandler;

            this._ErrorHandlers             = new Dictionary<HTTPStatusCode,  HTTPDelegate>();
            this._HTTPContentTypes          = new Dictionary<HTTPContentType, ContentTypeNode>();
        }
Пример #11
0
 public static void Route(HTTPMethod method, RoutePatternMatch route, RouteCallback_D callback) => Routing.AddHandler(method, route, callback);
Пример #12
0
 public Controller(HTTPMethod method, RoutePatternMatch route, Response res) :                               this(method.ToString(), route, route.CreateCallback(res))
 {
 }
Пример #13
0
 private static extern HTTPRequestHandle _CreateHTTPRequest(IntPtr self, HTTPMethod eHTTPRequestMethod, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(Utf8StringToNative))] string pchAbsoluteURL);
Пример #14
0
 public StringRequestContext(HTTPMethod method, string url) : base(method, url)
 {
 }
Пример #15
0
 public Controller(HTTPMethod method, RoutePatternMatch route, RouteCallback_D callback) :                   this(method.ToString(), route, route.CreateCallback(callback))
 {
 }
Пример #16
0
 //TODO: Remove me
 public void setHTTPMethod(HTTPMethod method)
 {
     this.HttpMethod = method;
 }
Пример #17
0
        /// <summary>
        /// CreateWebRequest ready for OAuth 2 access
        /// </summary>
        /// <param name="method">HTTPMethod</param>
        /// <param name="url"></param>
        /// <param name="settings">OAuth2Settings</param>
        /// <returns>HttpWebRequest</returns>
        public static HttpWebRequest CreateOAuth2WebRequest(HTTPMethod method, string url, OAuth2Settings settings)
        {
            CheckAndAuthenticateOrRefresh(settings);

            HttpWebRequest webRequest = NetworkHelper.CreateWebRequest(url, method);
            AddOAuth2Credentials(webRequest, settings);
            return webRequest;
        }
Пример #18
0
 public static void All(HTTPMethod method, Response res) => Routing.AddHandler(method, res);
Пример #19
0
 public static void All(HTTPMethod method, RouteCallback_D callback) => Routing.AddHandler(method, callback);
Пример #20
0
 public static void Route(HTTPMethod method, string route, Response res) => Routing.AddHandler(method, (RouteArg)route, res);
Пример #21
0
 public static void Route(HTTPMethod method, string route, RouteCallback_A callback) => Routing.AddHandler(method, (RouteArg)route, callback);
Пример #22
0
 public MethodArg(HTTPMethod method) => this.Value = method.ToString();
Пример #23
0
 public static void Route(HTTPMethod method, RoutePatternMatch route, Response res) => Routing.AddHandler(method, route, res);
Пример #24
0
 /// <summary>
 /// Submit a web request using oAuth.
 /// </summary>
 /// <param name="method">GET or POST</param>
 /// <param name="signUrl">The full url, including the querystring for the signing</param>
 /// <param name="requestURL">The full url, including the querystring for the request</param>
 /// <param name="parametersToSign">Parameters for the request, which need to be signed</param>
 /// <param name="additionalParameters">Parameters for the request, which do not need to be signed</param>
 /// <param name="postData">Data to post (MemoryStream)</param>
 /// <returns>The web server response.</returns>
 public string MakeOAuthRequest(HTTPMethod method, string signUrl, string requestURL, IDictionary<string, object> parametersToSign, IDictionary<string, object> additionalParameters, IBinaryContainer postData)
 {
     return MakeOAuthRequest(method, signUrl, requestURL, null, parametersToSign, additionalParameters, postData);
 }
Пример #25
0
        /// <summary>
        /// Make the actual OAuth request, all oauth parameters are passed as header (default) and the others are placed in the url or post data.
        /// Any additional parameters added after the Sign call are not in the signature, this could be by design!
        /// </summary>
        /// <param name="method"></param>
        /// <param name="requestURL"></param>
        /// <param name="headers"></param>
        /// <param name="parameters"></param>
        /// <param name="postData">IBinaryParameter</param>
        /// <returns>Response from server</returns>
        private string MakeRequest(HTTPMethod method, string requestURL, IDictionary<string, string> headers, IDictionary<string, object> parameters, IBinaryContainer postData)
        {
            if (parameters == null) {
                throw new ArgumentNullException("parameters");
            }
            IDictionary<string, object> requestParameters;
            // Add oAuth values as HTTP headers, if this is allowed
            StringBuilder authHeader = null;
            if (UseHTTPHeadersForAuthorization) {
                authHeader = new StringBuilder();
                requestParameters = new Dictionary<string, object>();
                foreach (string parameterKey in parameters.Keys) {
                    if (parameterKey.StartsWith(OAUTH_PARAMETER_PREFIX)) {
                        authHeader.AppendFormat(CultureInfo.InvariantCulture, "{0}=\"{1}\", ", parameterKey, UrlEncode3986(string.Format("{0}",parameters[parameterKey])));
                    } else if (!requestParameters.ContainsKey(parameterKey)) {
                        requestParameters.Add(parameterKey, parameters[parameterKey]);
                    }
                }
                // Remove trailing comma and space and add it to the headers
                if (authHeader.Length > 0) {
                    authHeader.Remove(authHeader.Length - 2, 2);
                }
            } else {
                requestParameters = parameters;
            }

            if (HTTPMethod.GET == method || postData != null) {
                if (requestParameters.Count > 0) {
                    // Add the parameters to the request
                    requestURL += "?" + NetworkHelper.GenerateQueryParameters(requestParameters);
                }
            }
            // Create webrequest
            HttpWebRequest webRequest = NetworkHelper.CreateWebRequest(requestURL, method);
            webRequest.ServicePoint.Expect100Continue = false;
            webRequest.UserAgent = _userAgent;

            if (UseHTTPHeadersForAuthorization && authHeader != null) {
                LOG.DebugFormat("Authorization: OAuth {0}", authHeader);
                webRequest.Headers.Add("Authorization: OAuth " + authHeader);
            }

            if (headers != null) {
                foreach(string key in headers.Keys) {
                    webRequest.Headers.Add(key, headers[key]);
                }
            }

            if ((HTTPMethod.POST == method || HTTPMethod.PUT == method) && postData == null && requestParameters.Count > 0) {
                if (UseMultipartFormData) {
                    NetworkHelper.WriteMultipartFormData(webRequest, requestParameters);
                } else {
                    StringBuilder form = new StringBuilder();
                    foreach (string parameterKey in requestParameters.Keys) {
                        if (parameters[parameterKey] is IBinaryContainer) {
                            IBinaryContainer binaryParameter = parameters[parameterKey] as IBinaryContainer;
                            form.AppendFormat(CultureInfo.InvariantCulture, "{0}={1}&", UrlEncode3986(parameterKey), UrlEncode3986(binaryParameter.ToBase64String(Base64FormattingOptions.None)));
                        } else {
                            form.AppendFormat(CultureInfo.InvariantCulture, "{0}={1}&", UrlEncode3986(parameterKey), UrlEncode3986(string.Format("{0}",parameters[parameterKey])));
                        }
                    }
                    // Remove trailing &
                    if (form.Length > 0) {
                        form.Remove(form.Length - 1, 1);
                    }
                    webRequest.ContentType = "application/x-www-form-urlencoded";
                    byte[] data = Encoding.UTF8.GetBytes(form.ToString());
                    using (var requestStream = webRequest.GetRequestStream()) {
                        requestStream.Write(data, 0, data.Length);
                    }
                }
            } else if (postData != null) {
                postData.Upload(webRequest);
            } else {
                webRequest.ContentLength = 0;
            }

            string responseData;
            try {
                responseData = NetworkHelper.GetResponseAsString(webRequest);
                LOG.DebugFormat("Response: {0}", responseData);
            } catch (Exception ex) {
                LOG.Error("Couldn't retrieve response: ", ex);
                throw;
            } finally {
                webRequest = null;
            }

            return responseData;
        }
Пример #26
0
 /// <summary>
 /// Helper method to create a web request with a lot of default settings
 /// </summary>
 /// <param name="uri">string with uri to connect to</param>
 /// /// <param name="method">Method to use</param>
 /// <returns>WebRequest</returns>
 public static HttpWebRequest CreateWebRequest(string uri, HTTPMethod method)
 {
     return(CreateWebRequest(new Uri(uri), method));
 }
Пример #27
0
 /// <summary>
 /// Helper method to create a web request with a lot of default settings
 /// </summary>
 /// <param name="uri">string with uri to connect to</param>
 /// /// <param name="method">Method to use</param>
 /// <returns>WebRequest</returns>
 public static HttpWebRequest CreateWebRequest(string uri, HTTPMethod method)
 {
     return CreateWebRequest(new Uri(uri), method);
 }
Пример #28
0
 public HttpHandler(HTTPMethod method, string url, string param)
 {
     this._APIUrl = new Uri(url);
     this._Method = method;
     this._PostData = param;
 }
 /// <summary>
 ///  Sets time stamp for signature computation
 /// </summary>
 /// <param name="method"></param>
 public void setHTTPMethod(string method)
 {
     switch (method)
     {
         case "GET":
             this.methodHTTP = HTTPMethod.GET;
             break;
         case "POST":
             this.methodHTTP = HTTPMethod.POST;
             break;
         case "PUT":
             this.methodHTTP = HTTPMethod.PUT;
             break;
         case "UPDATE":
             this.methodHTTP = HTTPMethod.UPDATE;
             break;
         default:
             this.methodHTTP = HTTPMethod.POST;
             break;
     }
 }
Пример #30
0
        private void HandleClient(TcpClient client)
        {
            lock (_openTcpClients)
                _openTcpClients.Add(client);
            try
            {
                Stream stream = client.GetStream();
                try
                {
                    foreach (PreRouteProcessor processor in PreRouteProcessors)
                    {
                        stream = processor.ProcessStream(stream);
                    }
                    bool         leaveOpen = true;
                    HTTPResponse response  = null;
                    HTTPRequest  request   = null;
                    StreamReader reader    = new StreamReader(stream, Encoding.UTF8, false, 4096);
                    try
                    {
                        while (leaveOpen && !_aborted)
                        {
                            response = new HTTPResponse();

                            /*
                             * Parse the first line of the HTTP Request
                             * Examples:
                             *      GET / HTTP/1.1
                             *      POST /submit HTTP/1.1
                             */
                            string requestString;
                            try
                            {
                                requestString = reader.ReadLine();
                            }
                            catch (Exception)
                            {
                                requestString = null;
                                leaveOpen     = false;
                                break;
                            }
                            if (requestString == null)
                            {
                                break;
                            }

                            string[] parts = requestString.Split(' ');
                            if (parts.Length != 3)
                            {
                                throw new HandlingException(HTTPStatusCode.BadRequest, "Bad Request");
                            }
                            string method  = parts[0].ToUpper();
                            string url     = parts[1];
                            string version = parts[2].ToUpper();

                            //Check if the version is what we expect
                            if (version != "HTTP/1.1" && version != "HTTP/1.0")
                            {
                                throw new HandlingException(HTTPStatusCode.HttpVersionNotSupported, "HTTP Version Not Supported");
                            }

                            //Check if the method is supported
                            if (!_supportedMethods.ContainsKey(method))
                            {
                                throw new HandlingException(HTTPStatusCode.NotImplemented, method + " Method Not Implemented");
                            }
                            HTTPMethod httpMethod = _supportedMethods[method];

                            url = HttpUtility.UrlDecode(url);

                            //Build the request object
                            request = new HTTPRequest(httpMethod, url);

                            //Add all headers to the request object
                            FillHeaders(request, reader);

                            //Handle encoding for this request
                            Encoding clientEncoding = InferEncoding(request);

                            //Extract all the data from the URL (base and query)
                            ExtractQuery(request, clientEncoding);

                            //Extract and decode all the POST data
                            ExtractPOST(request, reader, clientEncoding);

                            bool keepAlive = false;
                            // According to spec, Keep-Alive is ON by default
                            if (version == "HTTP/1.1")
                            {
                                keepAlive = true;
                            }
                            if (request.Headers.ContainsKey(HTTPHeader.Connection))
                            {
                                if (request.Headers[HTTPHeader.Connection].ToLower().Equals("close"))
                                {
                                    keepAlive = false;
                                    response.SetHeader(HTTPHeader.Connection, "close");
                                }
                            }

                            //Keep-Alive can only work on a multithreaded server!
                            if (!keepAlive || !MultiThreaded)
                            {
                                leaveOpen = false;
                                response.SetHeader(HTTPHeader.Connection, "close");
                            }
                            //Pass this on to the route solver
                            OnLog(request, null);
                            HandleRequest(request, response, stream);
                            response.Respond(stream);
                            OnLog(request, response);
                        }
                    }
                    catch (HandlingException e)
                    {
                        if (response != null)
                        {
                            try
                            {
                                // try to return the response
                                response.WriteError(e.Status, e.ErrorMessage);
                                response.Respond(stream);
                                OnLog(request, response);
                            }
                            catch
                            {
                                // ignore silently if it is not posible
                            }
                        }
                    }
                    catch (ThreadAbortException)
                    {
                        // Do nothing, server is terminating
                    }
                    catch (Exception e)
                    {
                        if (response != null)
                        {
                            try
                            {
                                // try to return the response
                                response.WriteError(HTTPStatusCode.InternalServerError, "Internal Server Error. " + e.Message);
                                response.Respond(stream);
                                OnLog(request, response);
                            }
                            catch
                            {
                                // ignore silently if it is not posible
                            }
                        }
                    }
                    finally
                    {
                        reader.Close();
                    }
                }
                finally
                {
                    stream.Dispose();
                }
            }
            finally
            {
                lock (_openTcpClients)
                    _openTcpClients.Remove(client);
            }
        }
Пример #31
0
 public Controller(HTTPMethod method, string route, RouteCallback_D callback) :                              this(method, route, RouteCallback.Convert(callback))
 {
 }
Пример #32
0
 //TODO: Remove me
 public void setHTTPMethod(HTTPMethod method)
 {
     this.HttpMethod = method;
 }
Пример #33
0
 // HTTPRequestHandle
 public HTTPRequestHandle CreateHTTPRequest(HTTPMethod eHTTPRequestMethod /*EHTTPMethod*/, string pchAbsoluteURL /*const char **/)
 {
     return(platform.ISteamHTTP_CreateHTTPRequest(eHTTPRequestMethod, Utility.GetUtf8Bytes(pchAbsoluteURL)));
 }
Пример #34
0
 /// <summary>
 /// Set the HTTP method.
 /// </summary>
 /// <param name="HTTPMethod">The HTTPMethod.</param>
 public HTTPRequestBuilder SetHTTPMethod(HTTPMethod HTTPMethod)
 {
     this.HTTPMethod = HTTPMethod;
     return this;
 }
Пример #35
0
        /// <summary>
        /// Creates a new HttpWebRequest based on the urlString, method and config.
        /// </summary>
        /// <param name="urlString">The urlString</param>
        /// <param name="method">The connection method</param>
        /// <returns>A new HttpWebRequest.</returns>
        private HttpWebRequest CreateConnection(string urlString, HTTPMethod method)
        {
            Uri url = new Uri(urlString);
            HttpWebRequest urlConnection = (System.Net.HttpWebRequest)WebRequest.Create(url);
            urlConnection.Method = method.ToString();
            urlConnection.ContentType = "application/xml";
            urlConnection.Credentials = new NetworkCredential(config.Username, config.Password);
            urlConnection.UserAgent = USER_AGENT_STRING;
            urlConnection.Timeout = config.RequestTimeout;
            urlConnection.ReadWriteTimeout = config.ReadWriteTimeout;

            if (config.UseGzip)
            {
                urlConnection.Headers.Add("Accept-Encoding", "gzip");
                urlConnection.Headers.Add("Content-Encoding", "gzip");
            }

            return urlConnection;
        }
Пример #36
0
        /// <summary> Get a parameter from passed input parameters  </summary>
        /// <param name="parameters"> Required parameters  </param>
        /// <param name="method"> Get / put / post / delete  </param>
        /// <param name="inputParams"> Passed input parameters  </param>
        /// <param name="defaultValue"> The default value  </param>
        /// <returns> NameValueCollection "Null" if parameter is missing  </returns>
        public dynamic GetParam(string[] parameters, HTTPMethod method = HTTPMethod.Get, Parameters inputParams = null, string defaultValue = null)
        {
            var response = new Parameters(parameters);
            foreach (var p in parameters)
            {
                var value = this.GetParam(p, method, inputParams);
                if (value != null)
                    Impromptu.InvokeSet(response, p, value);
            }

            return response;
        }
Пример #37
0
 public RESTClient <RS, ERS> Delete()
 {
     method = HTTPMethod.DELETE;
     return(this);
 }
Пример #38
0
        internal HTTPRequestHandle CreateHTTPRequest(HTTPMethod eHTTPRequestMethod, [MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(Utf8StringToNative))] string pchAbsoluteURL)
        {
            var returnValue = _CreateHTTPRequest(Self, eHTTPRequestMethod, pchAbsoluteURL);

            return(returnValue);
        }
Пример #39
0
        /// <summary> Get a parameter from passed input parameters </summary>
        /// <param name="parameter">Required parameter</param>
        /// <param name="method">Get / put / post / delete</param>
        /// <param name="inputParams">Passed input parameters</param>
        /// <param name="defaultValue">The default value</param>
        /// <returns>System.String. "Null" if parameter is missing</returns>
        public object GetParam(string parameter, HTTPMethod method = HTTPMethod.Get, dynamic inputParams = null, object defaultValue = null)
        {
            if (inputParams != null && Impromptu.InvokeGet(inputParams, parameter) != null)
            {
                return Impromptu.InvokeGet(inputParams, parameter);
            }

            if (parameter == "client_id" && this.Request != null && !string.IsNullOrEmpty(this.Request.Server("AUTH_USER")))
            {
                return this.Request.Server("AUTH_USER");
            }

            if (parameter == "client_secret" && this.Request != null && !string.IsNullOrEmpty(this.Request.Server("AUTH_PASSWORD")))
            {
                return this.Request.Server("AUTH_PASSWORD");
            }

            if (this.Request == null) return null;

            switch (method)
            {
                case HTTPMethod.Get:
                    return this.Request.Get(parameter, defaultValue != null ? defaultValue.ToString() : null);
                case HTTPMethod.Post:
                    return this.Request.Post(parameter, defaultValue != null ? defaultValue.ToString() : null);
                case HTTPMethod.Cookie:
                    return this.Request.Cookie(parameter, (HttpCookie)defaultValue);
                case HTTPMethod.File:
                    return this.Request.File(parameter, (HttpPostedFile)defaultValue);
                case HTTPMethod.Server:
                    return this.Request.Server(parameter, defaultValue != null ? defaultValue.ToString() : null);
                case HTTPMethod.Header:
                    return this.Request.Header(parameter, defaultValue != null ? defaultValue.ToString() : null);
                default:
                    return null;
            }
        }
Пример #40
0
 public RESTClient <RS, ERS> Get()
 {
     method = HTTPMethod.GET;
     return(this);
 }
Пример #41
0
        public void ExecuteScript(string fullPath, Dictionary<string, string> urlParameters,
            ClientHttpResponse response, string extension, string mimeType, HTTPMethod method, string postData,
            string documentRoot, dynamic serverHandle, ScriptExecutionParameters executionParameters)
        {
            //Prepare JSScript
            var scriptContents = File.ReadAllText(fullPath);
            var scriptDir = Path.GetDirectoryName(fullPath);
            var jsEngine = new Engine(cfg => cfg.AllowClr());

            var undefined = Undefined.Instance;

            //Inject variables
            if (method == HTTPMethod.Get)
            {
                jsEngine.SetValue("_GET", urlParameters);
                jsEngine.SetValue("_SERVER", response.RequestHttpHeaders);
                jsEngine.SetValue("_POST", undefined);
            }
            if (method == HTTPMethod.Post)
            {
                jsEngine.SetValue("_GET", undefined);
                jsEngine.SetValue("_SERVER", response.RequestHttpHeaders);
                jsEngine.SetValue("_POST", urlParameters);
                jsEngine.SetValue("POST_DATA", postData);
            }

            //Globals
            jsEngine.SetValue("DocumentRoot", documentRoot);
            jsEngine.SetValue("__dirname__", scriptDir);

            switch (extension)
            {
                case ".jscx": //Fully-controlled script
                {
                    try
                    {
                        //Manipulate Scope
                        jsEngine.SetValue("response", response);
                        jsEngine.SetValue("FireHTTPServer", serverHandle);
                        jsEngine.SetValue("_mimeTypeMappings", CommonVariables.MimeTypeMappings);
                        jsEngine.SetValue("dirSep", _dirSep);
                        DefineScriptingApi(jsEngine);
                        jsEngine.Execute(scriptContents);
                        break;
                    }
                    catch (DeadRequestException)
                    {
                        throw; //Don't catch these.
                    }
                    catch (Exception ex)
                    {
                        var level = (int) jsEngine.GetValue("__error_reporting_level").AsNumber();
                        if (level > 0)
                        {
                            if (!response.HasFinishedSendingHeaders)
                            {
                                //If headers not sent, send default headers.
                                response.SendHeader("HTTP/1.1 200 OK");
                                response.SendHeader("Content-Type: text/plain");
                                response.SendEndHeaders();
                            }
                            response.OutputStream.WriteLine("Error in script execution. Stack trace:");
                            response.OutputStream.WriteLine(ex.ToString());
                            break;
                        }
                        throw;
                    }
                }
            }
        }
Пример #42
0
 public RESTClient <RS, ERS> Patch()
 {
     method = HTTPMethod.PATCH;
     return(this);
 }
Пример #43
0
 /// <summary>
 /// Generates a new HTTP mapping.
 /// </summary>
 /// <param name="HTTPMethod">The HTTP method of this HTTP mapping.</param>
 /// <param name="UriTemplate">The URI template of this HTTP mapping.</param>
 public HTTPMappingAttribute(HTTPMethod HTTPMethod, String UriTemplate)
 {
     this.HTTPMethod  = HTTPMethod;
     this.UriTemplate = UriTemplate;
 }
Пример #44
0
 public RESTClient <RS, ERS> Post()
 {
     method = HTTPMethod.POST;
     return(this);
 }
Пример #45
0
        /// <summary>
        /// Submit a web request using oAuth.
        /// </summary>
        /// <param name="method">GET or POST</param>
        /// <param name="signUrl">The full url, including the querystring for the signing</param>
        /// <param name="requestURL">The full url, including the querystring for the request</param>
        /// <param name="headers">Headers for the request</param>
        /// <param name="parametersToSign">Parameters for the request, which need to be signed</param>
        /// <param name="additionalParameters">Parameters for the request, which do not need to be signed</param>
        /// <param name="postData">Data to post (MemoryStream)</param>
        /// <returns>The web server response.</returns>
        public string MakeOAuthRequest(HTTPMethod method, string signUrl, string requestURL, IDictionary<string, string> headers, IDictionary<string, object> parametersToSign, IDictionary<string, object> additionalParameters, IBinaryContainer postData)
        {
            if (parametersToSign == null) {
                parametersToSign = new Dictionary<string, object>();
            }
            int retries = 2;
            Exception lastException = null;
            while (retries-- > 0) {
                // If we are not trying to get a Authorization or Accestoken, and we don't have a token, create one
                if (string.IsNullOrEmpty(Token)) {
                    if (!AutoLogin || !Authorize()) {
                        throw new Exception("Not authorized");
                    }
                }
                try {
                    Sign(method, signUrl, parametersToSign);

                    // Join all parameters
                    IDictionary<string, object> newParameters = new Dictionary<string, object>();
                    foreach(var parameter in parametersToSign) {
                        newParameters.Add(parameter);
                    }
                    if (additionalParameters != null) {
                        foreach(var parameter in additionalParameters) {
                            newParameters.Add(parameter);
                        }
                    }
                    return MakeRequest(method, requestURL, headers, newParameters, postData);
                } catch (WebException wEx) {
                    lastException = wEx;
                    if (wEx.Response != null) {
                        HttpWebResponse response = wEx.Response as HttpWebResponse;
                        if (response != null && response.StatusCode == HttpStatusCode.Unauthorized) {
                            Token = null;
                            TokenSecret = null;
                            // Remove oauth keys, so they aren't added double
                            List<string> keysToDelete = new List<string>();
                            foreach (string parameterKey in parametersToSign.Keys) {
                                if (parameterKey.StartsWith(OAUTH_PARAMETER_PREFIX)) {
                                    keysToDelete.Add(parameterKey);
                                }
                            }
                            foreach(string keyToDelete in keysToDelete) {
                                parametersToSign.Remove(keyToDelete);
                            }
                            continue;
                        }
                    }
                    throw;
                }
            }
            if (lastException != null) {
                throw lastException;
            }
            throw new Exception("Not authorized");
        }
Пример #46
0
 public RESTClient <RS, ERS> Put()
 {
     method = HTTPMethod.PUT;
     return(this);
 }
Пример #47
0
        /// <summary>
        /// OAuth sign the parameters, meaning all oauth parameters are added to the supplied dictionary.
        /// And additionally a signature is added.
        /// </summary>
        /// <param name="method">Method (POST,PUT,GET)</param>
        /// <param name="requestURL">Url to call</param>
        /// <param name="parameters">IDictionary<string, string></param>
        private void Sign(HTTPMethod method, string requestURL, IDictionary<string, object> parameters)
        {
            if (parameters == null) {
                throw new ArgumentNullException("parameters");
            }
            // Build the signature base
            StringBuilder signatureBase = new StringBuilder();

            // Add Method to signature base
            signatureBase.Append(method.ToString()).Append("&");

            // Add normalized URL
            Uri url = new Uri(requestURL);
            string normalizedUrl = string.Format(CultureInfo.InvariantCulture, "{0}://{1}", url.Scheme, url.Host);
            if (!((url.Scheme == "http" && url.Port == 80) || (url.Scheme == "https" && url.Port == 443))) {
                normalizedUrl += ":" + url.Port;
            }
            normalizedUrl += url.AbsolutePath;
            signatureBase.Append(UrlEncode3986(normalizedUrl)).Append("&");

            // Add normalized parameters
            parameters.Add(OAUTH_VERSION_KEY, OAUTH_VERSION);
            parameters.Add(OAUTH_NONCE_KEY, GenerateNonce());
            parameters.Add(OAUTH_TIMESTAMP_KEY, GenerateTimeStamp());
            switch(SignatureType) {
                case OAuthSignatureTypes.RSASHA1:
                    parameters.Add(OAUTH_SIGNATURE_METHOD_KEY, RSASHA1SignatureType);
                    break;
                case OAuthSignatureTypes.PLAINTEXT:
                    parameters.Add(OAUTH_SIGNATURE_METHOD_KEY, PlainTextSignatureType);
                    break;
                case OAuthSignatureTypes.HMACSHA1:
                default:
                    parameters.Add(OAUTH_SIGNATURE_METHOD_KEY, HMACSHA1SignatureType);
                    break;
            }
            parameters.Add(OAUTH_CONSUMER_KEY_KEY, _consumerKey);
            if (CallbackUrl != null && RequestTokenUrl != null && requestURL.StartsWith(RequestTokenUrl)) {
                parameters.Add(OAUTH_CALLBACK_KEY, CallbackUrl);
            }
            if (!string.IsNullOrEmpty(Verifier)) {
                parameters.Add(OAUTH_VERIFIER_KEY, Verifier);
            }
            if (!string.IsNullOrEmpty(Token)) {
                parameters.Add(OAUTH_TOKEN_KEY, Token);
            }
            signatureBase.Append(UrlEncode3986(GenerateNormalizedParametersString(parameters)));
            LOG.DebugFormat("Signature base: {0}", signatureBase);
            string key = string.Format(CultureInfo.InvariantCulture, "{0}&{1}", UrlEncode3986(_consumerSecret), string.IsNullOrEmpty(TokenSecret) ? string.Empty : UrlEncode3986(TokenSecret));
            switch (SignatureType) {
                case OAuthSignatureTypes.RSASHA1:
                    // Code comes from here: http://www.dotnetfunda.com/articles/article1932-rest-service-call-using-oauth-10-authorization-with-rsa-sha1.aspx
                    // Read the .P12 file to read Private/Public key Certificate
                    string certFilePath = _consumerKey; // The .P12 certificate file path Example: "C:/mycertificate/MCOpenAPI.p12
                    string password = _consumerSecret; // password to read certificate .p12 file
                    // Read the Certification from .P12 file.
                    X509Certificate2 cert = new X509Certificate2(certFilePath.ToString(), password);
                    // Retrieve the Private key from Certificate.
                    RSACryptoServiceProvider RSAcrypt = (RSACryptoServiceProvider)cert.PrivateKey;
                    // Create a RSA-SHA1 Hash object
                    using (SHA1Managed shaHASHObject = new SHA1Managed()) {
                        // Create Byte Array of Signature base string
                        byte[] data = Encoding.ASCII.GetBytes(signatureBase.ToString());
                        // Create Hashmap of Signature base string
                        byte[] hash = shaHASHObject.ComputeHash(data);
                        // Create Sign Hash of base string
                        // NOTE - 'SignHash' gives correct data. Don't use SignData method
                        byte[] rsaSignature = RSAcrypt.SignHash(hash, CryptoConfig.MapNameToOID("SHA1"));
                        // Convert to Base64 string
                        string base64string = Convert.ToBase64String(rsaSignature);
                        // Return the Encoded UTF8 string
                        parameters.Add(OAUTH_SIGNATURE_KEY, UrlEncode3986(base64string));
                    }
                    break;
                case OAuthSignatureTypes.PLAINTEXT:
                    parameters.Add(OAUTH_SIGNATURE_KEY, key);
                    break;
                case OAuthSignatureTypes.HMACSHA1:
                default:
                    // Generate Signature and add it to the parameters
                    HMACSHA1 hmacsha1 = new HMACSHA1();
                    hmacsha1.Key = Encoding.UTF8.GetBytes(key);
                    string signature = ComputeHash(hmacsha1, signatureBase.ToString());
                    parameters.Add(OAUTH_SIGNATURE_KEY, signature);
                    break;
            }
        }
Пример #48
0
 public HTTPRequest(string newUrl)
 {
     url    = newUrl;
     method = HTTPMethod.GET;
 }
Пример #49
0
 public HTTPRequest(string newUrl)
 {
     url = newUrl;
       method = HTTPMethod.GET;
 }
Пример #50
0
 //TODO: Remove me
 public void setHTTPMethod(HTTPMethod method)
 {
     this.methodHTTP = method;
 }
Пример #51
0
 /// <summary>
 /// Helper method to create a web request with a lot of default settings
 /// </summary>
 /// <param name="uri">Uri with uri to connect to</param>
 /// <param name="method">Method to use</param>
 /// <returns>WebRequest</returns>
 public static HttpWebRequest CreateWebRequest(Uri uri, HTTPMethod method)
 {
     HttpWebRequest webRequest = CreateWebRequest(uri);
     webRequest.Method = method.ToString();
     return webRequest;
 }
Пример #52
0
 public unsafe static uint CreateHTTPRequest(HTTPMethod method, string absoluteURL)
 {
     return(0);
 }
 //TODO: Remove me
 public void setHTTPMethod(HTTPMethod method)
 {
     this.methodHTTP = method;
 }
Пример #54
0
        /// <summary>
        /// Create a new HTTP request.
        /// </summary>
        /// <param name="HTTPMethod">A HTTP method.</param>
        /// <param name="URI">An URI.</param>
        /// <param name="BuilderAction">A delegate to configure the new HTTP request builder.</param>
        /// <returns>A new HTTPRequest object.</returns>
        public HTTPRequestBuilder CreateRequest(HTTPMethod                  HTTPMethod,
                                                String                      URI,
                                                Action<HTTPRequestBuilder>  BuilderAction  = null)
        {

            var Builder     = new HTTPRequestBuilder(this) {
                HTTPMethod  = HTTPMethod,
                URI         = URI
            };

            BuilderAction?.Invoke(Builder);

            return Builder;

        }
Пример #55
0
        public void AddHandler(HTTPDelegate        HTTPDelegate,

                               HTTPMethod          HTTPMethod                  = null,
                               HTTPContentType     HTTPContentType             = null,

                               HTTPAuthentication  HTTPMethodAuthentication    = null,
                               HTTPAuthentication  ContentTypeAuthentication   = null,

                               HTTPDelegate        DefaultErrorHandler         = null,
                               URIReplacement      AllowReplacement            = URIReplacement.Fail)
        {
            HTTPMethodNode _HTTPMethodNode = null;

            if (!_HTTPMethods.TryGetValue(HTTPMethod, out _HTTPMethodNode))
            {
                _HTTPMethodNode = new HTTPMethodNode(HTTPMethod, HTTPMethodAuthentication, HTTPDelegate, DefaultErrorHandler);
                _HTTPMethods.Add(HTTPMethod, _HTTPMethodNode);
            }

            _HTTPMethodNode.AddHandler(HTTPDelegate,

                                       HTTPContentType,

                                       ContentTypeAuthentication,

                                       DefaultErrorHandler,
                                       AllowReplacement);
        }
Пример #56
0
 public Controller(HTTPMethod method, string route, Response res) :                                          this(method, route, RouteCallback.ResponseShortcut(res))
 {
 }
Пример #57
0
        /// <summary>
        /// Return the RAW request header.
        /// </summary>
        public static void RegisterRAWRequestHandler(this HTTPServer  HTTPServer,
                                                     HTTPHostname     Hostname,
                                                     String           URITemplate,
                                                     HTTPMethod       HTTPMethod = null)
        {
            HTTPServer.AddMethodCallback(Hostname,
                                         HTTPMethod:    HTTPMethod ?? HTTPMethod.GET,
                                         URITemplate:   URITemplate,
                                         HTTPDelegate:  async Request => {

                                             return new HTTPResponseBuilder(Request) {

                                                 HTTPStatusCode  = HTTPStatusCode.OK,
                                                 Server          = HTTPServer.DefaultServerName,
                                                 Date            = DateTime.Now,
                                                 CacheControl    = "no-cache",
                                                 Connection      = "close",
                                                 ContentType     = HTTPContentType.TEXT_UTF8,
                                                 Content         = ("Incoming http connection from '" + Request.RemoteSocket + "'" +
                                                                     Environment.NewLine + Environment.NewLine +
                                                                     Request.RawHTTPHeader +
                                                                     Environment.NewLine + Environment.NewLine +
                                                                     "Method => "         + Request.HTTPMethod      + Environment.NewLine +
                                                                     "URL => "            + Request.URI         + Environment.NewLine +
                                                                     "QueryString => "    + Request.QueryString     + Environment.NewLine +
                                                                     "Protocol => "       + Request.ProtocolName    + Environment.NewLine +
                                                                     "Version => "        + Request.ProtocolVersion + Environment.NewLine).ToUTF8Bytes()

                                             };

            });
        }
Пример #58
0
 public RequestContext(HTTPMethod method, string url)
 {
     Method = method;
     Url    = url;
 }
Пример #59
0
        public static Dictionary <string, string> GetPostData(
            string path, ref HttpListenerContext context, HTTPMethod method)
        {
            var formdata = new Dictionary <string, string>();

            switch (method)
            {
            case HTTPMethod.POST:
                var encoding = context.Request.ContentEncoding;
                var ctype    = context.Request.ContentType;
                var line     = string.Empty;

                using (var reader = new StreamReader(context.Request.InputStream, encoding))
                    line = reader.ReadToEnd();

                if (string.IsNullOrEmpty(line))
                {
                    return(null);
                }

                if (!string.IsNullOrEmpty(ctype))
                {
                    if (ctype.Split(';')[0] != "application/x-www-form-urlencoded")
                    {
                        var boundary = ctype.Split('=')[1];

                        if (string.IsNullOrEmpty(line))
                        {
                            return(null);
                        }

                        var start = line.IndexOf(boundary) + (boundary.Length + 2);
                        var end   = line.LastIndexOf(boundary) + boundary.Length;
                        line = line.Substring(start, end - start);
                        var formparts = new List <string>();

                        while (line.Contains(boundary))
                        {
                            if (line.StartsWith("Content-Disposition:"))
                            {
                                start = line.IndexOf("Content-Disposition: form-data;") +
                                        "Content-Disposition: form-data;".Length;

                                end = line.IndexOf(boundary);
                                formparts.Add(line.Substring(start, end - start).TrimStart());
                                line = line.Remove(0, end);
                            }

                            if (line.StartsWith(boundary))
                            {
                                if (line.Length > boundary.Length + 2)
                                {
                                    line = line.Remove(0, boundary.Length + 2);
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }

                        foreach (var item in formparts)
                        {
                            if (item.Contains("filename=\""))
                            {
                                var posttag = item.Substring(0, item.IndexOf(";"));
                                var data    = item;
                                start = data.IndexOf("filename=\"") + "filename=\"".Length;
                                data  = data.Remove(0, start);
                                end   = data.IndexOf("\"");

                                var filename = data.Substring(0, end);
                                if (string.IsNullOrEmpty(filename))
                                {
                                    continue;
                                }

                                if (filename.Contains("\\") || filename.Contains("/"))
                                {
                                    var parts = filename.Split(filename.Contains("\\") ? '\\' : '/');
                                    filename = parts[parts.Length - 1];
                                }

                                start = data.IndexOf("Content-Type: ");
                                data  = data.Remove(0, start);
                                end   = data.IndexOf("\r\n");
                                var cType = data.Substring(0, end + 2);
                                data = data.Remove(0, end + 2);
                                var filedata   = context.Request.ContentEncoding.GetBytes(data.Substring(2, data.IndexOf("\r\n--")));
                                var uploadpath = Filesystem.Combine(path, filename);

                                try
                                {
                                    File.WriteAllBytes(uploadpath, filedata);

                                    if (!formdata.ContainsKey(posttag))
                                    {
                                        formdata.Add(posttag, uploadpath);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Console.WriteLine(ex);
                                    continue;
                                }
                            }
                            else
                            {
                                var x = item.Replace("\r\n--", string.Empty).Replace("name=\"",
                                                                                     string.Empty).Replace("\"", string.Empty).Replace("\r\n\r\n", "|").Split('|');
                                x[0] = x[0].Replace(" file", string.Empty);

                                if (!formdata.ContainsKey(x[0]))
                                {
                                    formdata.Add(x[0], x[1]);
                                }
                            }
                        }

                        formparts.Clear();
                        formparts = null;
                    }
                    else
                    {
                        var tmp = line.Split('&');
                        for (var i = 0; i < tmp.Length; i++)
                        {
                            if (tmp[i].Contains("="))
                            {
                                var p = tmp[i].Split('=');
                                if (!formdata.ContainsKey(p[0]))
                                {
                                    formdata.Add(p[0], HttpUtility.UrlDecode(p[1]).ToString());
                                }
                            }
                        }
                    }
                }

                break;

            case HTTPMethod.GET:
                if (path.Contains("?") && path.Contains("&") && path.Contains("="))
                {
                    var get_params = HttpUtility.UrlDecode(path).Split('?')[1].Split('&');
                    for (var i = 0; i < get_params.Length; i++)
                    {
                        if (get_params[i].Contains("="))
                        {
                            var p = get_params[i].Split('=');
                            if (!formdata.ContainsKey(p[0]))
                            {
                                formdata.Add(p[0], p[1]);
                            }
                        }
                    }
                }

                break;

            default:
                break;
            }

            return(formdata);
        }
Пример #60
0
 public Controller(HTTPMethod method, string route, RouteCallback_A callback) :                              this(method.ToString(), route, callback)
 {
 }