public void ProcessRequest() { string strOutput; switch (this.QS["action"]) { case "GetLog": this.Method = new GetLog(ref this.QS); break; default: break; } strOutput = this.Method.DoRequest(); byte[] msg = System.Text.Encoding.UTF8.GetBytes(strOutput); this.Response.StatusCode = (int)HttpStatusCode.OK; this.Response.ContentType = "application/json"; this.Response.ContentLength64 = msg.Length; using (Stream s = this.Response.OutputStream) s.Write(msg, 0, msg.Length); }
public API(ref HttpListenerContext context, Server myServer) { this.QS = context.Request.QueryString; this.Request = context.Request; this.Response = context.Response; this.Method = new APIMethod(ref this.QS); }
/// <summary> /// Update the providers with the provided serialization object. /// </summary> /// <param name="serial"></param> internal void Import(APIProvidersSettings serial) { m_customProviders.Clear(); CurrentProvider = DefaultProvider; // Providers foreach (SerializableAPIProvider sProvider in serial.CustomProviders) { APIProvider provider = new APIProvider { Name = sProvider.Name, Url = new Uri(sProvider.Address), SupportsCompressedResponse = sProvider.SupportsCompressedResponse }; // Providers' methods foreach (SerializableAPIMethod sMethod in sProvider.Methods) { Enum method = APIMethods.Methods.FirstOrDefault(x => x.ToString() == sMethod.MethodName); if (method == null) { continue; } APIMethod apiMethod = provider.GetMethod(method); if (apiMethod != null) { apiMethod.Path = sMethod.Path; } } // Add this provider to our inner list m_customProviders.Add(provider); } // Current provider APIProvider newCurrentProvider = this[serial.CurrentProviderName]; if (newCurrentProvider != null) { CurrentProvider = newCurrentProvider; } // Test Provider is only available in debug mode if (serial.CurrentProviderName == TestProvider.Name) { CurrentProvider = EveMonClient.IsDebugBuild ? TestProvider : DefaultProvider; } }
protected async Task <TResult> RunAsync <TResult>(APIMethod method, string interfaceName, string name, int version, Dictionary <string, object> parameter) { parameter.Add("key", this.apiKey); var url = BuildURL(interfaceName, name, version); string json; switch (method) { case APIMethod.Get: json = await RunGetAsync(url, parameter); break; case APIMethod.Post: throw new InvalidOperationException("What part of ObsoleteAttribute don't you understand?"); ////json = await RunPostAsync(url, parameter); ////break; default: throw new ArgumentException("Unknown 'method' value '" + method + "'"); } // Hacky casting ahoy! We know the type cast is safe, but the compiler doesn't. if (typeof(TResult) == typeof(string)) { return((TResult)(object)json); } else if (typeof(TResult) == typeof(JToken)) { return((TResult)(object)JToken.Parse(json)); } else { return(JsonConvert.DeserializeObject <TResult>(json)); } }
private string BuildRequestURI(APIMethod method, int key = 0) { switch (method) { case APIMethod.Load: return($"{_apiPrefix}/{_apiID}"); case APIMethod.Create: return($"{_apiPrefix}/{_apiID}"); case APIMethod.Read: return($"{_apiPrefix}/{_apiID}/{key}"); case APIMethod.Update: return($"{_apiPrefix}/{_apiID}/{key}"); case APIMethod.Delete: return($"{_apiPrefix}/{_apiID}/{key}"); default: throw new ArgumentException("BuildRequestURI"); } }
/// <summary> /// General > API Providers > Add. /// Displays the API provider configuration. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnAddAPIServer_Click(object sender, EventArgs e) { SerializableAPIProvider newProvider = new SerializableAPIProvider(); newProvider.Methods.AddRange(APIMethod.CreateDefaultSet().Select( apiMethod => new SerializableAPIMethod { MethodName = apiMethod.Method.ToString(), Path = apiMethod.Path })); using (APISettingsForm apiForm = new APISettingsForm(m_settings.APIProviders, newProvider)) { DialogResult result = apiForm.ShowDialog(); if (result != DialogResult.OK) { return; } m_settings.APIProviders.CustomProviders.Add(newProvider); InitializeAPIProvidersDropDown(); cbAPIServer.SelectedIndex = cbAPIServer.Items.Count - 1; } }
private string BuildRequestURI(APIMethod method, TKey key = default(TKey)) { switch (method) { case APIMethod.Load: return($"{_apiPrefix}/{_apiId}"); case APIMethod.Create: return($"{_apiPrefix}/{_apiId}"); case APIMethod.Read: return($"{_apiPrefix}/{_apiId}/{key}"); case APIMethod.Update: return($"{_apiPrefix}/{_apiId}/{key}"); case APIMethod.Delete: return($"{_apiPrefix}/{_apiId}/{key}"); default: //Shouldn't it be URL?? throw new ArgumentException("BuildRequestURI"); } }
/// <summary> /// Construct an HttpWebRequest object using the specified CIXAPI function, format /// and method. Any authentication rider is attached to the header as required and /// the appropriate content type set. /// </summary> /// <param name="apiFunction">The API function name</param> /// <param name="username">Authentication username</param> /// <param name="password">Authentication password</param> /// <param name="format">The API format requested (JSON or XML)</param> /// <param name="method">The API method required (GET or POST)</param> /// <param name="postObject">For POST, this is the object to be posted</param> /// <param name="queryString">Optional query string for the URL</param> /// <returns>A constructed HttpWebRequest</returns> private static HttpWebRequest Create(string apiFunction, string username, string password, APIFormat format, APIMethod method, object postObject, string queryString) { HttpWebRequest request; byte[] postMessageBytes; if (username == null || password == null) { return null; } if (method == APIMethod.POST) { var o = postObject as Image; if (o != null) { Image postImage = o; ImageConverter converter = new ImageConverter(); postMessageBytes = (byte[])converter.ConvertTo(postImage, typeof(byte[])); if (postMessageBytes == null) { return null; } request = (HttpWebRequest)WebRequest.Create(MakeURL(apiFunction, format, queryString)); request.Method = APIMethodToString(method); if (ImageFormat.Jpeg.Equals(postImage.RawFormat)) { request.ContentType = "image/jpeg"; } if (ImageFormat.Gif.Equals(postImage.RawFormat)) { request.ContentType = "image/gif"; } if (ImageFormat.Png.Equals(postImage.RawFormat)) { request.ContentType = "image/png"; } if (ImageFormat.Bmp.Equals(postImage.RawFormat)) { request.ContentType = "image/bitmap"; } request.ContentLength = postMessageBytes.Length; } else { var s = postObject as string; if (s != null) { string postString = s; ASCIIEncoding encoder = new ASCIIEncoding(); postMessageBytes = encoder.GetBytes(postString); request = (HttpWebRequest)WebRequest.Create(MakeURL(apiFunction, format, queryString)); request.Method = APIMethodToString(method); request.ContentLength = postMessageBytes.Length; request.ContentType = "application/text"; } else { string postMessageXml; using (MemoryStream memoryStream = new MemoryStream()) { using (StreamReader reader = new StreamReader(memoryStream)) { DataContractSerializer serializer = new DataContractSerializer(postObject.GetType()); serializer.WriteObject(memoryStream, postObject); memoryStream.Position = 0; postMessageXml = reader.ReadToEnd(); } } // Messages are posted as 7-bit ASCII. UTF8Encoding encoder = new UTF8Encoding(); postMessageBytes = encoder.GetBytes(postMessageXml); request = (HttpWebRequest)WebRequest.Create(MakeURL(apiFunction, format, queryString)); request.Method = APIMethodToString(method); request.ContentLength = encoder.GetByteCount(postMessageXml); request.ContentType = "application/xml; charset=utf-8"; request.Accept = "application/xml; charset=utf-8"; } } } else { request = (HttpWebRequest)WebRequest.Create(MakeURL(apiFunction, format, queryString)); request.Method = APIMethodToString(method); postMessageBytes = null; if (format == APIFormat.XML) { request.ContentType = "application/xml; charset=utf-8"; request.Accept = "application/xml; charset=utf-8"; } else { request.ContentType = "application/json"; request.Accept = "application/json"; } } string authInfo = username + ":" + password; authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo)); request.Headers.Add("Authorization", "Basic " + authInfo); request.PreAuthenticate = true; if (postMessageBytes != null) { Stream dataStream = request.GetRequestStream(); dataStream.Write(postMessageBytes, 0, postMessageBytes.Length); dataStream.Close(); } return request; }
/// <summary> /// Converts the specified APIMethod to a string. /// </summary> /// <param name="method">The API method required (GET or POST)</param> /// <returns>The string representing the API method</returns> private static string APIMethodToString(APIMethod method) { return method == APIMethod.GET ? "GET" : "POST"; }
/// <summary> /// Converts the specified APIMethod to a string. /// </summary> /// <param name="method">The API method required (GET or POST)</param> /// <returns>The string representing the API method</returns> private static string APIMethodToString(APIMethod method) { return(method == APIMethod.GET ? "GET" : "POST"); }
/// <summary> /// Construct an HttpWebRequest object using the specified CIXAPI function, format /// and method. Any authentication rider is attached to the header as required and /// the appropriate content type set. /// </summary> /// <param name="apiFunction">The API function name</param> /// <param name="username">Authentication username</param> /// <param name="password">Authentication password</param> /// <param name="format">The API format requested (JSON or XML)</param> /// <param name="method">The API method required (GET or POST)</param> /// <param name="postObject">For POST, this is the object to be posted</param> /// <param name="queryString">Optional query string for the URL</param> /// <returns>A constructed HttpWebRequest</returns> private static HttpWebRequest Create(string apiFunction, string username, string password, APIFormat format, APIMethod method, object postObject, string queryString) { HttpWebRequest wrGeturl; byte[] postMessageBytes; if (username == null || password == null) { return(null); } if (method == APIMethod.POST) { var o = postObject as Image; if (o != null) { Image postImage = o; ImageConverter converter = new ImageConverter(); postMessageBytes = (byte[])converter.ConvertTo(postImage, typeof(byte[])); if (postMessageBytes == null) { return(null); } wrGeturl = (HttpWebRequest)WebRequest.Create(MakeURL(apiFunction, format, queryString)); wrGeturl.Method = APIMethodToString(method); if (ImageFormat.Jpeg.Equals(postImage.RawFormat)) { wrGeturl.ContentType = "image/jpeg"; } if (ImageFormat.Gif.Equals(postImage.RawFormat)) { wrGeturl.ContentType = "image/gif"; } if (ImageFormat.Png.Equals(postImage.RawFormat)) { wrGeturl.ContentType = "image/png"; } if (ImageFormat.Bmp.Equals(postImage.RawFormat)) { wrGeturl.ContentType = "image/bitmap"; } wrGeturl.ContentLength = postMessageBytes.Length; } else { var s = postObject as string; if (s != null) { string postString = s; ASCIIEncoding encoder = new ASCIIEncoding(); postMessageBytes = encoder.GetBytes(postString); wrGeturl = (HttpWebRequest)WebRequest.Create(MakeURL(apiFunction, format, queryString)); wrGeturl.Method = APIMethodToString(method); wrGeturl.ContentLength = postMessageBytes.Length; wrGeturl.ContentType = "application/text"; } else { StringBuilder postMessageXml = new StringBuilder(); using (XmlWriter writer = XmlWriter.Create(postMessageXml)) { XmlSerializer serializer = new XmlSerializer(postObject.GetType()); serializer.Serialize(writer, postObject); } // Remove the header postMessageXml.Replace("<?xml version=\"1.0\" encoding=\"utf-16\"?>", ""); // Messages are posted as 7-bit ASCII. UTF8Encoding encoder = new UTF8Encoding(); postMessageBytes = encoder.GetBytes(postMessageXml.ToString()); wrGeturl = (HttpWebRequest)WebRequest.Create(MakeURL(apiFunction, format, queryString)); wrGeturl.Method = APIMethodToString(method); wrGeturl.ContentLength = encoder.GetByteCount(postMessageXml.ToString()); wrGeturl.ContentType = "application/xml; charset=utf-8"; wrGeturl.Accept = "application/xml; charset=utf-8"; } } } else { wrGeturl = (HttpWebRequest)WebRequest.Create(MakeURL(apiFunction, format, queryString)); wrGeturl.Method = APIMethodToString(method); postMessageBytes = null; if (format == APIFormat.XML) { wrGeturl.ContentType = "application/xml; charset=utf-8"; wrGeturl.Accept = "application/xml; charset=utf-8"; } else { wrGeturl.ContentType = "application/json"; wrGeturl.Accept = "application/json"; } } string authInfo = username + ":" + password; authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo)); wrGeturl.Headers.Add("Authorization", "Basic " + authInfo); wrGeturl.PreAuthenticate = true; if (postMessageBytes != null) { Stream dataStream = wrGeturl.GetRequestStream(); dataStream.Write(postMessageBytes, 0, postMessageBytes.Length); dataStream.Close(); } return(wrGeturl); }
public SteamAPICallAttribute(string name, int version, APIMethod method = APIMethod.Get) { this.Name = name; this.Version = version; this.Method = method; }
public static T CallAPI <T>(string url, APIMethod method, object objReq, CallAPIOption option = null) where T : class { var log = new StringBuilder(); log.AppendLine(string.Concat($"Before call api url: {url}", Environment.NewLine, $"input: {JsonConvert.SerializeObject(objReq)}")); T result = null; try { if (APIMethod.GET.Equals(method) && objReq != null) { var dictionary = JsonConvert.DeserializeObject <Dictionary <string, string> >(JsonConvert.SerializeObject(objReq)); string queryString = string.Join("&", dictionary.Select(x => string.Format("{0}={1}", x.Key, HttpUtility.UrlEncode(x.Value)))); url += string.Format("?{0}", queryString); } HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = method.ToString(); request.KeepAlive = false; request.ContentType = "application/json; charset=UTF-8"; if (option != null) { if (option.Timeout > 0) { request.Timeout = option.Timeout; } if (option.Headers.Keys.Any()) { foreach (var item in option.Headers) { request.Headers.Add(item.Key, item.Value); } } if (option.IsInternal) { request.Headers.Add("HEADER_AUTHORIZATION", "your token"); } } if (APIMethod.POST.Equals(method)) { byte[] byteArray = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(objReq)); request.ContentLength = byteArray.Length; Stream dataStream = request.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Close(); } WebResponse response = request.GetResponse(); HttpStatusCode statusCode = ((HttpWebResponse)response).StatusCode; if (statusCode.Equals(HttpStatusCode.OK)) { string responseString = string.Empty; using (var streamReader = new StreamReader(response.GetResponseStream())) { responseString = streamReader.ReadToEnd(); } result = JsonConvert.DeserializeObject <T>(responseString); } else { log.AppendLine($"ResponseCode: {statusCode}"); string responseString = string.Empty; using (var streamReader = new StreamReader(response.GetResponseStream())) { responseString = streamReader.ReadToEnd(); } log.AppendLine($"Response: {JsonConvert.DeserializeObject<dynamic>(responseString)}"); } } catch (Exception ex) { log.AppendLine($"Exception: {ex.ToString()}"); } finally { // TODO: write log //LoggingHelper.SetLogStep(log.ToString()); } return(result); }
private static HttpWebRequest Create(string apiFunction, string username, string password, APIFormat format, APIMethod method, object postObject, string queryString) { HttpWebRequest request; byte[] postMessageBytes; if (username == null || password == null) { return(null); } if (method == APIMethod.POST) { var o = postObject as Image; if (o != null) { Image postImage = o; ImageConverter converter = new ImageConverter(); postMessageBytes = (byte[])converter.ConvertTo(postImage, typeof(byte[])); if (postMessageBytes == null) { return(null); } request = (HttpWebRequest)WebRequest.Create(MakeURL(apiFunction, format, queryString)); request.Method = APIMethodToString(method); if (ImageFormat.Jpeg.Equals(postImage.RawFormat)) { request.ContentType = "image/jpeg"; } if (ImageFormat.Gif.Equals(postImage.RawFormat)) { request.ContentType = "image/gif"; } if (ImageFormat.Png.Equals(postImage.RawFormat)) { request.ContentType = "image/png"; } if (ImageFormat.Bmp.Equals(postImage.RawFormat)) { request.ContentType = "image/bitmap"; } request.ContentLength = postMessageBytes.Length; } else { var s = postObject as string; if (s != null) { string postString = s; ASCIIEncoding encoder = new ASCIIEncoding(); postMessageBytes = encoder.GetBytes(postString); request = (HttpWebRequest)WebRequest.Create(MakeURL(apiFunction, format, queryString)); request.Method = APIMethodToString(method); request.ContentLength = postMessageBytes.Length; request.ContentType = "application/text"; } else { string postMessageXml; using (MemoryStream memoryStream = new MemoryStream()) { using (StreamReader reader = new StreamReader(memoryStream)) { DataContractSerializer serializer = new DataContractSerializer(postObject.GetType()); serializer.WriteObject(memoryStream, postObject); memoryStream.Position = 0; postMessageXml = reader.ReadToEnd(); } } // Messages are posted as 7-bit ASCII. UTF8Encoding encoder = new UTF8Encoding(); postMessageBytes = encoder.GetBytes(postMessageXml); request = (HttpWebRequest)WebRequest.Create(MakeURL(apiFunction, format, queryString)); request.Method = APIMethodToString(method); request.ContentLength = encoder.GetByteCount(postMessageXml); request.ContentType = "application/xml; charset=utf-8"; request.Accept = "application/xml; charset=utf-8"; } } } else { request = (HttpWebRequest)WebRequest.Create(MakeURL(apiFunction, format, queryString)); request.Method = APIMethodToString(method); postMessageBytes = null; if (format == APIFormat.XML) { request.ContentType = "application/xml; charset=utf-8"; request.Accept = "application/xml; charset=utf-8"; } else { request.ContentType = "application/json"; request.Accept = "application/json"; } } string authInfo = username + ":" + password; authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo)); request.Headers.Add("Authorization", "Basic " + authInfo); request.PreAuthenticate = true; if (postMessageBytes != null) { Stream dataStream = request.GetRequestStream(); dataStream.Write(postMessageBytes, 0, postMessageBytes.Length); dataStream.Close(); } return(request); }
public static string ProcessIncrementDecrementValueRequest(byte[] stream, HttpWebRequest newRequest, HttpListenerContext context, APIMethod method) { string bodyParams = System.Text.Encoding.Default.GetString(stream); var nvc = HttpUtility.ParseQueryString(bodyParams); int productId = -1; int.TryParse(nvc.Get("ProductId"), out productId); var licenseKey = nvc.Get("Key"); int intValue = -1; int.TryParse(nvc.Get("IntValue"), out intValue); int doId = -1; int.TryParse(nvc.Get("Id"), out doId); if (method == APIMethod.DecrementIntValueToKey) { doId = -1 * Math.Abs(doId); } else { doId = Math.Abs(doId); } if (!Program.attemptToRefresh && !string.IsNullOrEmpty(Program.RSAPublicKey)) { LAResult result = null; var key = new LAKey { Key = licenseKey, ProductId = productId, SignMethod = 0 }; var keyAlt = new LAKey { Key = licenseKey, ProductId = productId, SignMethod = 1 }; if (!Program.licenseCache.TryGetValue(key, out result) && !Program.licenseCache.TryGetValue(keyAlt, out result)) { var error = JsonConvert.SerializeObject(new BasicResult { Result = ResultType.Error, Message = "License server error: could not find the license file (to increment/decrement the data object)." }); ReturnResponse(error, context); return($"Could not find the license file for '{licenseKey}' to continue with the increment or decrement operation."); } if (!result.LicenseKey.DataObjects.Any(x => x.Id == doId)) { var error = JsonConvert.SerializeObject(new BasicResult { Result = ResultType.Error, Message = "License server error: could not find the data object in the license file (to increment/decrement the data object)." }); ReturnResponse(error, context); return($"Could not find the data object with ID {doId} in the license file for '{licenseKey}' to continue with the increment or decrement operation."); } var doKey = new DOKey { DOID = doId, Key = licenseKey, ProductId = productId }; Program.DOOperations.AddOrUpdate(doKey, doId, (x, y) => y + doId); var success = JsonConvert.SerializeObject(new BasicResult { Result = ResultType.Success, Message = "" }); ReturnResponse(success, context); return($"Updated data object successfully."); } else { // for now, just forward the request. ForwardRequest(stream, newRequest, context); //try //{ //} //catch (Exception ex) //{ //} } // add and store log. return(null); }
public static string ProcessActivateRequest(byte[] stream, Dictionary <LAKey, LAResult> licenseCache, int cacheLength, HttpWebRequest newRequest, HttpListenerContext context, ConcurrentDictionary <LAKey, string> keysToUpdate, bool attemptToRefresh, bool localFloatingServer, ConcurrentDictionary <LAKeyBase, ConcurrentDictionary <string, ActivationData> > activatedMachinesFloating, APIMethod method = APIMethod.Unknown) { string bodyParams = System.Text.Encoding.Default.GetString(stream); var nvc = HttpUtility.ParseQueryString(bodyParams); int productId = -1; int.TryParse(nvc.Get("ProductId"), out productId); int signMethod = -1; int.TryParse(nvc.Get("SignMethod"), out signMethod); if (nvc.Get("SignMethod") == "StringSign") { signMethod = 1; } var licenseKey = nvc.Get("Key"); var machineCode = nvc.Get("MachineCode"); var friendlyName = nvc.Get("FriendlyName"); int floatingTimeInterval = -1; int.TryParse(nvc.Get("FloatingTimeInterval"), out floatingTimeInterval); LAResult result = null; var key = new LAKey { Key = licenseKey, ProductId = productId, SignMethod = signMethod }; var keyAlt = new LAKey { Key = licenseKey, ProductId = productId, SignMethod = Math.Abs(signMethod - 1) }; if ((method == APIMethod.GetKey || floatingTimeInterval > 0) && localFloatingServer) { if (signMethod == 0) { var error = JsonConvert.SerializeObject(new BasicResult { Result = ResultType.Error, Message = "License server error: SignMethod=1 is needed to use floating licensing offline." }); ReturnResponse(error, context); return($"SignMethod was not set to 1 for '{licenseKey}', which is needed to continue with the floating activation."); } if (Program.ConfigurationExpires != null && Program.ConfigurationExpires < DateTimeOffset.UtcNow) { var error = JsonConvert.SerializeObject(new BasicResult { Result = ResultType.Error, Message = "License server error: The configuration has expired. Please contact the vendor to receive a new version of the license server to continue to use floating licenses offline." }); ReturnResponse(error, context); return($"The configuration has expired. Please contact the vendor to receive a new version of the license server to continue to use floating licenses offline."); } //floating license if (!licenseCache.TryGetValue(key, out result) && !licenseCache.TryGetValue(keyAlt, out result)) { var error = JsonConvert.SerializeObject(new BasicResult { Result = ResultType.Error, Message = "License server error: could not find the license file (floating license)." }); ReturnResponse(error, context); return($"Could not find the license file for '{licenseKey}' to continue with the floating activation."); } if (result.LicenseKey.MaxNoOfMachines > 0 || method == APIMethod.GetKey) { var activationData = new ConcurrentDictionary <string, ActivationData>(); activatedMachinesFloating.TryGetValue(key, out activationData); if (activationData == null) { activationData = activatedMachinesFloating.AddOrUpdate(key, x => new ConcurrentDictionary <string, ActivationData>(), (x, y) => y); } if (method == APIMethod.GetKey) { FloatingResult(result, null, null, context, 1, activationData.Values.Select(x => new ActivationData { Time = x.Time, FloatingExpires = x.FloatingExpires, FriendlyName = x.FriendlyName, IP = x.IP, Mid = x.Mid }).ToList()); return($"Floating license {licenseKey} returned successfully using a GetKey request. The data from the local license server is used."); } var activation = new ActivationData(); activationData.TryGetValue(machineCode, out activation); if (activation != null && activation.FloatingExpires > DateTime.UtcNow) { activation.FloatingExpires = DateTime.UtcNow.AddSeconds(floatingTimeInterval); activation.FriendlyName = friendlyName; activation.IP = context.Request.RemoteEndPoint.ToString(); FloatingResult(result, activation, machineCode, context); return($"Floating license {licenseKey} returned successfully."); } else if (activationData.Count(x => x.Value.FloatingExpires > DateTime.UtcNow) < result.LicenseKey.MaxNoOfMachines) { activation = activationData.AddOrUpdate(machineCode, x => new ActivationData { Mid = machineCode, Time = DateTime.UtcNow, FloatingExpires = DateTime.UtcNow.AddSeconds(floatingTimeInterval), FriendlyName = friendlyName, IP = context.Request.RemoteEndPoint.ToString() }, (x, y) => new ActivationData { Mid = machineCode, Time = y.Time, FloatingExpires = DateTime.UtcNow.AddSeconds(floatingTimeInterval), FriendlyName = friendlyName, IP = context.Request.RemoteEndPoint.ToString() }); FloatingResult(result, activation, machineCode, context); return($"Floating license {licenseKey} returned successfully."); } else { var error = JsonConvert.SerializeObject(new BasicResult { Result = ResultType.Error, Message = "Cannot activate the new device as the limit has been reached." }); ReturnResponse(error, context); return($"The limit of the number of concurrent devices for '{licenseKey}' was reached. Activation failed."); } // return new license } else { var activation = new ActivationData { Mid = machineCode, FriendlyName = friendlyName, IP = context.Request.RemoteEndPoint.ToString(), Time = DateTime.UtcNow, FloatingExpires = DateTime.UtcNow.AddSeconds(floatingTimeInterval) }; FloatingResult(result, activation, machineCode, context); return($"Floating license {licenseKey} returned successfully."); } } else if (licenseCache.TryGetValue(key, out result) && (method == APIMethod.GetKey || result?.LicenseKey?.ActivatedMachines.Any(x => x.Mid == machineCode) == true) && cacheLength > 0) { TimeSpan ts = DateTime.UtcNow - result.SignDate; if (ts.Days >= cacheLength || attemptToRefresh) { // need to obtain new license try { result.Response = ForwardRequest(stream, newRequest, context); } catch (Exception ex) { if (ts.Days >= cacheLength) { if (method == APIMethod.GetKey) { return($"Could not retrieve an updated license '{licenseKey}'."); } else { return($"Could not retrieve an updated license '{licenseKey}' and machine code '{machineCode}'."); } } else if (attemptToRefresh) { ReturnResponse(result.Response, context); if (method == APIMethod.GetKey) { return($"Retrieved cached version of the license '{licenseKey}'."); } else { return($"Retrieved cached version of the license '{licenseKey}' and machine code '{machineCode}'."); } } } if (signMethod == 1) { var resultObject = JsonConvert.DeserializeObject <RawResponse>(result.Response); var license2 = JsonConvert.DeserializeObject <LicenseKeyPI>(System.Text.UTF8Encoding.UTF8.GetString(Convert.FromBase64String(resultObject.LicenseKey))).ToLicenseKey(); result.SignDate = license2.SignDate; result.LicenseKey = license2; } else { var resultObject = JsonConvert.DeserializeObject <KeyInfoResult>(result.Response); result.SignDate = resultObject.LicenseKey.SignDate; result.LicenseKey = resultObject.LicenseKey; } keysToUpdate.AddOrUpdate(key, x => result.Response, (x, y) => result.Response); if (method == APIMethod.GetKey) { return($"Cache updated for license '{licenseKey}'."); } else { return($"Cache updated for license '{licenseKey}' and machine code '{machineCode}'."); } } else { ReturnResponse(result.Response, context); if (method == APIMethod.GetKey) { return($"Retrieved cached version of the license '{licenseKey}'."); } else { return($"Retrieved cached version of the license '{licenseKey}' and machine code '{machineCode}'."); } } } else { result = new LAResult(); try { result.Response = ForwardRequest(stream, newRequest, context); } catch (WebException ex) { try { var output = ReadToByteArray(ex.Response.GetResponseStream()); context.Response.OutputStream.Write(output, 0, output.Length); context.Response.KeepAlive = false; context.Response.Close(); return($"Could not contact the server '{licenseKey}' and machine code '{machineCode}'. Error message {ex?.Message}."); } catch (Exception ex2) { ReturnResponse(JsonConvert.SerializeObject(new BasicResult { Result = ResultType.Error, Message = "Could not contact the central sever (api.cryptolens.io:443)." }), context); return($"Could not contact the server '{licenseKey}' and machine code '{machineCode}'. Error message {ex2?.Message} and stack trace {ex2?.StackTrace}"); } } catch (Exception ex) { ReturnResponse(JsonConvert.SerializeObject(new BasicResult { Result = ResultType.Error, Message = "Could not contact the central sever (api.cryptolens.io:443)." }), context); return($"Could not contact the server '{licenseKey}' and machine code '{machineCode}'. Error message {ex?.Message} and stack trace {ex?.StackTrace}"); } if (cacheLength > 0) { if (signMethod == 1) { var resultObject = JsonConvert.DeserializeObject <RawResponse>(result.Response); if (!SKM.V3.Methods.Helpers.IsSuccessful(resultObject)) { return($"The error '{resultObject?.Message}' was received from the server for license '{licenseKey}' and machine code '{machineCode}'. The method {method} was used. Read more at https://help.cryptolens.io/faq/index#troubleshooting-api-errors."); } var license2 = JsonConvert.DeserializeObject <LicenseKeyPI>(System.Text.UTF8Encoding.UTF8.GetString(Convert.FromBase64String(resultObject.LicenseKey))).ToLicenseKey(); result.SignDate = license2.SignDate; result.LicenseKey = license2; } else { var resultObject = JsonConvert.DeserializeObject <KeyInfoResult>(result.Response); result.SignDate = resultObject.LicenseKey.SignDate; result.LicenseKey = resultObject.LicenseKey; } if (licenseCache.ContainsKey(key)) { licenseCache[key] = result; } else { licenseCache.Add(key, result); } keysToUpdate.AddOrUpdate(key, x => result.Response, (x, y) => result.Response); return($"Added to the cache the license '{licenseKey}' and machine code '{machineCode}'."); } return(null); } }
static void ResponseThread() { while (true) { HttpListenerContext context = httpListener.GetContext(); // get a context try { if (context.Request.Url.OriginalString.Contains("/api/")) { WriteMessage(context.Request.Url.ToString()); // adapted from https://stackoverflow.com/a/700307/1275924 var original = context.Request; var pathAndQuery = new Uri(context.Request.Url.OriginalString).PathAndQuery; HttpWebRequest newRequest = (HttpWebRequest)WebRequest.Create("https://app.cryptolens.io/" + pathAndQuery); newRequest.ContentType = original.ContentType; newRequest.Method = original.HttpMethod; newRequest.UserAgent = original.UserAgent; byte[] originalStream = Helpers.ReadToByteArray(original.InputStream, 1024); if (original.HttpMethod == "GET") { WriteMessage("GET requests are not supported. Error."); Helpers.ReturnResponse(Newtonsoft.Json.JsonConvert.SerializeObject(new BasicResult { Result = ResultType.Error, Message = "GET requests are not supported in this version of the license server." }), context); } else { // for POST APIMethod method = Helpers.GetAPIMethod(pathAndQuery); if (method == APIMethod.Activate || method == APIMethod.GetKey) { var activateResponse = Helpers.ProcessActivateRequest(originalStream, licenseCache, cacheLength, newRequest, context, keysToUpdate, attemptToRefresh, localFloatingServer, activatedMachinesFloating, method); if (activateResponse != null) { WriteMessage(activateResponse); } } else if (method == APIMethod.IncrementIntValueToKey || method == APIMethod.DecrementIntValueToKey) { var incrementDecrementResponse = Helpers.ProcessIncrementDecrementValueRequest(originalStream, newRequest, context, Helpers.GetAPIMethod(pathAndQuery)); if (incrementDecrementResponse != null) { WriteMessage(incrementDecrementResponse); } } else { Stream reqStream = newRequest.GetRequestStream(); reqStream.Write(originalStream, 0, originalStream.Length); reqStream.Close(); var output = Helpers.ReadToByteArray(newRequest.GetResponse().GetResponseStream()); context.Response.OutputStream.Write(output, 0, output.Length); context.Response.KeepAlive = false; context.Response.Close(); } } } else if (context.Request.Url.LocalPath.ToLower().StartsWith("/stats")) { var totalFloatingMachines = activatedMachinesFloating.Values.Sum(x => x.Count); Helpers.HTMLResponse("Stats", $"<table border=1><tr><th>Property</th><th>Value</th></tr>" + $"<tr><td>Licenses in cache</td><td>{licenseCache.Keys.Count}</td></tr>" + $"<tr><td>Number of licenses (floating offline)</td><td>{activatedMachinesFloating.Keys.Count}</td></tr>" + $"<tr><td>Number of machines (floating offline)</td><td>{totalFloatingMachines}</td></tr></table>", context); WriteMessage("Web dashboard served successfully."); } else if (context.Request.Url.LocalPath.ToLower().StartsWith("/licenses")) { var totalFloatingMachines = activatedMachinesFloating.Values.Sum(x => x.Count); var sb = new StringBuilder(); sb.Append("<p>The following licenses are cached by the license server.</p>"); sb.Append("<table border=1 style='border-style:groove;'><tr><th>License</th><th>Operations</th></tr>"); foreach (var license in licenseCache) { sb.Append($"<tr><td>{license.Key.Key}</td><td></td></tr>"); } sb.Append("</table>"); Helpers.HTMLResponse("Stats", sb.ToString(), context); WriteMessage("Web dashboard served successfully."); } else if (context.Request.Url.LocalPath.ToLower().StartsWith("/report/floatingusage")) { var totalFloatingMachines = activatedMachinesFloating.Values.Sum(x => x.Count); string product = context.Request.QueryString.Get("productId"); string key = context.Request.QueryString.Get("license"); int productId = -1; int.TryParse(product, out productId); int maxNoOfMachines = 0; LAResult res = null; if (!licenseCache.TryGetValue(new LAKey() { Key = key, ProductId = productId, SignMethod = 1 }, out res)) { licenseCache.TryGetValue(new LAKey() { Key = key, ProductId = productId, SignMethod = 0 }, out res); } if (res != null) { maxNoOfMachines = res.LicenseKey.MaxNoOfMachines; } var sb = new StringBuilder(); sb.Append("<p>The following licenses are cached by the license server.</p>"); sb.Append(AnalyticsMethods.SummaryAuditFloating(productId, key, "", maxNoOfMachines)); Helpers.HTMLResponse("Stats", sb.ToString(), context); WriteMessage("Web dashboard served successfully."); } else { byte[] responseArray = Encoding.UTF8.GetBytes($"<html><head><title>Cryptolens License Server {versionInfo} -- port {port}</title></head>" + $"<body><p>Welcome to the <strong>Cryptolens License Server {versionInfo}</strong> -- port {port}! If you see this message, it means " + "everything is working properly.</em></p><p>" + "If you can find its documentation <a href='https://github.com/cryptolens/license-server'>here</a>." + "</p></body></html>"); context.Response.OutputStream.Write(responseArray, 0, responseArray.Length); context.Response.KeepAlive = false; context.Response.Close(); WriteMessage("Web dashboard served successfully."); } } catch (Exception ex) { WriteMessage(ex?.Message + "\n" + ex?.InnerException?.ToString() + "\n" + ex?.StackTrace); } finally { context.Response.Close(); } } }
protected TResult Run <TResult>(APIMethod method, string interfaceName, string name, int version, Dictionary <string, object> parameter) { return(RunAsync <TResult>(method, interfaceName, name, version, parameter).Result); }