public void TestExceptionBubble() { var instanceMock = new Mock <IAwesomeInterface>(); var cacheProviderMock = new Mock <ICacheProvider <IAwesomeInterface> >(); var sleipner = new SleipnerProxy <IAwesomeInterface>(instanceMock.Object, cacheProviderMock.Object); sleipner.Config(a => { a.For(b => b.ParameterlessMethod()).CacheFor(10).BubbleExceptionsWhenStale(); }); var proxyContext = ProxyRequest <IAwesomeInterface> .FromExpression(a => a.ParameterlessMethod()); var cachePolicy = sleipner.CachePolicyProvider.GetPolicy(proxyContext.Method, proxyContext.Parameters); var parameters = new object[0]; IEnumerable <string> result = new[] { "", "" }; var exception = new AwesomeException(); cacheProviderMock.Setup(a => a.GetItem(proxyContext, cachePolicy)).Returns(new CachedObject <IEnumerable <string> >(CachedObjectState.Stale, result)); instanceMock.Setup(a => a.ParameterlessMethod()).Throws(exception); sleipner.Object.ParameterlessMethod(); Thread.Sleep(1000); instanceMock.Verify(a => a.ParameterlessMethod(), Times.Once()); cacheProviderMock.Verify(a => a.GetItem(proxyContext, cachePolicy), Times.Once()); cacheProviderMock.Verify(a => a.StoreItem(proxyContext, cachePolicy, result), Times.Never()); cacheProviderMock.Verify(a => a.StoreException(proxyContext, cachePolicy, exception), Times.Once()); }
// PUT api/proxy/5 public HttpResponseMessage Put(ProxyRequest request) { HttpResponseMessage result = null; System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); byte[] arr = encoding.GetBytes(request.Content); HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create(request.Uri); httpRequest.Method = "PUT"; httpRequest.ContentType = "application/json"; httpRequest.ContentLength = arr.Length; httpRequest.KeepAlive = true; Stream dataStream = httpRequest.GetRequestStream(); dataStream.Write(arr, 0, arr.Length); dataStream.Close(); var response = (HttpWebResponse)httpRequest.GetResponse(); var buffer = new byte[response.ContentLength]; response.GetResponseStream().Read(buffer, 0, buffer.Length); var ms = String.Join("", buffer.Select(x => (char)x).ToArray()); result = new HttpResponseMessage { Content = new StringContent(ms), StatusCode = response.StatusCode }; return(result); }
private async Task <HttpResponseMessage> MakeHttpRequest(ProxyRequest proxyRequest, string scheme, string accessToken) { if (proxyRequest.Method.ToLower() == "get") { return(await _proxyHttpClient.GetAsync(proxyRequest.Url, scheme, accessToken)); } if (proxyRequest.Method.ToLower() == "post") { return(await _proxyHttpClient.PostAsync(proxyRequest.Url, proxyRequest.RequestBody, scheme, accessToken)); } if (proxyRequest.Method.ToLower() == "put") { return(await _proxyHttpClient.PutAsync(proxyRequest.Url, proxyRequest.RequestBody, scheme, accessToken)); } if (proxyRequest.Method.ToLower() == "patch") { return(await _proxyHttpClient.PatchAsync(proxyRequest.Url, proxyRequest.RequestBody, scheme, accessToken)); } if (proxyRequest.Method.ToLower() == "delete") { return(await _proxyHttpClient.DeleteAsync(proxyRequest.Url, scheme, accessToken)); } return(new HttpResponseMessage(HttpStatusCode.BadRequest)); }
public void TestReturnsCachedItemWithinPeriod_ListType() { var cache = new DictionaryCache <IAwesomeInterface>(); var configProvider = new BasicConfigurationProvider <IAwesomeInterface>(); configProvider.For(a => a.ParameteredMethod(Param.IsAny <string>(), Param.IsAny <int>(), Param.IsAny <List <string> >())).CacheFor(10); var proxyContext = ProxyRequest <IAwesomeInterface> .FromExpression(a => a.ParameteredMethod("a", 2, new List <string>() { "a", "b" })); var val = Enumerable.Empty <string>(); var cachePolicy = configProvider.GetPolicy(proxyContext.Method, proxyContext.Parameters); Assert.IsNotNull(cachePolicy, "Config provider didn't return a cache policy"); Assert.IsTrue(cachePolicy.CacheDuration == 10, "Cache provider returned an unexpected cache policy"); cache.StoreItem(proxyContext, cachePolicy, val); var returnedValue = cache.GetItem(proxyContext, cachePolicy); Assert.AreEqual(val, returnedValue.Object); }
public void TestILGenerator() { var generator = new ILGenProxyGenerator(); var proxyType = generator.CreateProxy <IAwesomeInterface>(); var instanceMock = new Mock <IAwesomeInterface>(); var proxyHandlerMock = new Mock <IProxyHandler <IAwesomeInterface> >(); var proxy = (IAwesomeInterface)Activator.CreateInstance(proxyType, instanceMock.Object, proxyHandlerMock.Object); proxy.FaulyCachedMethod(); var proxyRequest1 = ProxyRequest <IAwesomeInterface> .FromExpression(a => a.FaulyCachedMethod()); instanceMock.Verify(a => a.FaulyCachedMethod(), Times.Never()); proxyHandlerMock.Verify(a => a.HandleRequest(proxyRequest1), Times.Once()); proxy.VoidMethod(); instanceMock.Verify(a => a.VoidMethod(), Times.Once()); proxy.ParameteredMethod("", 1); var proxyRequest2 = ProxyRequest <IAwesomeInterface> .FromExpression(a => a.ParameteredMethod("", 1)); instanceMock.Verify(a => a.ParameteredMethod("", 1), Times.Never()); proxyHandlerMock.Verify(a => a.HandleRequest(proxyRequest2)); }
private static void InternalSend(Socket socket, ProxyRequest request) { var proxyTunnel = new ProxyTunnel(socket, request); proxyTunnel.CreateTunnel(); proxyTunnel.Send(); }
/// <summary> /// After intercepting the request from the client, this starts the initialization of processing a request for the client. /// and handling an TLS/SSL handshake if required. Returning a populated <see cref="ProxyRequest"/> object defining the data needed to /// process a request and response to the remote server. /// </summary> /// <returns>Returns a <see cref="ProxyRequest"/> object encapsulating the client's request.</returns> public ProxyRequest ProcessRequest() { var request = new ProxyRequest { IPAddress = ((IPEndPoint)this.TcpClient.Client.RemoteEndPoint).Address, RequestDateTime = DateTime.Now }; // Initialize the request object. populating the data based on the http headers within the client stream this.ClientStreamReader = new StreamReader(this.ClientStream); var httpCommand = this.ClientStreamReader.ReadLine(); if (string.IsNullOrEmpty(httpCommand)) { request.SuccessfulInitializaiton = false; this.NLogger.Warn("Data header of a proxy request was null or empty."); return(request); } var httpCommandSplit = httpCommand.Split(' '); request.Method = httpCommandSplit[0]; request.RemoteUri = httpCommandSplit[1]; request.HttpVersion = new Version(httpCommandSplit[2].Split('/')[1]); request.SuccessfulInitializaiton = request.Method != "CONNECT" || this.SslHandshake(request); return(request); }
private ProxySettings GetProxySettings(int moduleId, ProxyRequest proxyRequest) { ProxySettings proxySettings; try { // TODO : Get proxy settings from the database or other file with moduleId proxySettings = new ProxySettings(); proxySettings.ConnectionType = ConnectionType.LDAP; proxySettings.Url = ""; proxySettings.Timeout = 60000; var parameters = new Dictionary <string, string>(); parameters.Add("BindDn", @""); parameters.Add("BindCredentials", @""); parameters.Add("SearchBase", @""); parameters.Add("SearchFilter", @""); parameters.Add("AdminCn", @""); proxySettings.Parameters = parameters; return(proxySettings); } catch (Exception ex) { throw ex; } }
public CachedObject <TResult> GetItem <TResult>(ProxyRequest <T, TResult> proxyRequest, CachePolicy cachePolicy) { var cacheKey = new DictionaryCacheKey(proxyRequest.Method, proxyRequest.Parameters); if (_cache.ContainsKey(cacheKey)) { var cachedObject = _cache[cacheKey]; if (cachedObject.ThrownException != null && cachedObject.Created.AddSeconds(cachePolicy.ExceptionCacheDuration) > DateTime.Now) { return(new CachedObject <TResult>(CachedObjectState.Exception, cachedObject.ThrownException)); } else if (cachedObject.ThrownException != null) { return(new CachedObject <TResult>(CachedObjectState.None, null)); } if (cachedObject.AbsoluteDuration.TotalSeconds > 0 && cachedObject.Created + cachedObject.AbsoluteDuration < DateTime.Now) { return(new CachedObject <TResult>(CachedObjectState.None, null)); } return(new CachedObject <TResult>(cachedObject.IsExpired ? CachedObjectState.Stale : CachedObjectState.Fresh, (TResult)cachedObject.Object)); } return(new CachedObject <TResult>(CachedObjectState.None, null)); }
public void TestGetItemExceptionExpired() { var memcachedMock = new Mock <IMemcachedClient>(); var enyimProvider = new EnyimMemcachedProvider <IAwesomeInterface>(memcachedMock.Object); var cachePolicy = new CachePolicy() { CacheDuration = 2 }; var proxyContext = ProxyRequest <IAwesomeInterface> .FromExpression(a => a.ParameteredMethod("", 1)); var hashKey = proxyContext.CreateHash(); var exception = new Exception("Rofl exception"); object val = new MemcachedObject <IEnumerable <string> >() { Created = DateTime.Now.AddSeconds(-11), IsException = true, Exception = exception }; memcachedMock.Setup(a => a.TryGet(hashKey, out val)).Returns(true); var result = enyimProvider.GetItem <IEnumerable <string> >(proxyContext, cachePolicy); Assert.IsTrue(result.State == CachedObjectState.None); Assert.IsNull(result.ThrownException, "Provider did not return null in exception field"); Assert.IsNull(result.Object, "Provider did not return null in object field"); }
public void TestGetItemStale() { var memcachedMock = new Mock <IMemcachedClient>(); var enyimProvider = new EnyimMemcachedProvider <IAwesomeInterface>(memcachedMock.Object); var cachePolicy = new CachePolicy() { CacheDuration = 10 }; var proxyContext = ProxyRequest <IAwesomeInterface> .FromExpression(a => a.ParameteredMethod("", 1)); var hashKey = proxyContext.CreateHash(); var obj = new[] { "", "" }; object val = new MemcachedObject <IEnumerable <string> >() { Created = DateTime.Now.AddSeconds(-15), Object = obj }; memcachedMock.Setup(a => a.TryGet(hashKey, out val)).Returns(true); var result = enyimProvider.GetItem <IEnumerable <string> >(proxyContext, cachePolicy); Assert.IsTrue(result.State == CachedObjectState.Stale, "Provider did not return stale, but: " + result.State); Assert.AreEqual(obj, result.Object, "Provider did not return object"); Assert.IsNull(result.ThrownException, "Provider did not return null in exception field"); }
public CachedObject <TResult> GetItem <TResult>(ProxyRequest <T, TResult> proxyRequest, CachePolicy cachePolicy) { var key = proxyRequest.CreateHash(); object value; if (_client.TryGet(key, out value)) { var cachedObject = value as MemcachedObject <TResult>; if (cachedObject == null) { return(new CachedObject <TResult>(CachedObjectState.None, null)); } if (cachedObject.IsException && cachedObject.Created.AddSeconds(cachePolicy.ExceptionCacheDuration) > DateTime.Now) { return(new CachedObject <TResult>(CachedObjectState.Exception, cachedObject.Exception)); } else if (cachedObject.IsException) { return(new CachedObject <TResult>(CachedObjectState.None, null)); } var fresh = cachedObject.Created.AddSeconds(cachePolicy.CacheDuration) > DateTime.Now; var state = fresh ? CachedObjectState.Fresh : CachedObjectState.Stale; return(new CachedObject <TResult>(state, cachedObject.Object)); } return(new CachedObject <TResult>(CachedObjectState.None, null)); }
/// <summary> /// Called to handle workflow related request messages received from the <b>temporal-proxy</b>. /// </summary> /// <param name="request">The request message.</param> /// <returns>The tracking <see cref="Task"/>.</returns> internal async Task OnProxyRequestAsync(ProxyRequest request) { await SyncContext.Clear; Covenant.Requires <ArgumentNullException>(request != null, nameof(request)); ProxyReply reply; switch (request.Type) { case InternalMessageTypes.WorkflowInvokeRequest: reply = await OnInvokeAsync((WorkflowInvokeRequest)request); break; case InternalMessageTypes.WorkflowSignalInvokeRequest: reply = await OnSignalAsync((WorkflowSignalInvokeRequest)request); break; case InternalMessageTypes.WorkflowQueryInvokeRequest: reply = await OnQueryAsync((WorkflowQueryInvokeRequest)request); break; default: throw new InvalidOperationException($"Unexpected message type [{request.Type}]."); } await Client.ProxyReplyAsync(request, reply); }
/// <summary> /// Called to handle a workflow related request message received from the cadence-proxy. /// </summary> /// <param name="client">The client that received the request.</param> /// <param name="request">The request message.</param> /// <returns>The tracking <see cref="Task"/>.</returns> internal static async Task OnProxyRequestAsync(CadenceClient client, ProxyRequest request) { Covenant.Requires <ArgumentNullException>(client != null); Covenant.Requires <ArgumentNullException>(request != null); ProxyReply reply; switch (request.Type) { case InternalMessageTypes.ActivityInvokeRequest: reply = await OnActivityInvokeRequest(client, (ActivityInvokeRequest)request); break; case InternalMessageTypes.ActivityStoppingRequest: reply = await ActivityStoppingRequest(client, (ActivityStoppingRequest)request); break; default: throw new InvalidOperationException($"Unexpected message type [{request.Type}]."); } await client.ProxyReplyAsync(request, reply); }
public void StoreException <TResult>(ProxyRequest <T, TResult> proxyRequest, CachePolicy cachePolicy, Exception exception) { var cacheKey = new DictionaryCacheKey(proxyRequest.Method, proxyRequest.Parameters); var duration = TimeSpan.FromSeconds(cachePolicy.CacheDuration); var absoluteDuration = TimeSpan.FromSeconds(cachePolicy.MaxAge); _cache[cacheKey] = new DictionaryCachedItem(exception, duration, absoluteDuration); }
public RPCProxyObject GetProxyObject(string name) { BaseRequest req = new ProxyRequest(name); this.Send(req); BaseResponse resp = this.WaitForResponse(req, 5000000); return(new RPCProxyObject(this, (resp as ProxyResponse).ObjectID)); }
public void TestParameterless() { var configuredMethod = GetConfiguredMethod <IAwesomeInterface>(a => a.ParameterlessMethod()); var proxyContext = ProxyRequest <IAwesomeInterface> .FromExpression(a => a.ParameterlessMethod()); var matched = configuredMethod.IsMatch(proxyContext.Method, proxyContext.Parameters); Assert.IsTrue(matched, "MethodConfig didn't match"); }
public void Purge <TResult>(Expression <Func <T, TResult> > expression) { var methodInfo = SymbolExtensions.GetMethodInfo(expression); var parameters = SymbolExtensions.GetParameter(expression); var proxyExpression = new ProxyRequest <T, TResult>(methodInfo, parameters); var hash = proxyExpression.CreateHash(); _client.Remove(hash); }
public void Purge <TResult>(Expression <Func <T, TResult> > expression) { var methodInfo = SymbolExtensions.GetMethodInfo(expression); var parameters = SymbolExtensions.GetParameter(expression); var proxyExpression = new ProxyRequest <T, TResult>(methodInfo, parameters); var cacheKey = new DictionaryCacheKey(proxyExpression.Method, proxyExpression.Parameters); _cache.Remove(cacheKey); }
public bool TryGetRaw <TResult>(ProxyRequest <T, TResult> proxyRequest, out object result) { var cacheKey = new DictionaryCacheKey(proxyRequest.Method, proxyRequest.Parameters); if (_cache.ContainsKey(cacheKey)) { result = _cache[cacheKey]; return(true); } result = null; return(false); }
private BaseResponse _handler_Proxy(BasePacket packet) { ProxyRequest p = packet as ProxyRequest; ProxyHolder proxy = this.GetProxyByName(p.Name); if (proxy == null) { throw new Exception("Proxy not found: " + p.Name); } return(new ProxyResponse(proxy.ObjectID, p)); }
public virtual IProxy GetProxy(int moduleId, ProxyRequest proxyRequest) { var proxySettings = GetProxySettings(moduleId, proxyRequest); var proxy = this._proxies.ToList().FirstOrDefault(p => p.ConnectionType == proxySettings.ConnectionType); if (proxy != null) { proxy.Initialize(proxySettings); return(proxy); } throw new ApplicationException("Proxy not found for :" + proxySettings.ConnectionType); }
public void TestPurgeItem() { var memcachedMock = new Mock <IMemcachedClient>(); var enyimProvider = new EnyimMemcachedProvider <IAwesomeInterface>(memcachedMock.Object); var proxyContext = ProxyRequest <IAwesomeInterface> .FromExpression(a => a.ParameteredMethod("", 1)); var hashKey = proxyContext.CreateHash(); enyimProvider.Purge(a => a.ParameteredMethod("", 1)); memcachedMock.Verify(a => a.Remove(hashKey), Times.Once()); }
private void UpdateGUI() { for (; LastProxyOutputIndex < proxyManager.Output.Requests.Count; LastProxyOutputIndex++) { ProxyRequest proxyRequest = proxyManager.Output.Requests[LastProxyOutputIndex]; Requests.Add(proxyRequest); ListViewItem Item = new ListViewItem(); Item.Text = proxyRequest.RequestTime.ToLongTimeString(); Item.SubItems.Add(proxyRequest.URL); Item.SubItems.Add(proxyRequest.POST); listViewSnifferOutput.Items.Add(Item); } }
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////// private void WwwProxy_PostResponse(ProxyRequest request, ProxyResponse response) { try { object responseFilter = scriptEngine_.Operations.GetMember <object>(wwwProxyFilterInstance_, "post_response_filter"); object[] parameters = { request, response }; scriptEngine_.Operations.Call(responseFilter, parameters); } catch (Exception e) { debugLog_.Write("WwwProxyScripting.WwwProxy_PostResponse()", e.ToString()); } }
/// <summary> /// Handle the TLS/SSL hande upgrade for the request provided. /// </summary> /// <param name="request"> /// The <see cref="ProxyRequest"/> object associated with the TLS/SSL handshake /// </param> /// <returns>Returns a <see cref="bool"/> value indicating whether or not the handshake was successful</returns> private bool SslHandshake(ProxyRequest request) { request.IsHttps = true; // Browser wants to create a secure tunnel // instead we are perform a man in the middle request.RemoteUri = "https://" + request.RemoteUri; var cert = CertificateService.GetSelfSignedCertificate(new Uri(request.RemoteUri), this.IssuerKey); //read and ignore headers while (!string.IsNullOrEmpty(this.ClientStreamReader.ReadLine())) { } //tell the client that a tunnel has been established var connectStreamWriter = new StreamWriter(this.ClientStream); connectStreamWriter.WriteLine($"HTTP/{request.HttpVersion.ToString(2)} 200 Connection established"); connectStreamWriter.WriteLine ($"Timestamp: {DateTime.Now.ToString(CultureInfo.InvariantCulture)}"); connectStreamWriter.WriteLine("Proxy-agent: http-logger.net"); connectStreamWriter.WriteLine(); connectStreamWriter.Flush(); //now-create an https "server" this.SslStream = new SslStream(this.ClientStream, false); this.SslStream.AuthenticateAsServer(cert, false, SslProtocols.Tls | SslProtocols.Ssl3 | SslProtocols.Ssl2, true); //HTTPS server created - we can now decrypt the client's traffic this.ClientStreamReader = new StreamReader(this.SslStream); //read the new http command. var httpCommand = this.ClientStreamReader.ReadLine(); if (string.IsNullOrEmpty(httpCommand)) { this.ClientStreamReader.Close(); this.ClientStream.Close(); this.SslStream.Close(); return(false); } var httpCommandSplit = httpCommand.Split(' '); request.Method = httpCommandSplit[0]; request.RemoteUri += httpCommandSplit[1]; return(true); }
public void Test_ProxyRequest() { // Ensures that we can serialize and deserialize request messages. ProxyRequest message; using (var stream = new MemoryStream()) { // Empty message. message = new ProxyRequest(); stream.SetLength(0); stream.Write(message.SerializeAsBytes(ignoreTypeCode: true)); stream.Seek(0, SeekOrigin.Begin); message = ProxyMessage.Deserialize <ProxyRequest>(stream, ignoreTypeCode: true); Assert.NotNull(message); Assert.Equal(0, message.ClientId); Assert.Equal(0, message.RequestId); Assert.False(message.IsCancellable); // Round-trip message.ClientId = 444; message.RequestId = 555; Assert.Equal(555, message.RequestId); message.IsCancellable = true; stream.SetLength(0); stream.Write(message.SerializeAsBytes(ignoreTypeCode: true)); stream.Seek(0, SeekOrigin.Begin); message = ProxyMessage.Deserialize <ProxyRequest>(stream, ignoreTypeCode: true); Assert.NotNull(message); Assert.Equal(444, message.ClientId); Assert.Equal(555, message.RequestId); Assert.True(message.IsCancellable); // Clone() message = (ProxyRequest)message.Clone(); Assert.NotNull(message); Assert.Equal(444, message.ClientId); Assert.Equal(555, message.RequestId); Assert.True(message.IsCancellable); } }
public override void Handle(ProxyRequest req) { using (var remoteClient = new TcpClient()) { this.CancelSource.Token.Register(() => { try { remoteClient.Close(); } catch { } }); try { remoteClient.Connect(req.GetEndPoint()); } catch { this.ProxyStream.Write(ConnectionFailed, 0, ConnectionFailed.Length); throw; } if (req.KeepAlive) { this.ProxyStream.Write(ConnectionEstablishedKA, 0, ConnectionEstablishedKA.Length); } else { this.ProxyStream.Write(ConnectionEstablished, 0, ConnectionEstablished.Length); } using (var remoteStream = remoteClient.GetStream()) { var tasks = this.CopyToAsyncBoth(remoteStream); try { Task.WaitAll(tasks); } catch { } } } }
public async Task <Message> ExecuteWebhook(ProxyRequest req) { _logger.Verbose("Invoking webhook in channel {Channel}", req.ChannelId); // Get a webhook, execute it var webhook = await _webhookCache.GetWebhook(req.ChannelId); var webhookMessage = await ExecuteWebhookInner(webhook, req); // Log the relevant metrics _metrics.Measure.Meter.Mark(BotMetrics.MessagesProxied); _logger.Information("Invoked webhook {Webhook} in channel {Channel} (thread {ThreadId})", webhook.Id, req.ChannelId, req.ThreadId); return(webhookMessage); }
public bool TryGetRaw <TResult>(ProxyRequest <T, TResult> proxyRequest, out object result) { var key = proxyRequest.CreateHash(); object value; if (_client.TryGet(key, out value)) { var cachedObject = value as MemcachedObject <TResult>; if (cachedObject != null) { result = cachedObject; return(true); } } result = null; return(false); }