private static void ActionOnRemainingInstances(
     string route,
     string launchedOem,
     string launchedVmName)
 {
     foreach (string installedCoexistingOem in InstalledOem.InstalledCoexistingOemList)
     {
         if (ProcessUtils.IsAlreadyRunning("Global\\BlueStacks_BlueStacksUI_Lock" + installedCoexistingOem))
         {
             foreach (string vm in RegistryManager.RegistryManagers[installedCoexistingOem].VmList)
             {
                 try
                 {
                     if (string.Equals(installedCoexistingOem, launchedOem, StringComparison.InvariantCultureIgnoreCase))
                     {
                         if (string.Equals(vm, launchedVmName, StringComparison.InvariantCultureIgnoreCase))
                         {
                             continue;
                         }
                     }
                     if (Utils.PingPartner(installedCoexistingOem, vm))
                     {
                         Logger.Info("Sending " + route + " call to oem:" + installedCoexistingOem + " vm:" + vm);
                         HTTPUtils.SendRequestToClientAsync(route, (Dictionary <string, string>)null, vm, 0, (Dictionary <string, string>)null, false, 1, 0, installedCoexistingOem);
                     }
                 }
                 catch (Exception ex)
                 {
                     Logger.Info(string.Format("Error Sending {0} call to oem: {1} vm: {2} with exception: {3}", (object)route, (object)installedCoexistingOem, (object)vm, (object)ex));
                 }
             }
         }
     }
 }
Beispiel #2
0
        private static string GetInternal(
            string url,
            Dictionary <string, string> headers,
            bool gzip,
            int retries,
            int sleepTimeMSec,
            int timeout,
            string vmName,
            bool isOnUIThreadOnPurpose,
            string oem = "bgp")
        {
            if (Thread.CurrentThread.ManagedThreadId == 1 && !isOnUIThreadOnPurpose)
            {
                Logger.Warning("WARNING: This network call is from the UI thread. StackTrace: {0}", (object)new StackTrace());
            }
            NameValueCollection headerCollection = HTTPUtils.GetRequestHeaderCollection(vmName);
            Uri uri = new Uri(url);

            if (uri.Host.Contains("localhost") || uri.Host.Contains("127.0.0.1"))
            {
                RegistryKey registryKey = RegistryUtils.InitKeyWithSecurityCheck("Software\\BlueStacks" + (oem.Equals("bgp", StringComparison.InvariantCultureIgnoreCase) ? "" : "_" + oem));
                headerCollection.Add("x_api_token", (string)registryKey.GetValue("ApiToken", (object)""));
            }
            else
            {
                headerCollection.Remove("x_api_token");
            }
            return(HTTP.Get(url, headers, gzip, retries, sleepTimeMSec, timeout, headerCollection, Utils.GetUserAgent(oem)));
        }
 private bool HitGuestAPI(string api)
 {
     try
     {
         return(AdbCommandRunner.CheckIfGuestCommandSuccess(HTTPUtils.SendRequestToGuest(api, (Dictionary <string, string>)null, this.mVmName, 0, (Dictionary <string, string>)null, false, 1, 0, "bgp")));
     }
     catch (Exception ex)
     {
         Logger.Error("Error in Sending request {0} to guest {1}", (object)api, (object)ex.ToString());
     }
     return(false);
 }
        public static void SyncConfig(string keyMapParserVersion, string vmName)
        {
            VmCmdHandler.RunCommand("settime " + ((DateTime.UtcNow.Ticks - 621355968000000000L) / 10000L).ToString(), vmName, "bgp");
            Utils.SetTimeZoneInGuest(vmName);
            Dictionary <string, string> data = new Dictionary <string, string>();
            string currentKeyboardLayout     = Utils.GetCurrentKeyboardLayout();

            data.Add("keyboardlayout", currentKeyboardLayout);
            string path = "setkeyboardlayout";

            Logger.Info("Sending request for " + path + " with data : ");
            foreach (KeyValuePair <string, string> keyValuePair in data)
            {
                Logger.Info("key : " + keyValuePair.Key + " value : " + keyValuePair.Value);
            }
            string str = VmCmdHandler.SendRequest(path, data, vmName, out JObject _, "bgp");

            if (str == null || str.Contains("error"))
            {
                Logger.Info("Failed to set keyboard layout in sync config...checking for latinime");
                try
                {
                    if (Utils.IsLatinImeSelected(vmName))
                    {
                        HTTPUtils.SendRequestToEngine("setPcImeWorkflow", (Dictionary <string, string>)null, vmName, 0, (Dictionary <string, string>)null, false, 1, 0, "", "bgp");
                    }
                    else if (Oem.Instance.IsSendGameManagerRequest)
                    {
                        HTTPUtils.SendRequestToClient("showIMESwitchPrompt", (Dictionary <string, string>)null, vmName, 0, (Dictionary <string, string>)null, false, 1, 0, "bgp");
                    }
                }
                catch (Exception ex)
                {
                    Logger.Warning("Error in informing engine/client. Ex: " + ex.Message);
                }
            }
            if (VmCmdHandler.RunCommand("setkeymappingparserversion " + keyMapParserVersion, vmName, "bgp") == null)
            {
                Logger.Error("setkeymappingparserversion did not work, will try again on frontend restart");
            }
            else
            {
                RegistryManager.Instance.Guest[vmName].ConfigSynced = 1;
            }
        }
Beispiel #5
0
 public static void SendRequestToMultiInstanceAsync(
     string route,
     Dictionary <string, string> data = null,
     string vmName = "Android",
     int timeout   = 0,
     Dictionary <string, string> headers = null,
     bool printResponse = false,
     int retries        = 1,
     int sleepTimeMSec  = 0,
     string oem         = "bgp")
 {
     if (retries == 1)
     {
         ThreadPool.QueueUserWorkItem((WaitCallback)(obj =>
         {
             try
             {
                 HTTPUtils.SendRequestToMultiInstance(route, data, vmName, timeout, headers, printResponse, retries, sleepTimeMSec, oem);
             }
             catch (Exception ex)
             {
                 Logger.Error("An exception in SendRequestToClient. route: {0}, \n{1}", (object)route, (object)ex);
             }
         }));
     }
     else
     {
         new Thread((ThreadStart)(() =>
         {
             try
             {
                 HTTPUtils.SendRequestToMultiInstance(route, data, vmName, timeout, headers, printResponse, retries, sleepTimeMSec, oem);
             }
             catch (Exception ex)
             {
                 Logger.Error("An exception in SendRequestToClient. route: {0}, \n{1}", (object)route, (object)ex);
             }
         }))
         {
             IsBackground = true
         }
     }.Start();
        private static string CreateRequestUrlAndDownloadJsonData()
        {
            string urlOriginal = RegistryManager.Instance.Host + "/bs4/getmultiinstancebuild?";

            try
            {
                string osName             = string.Empty;
                string str1               = "app_player";
                string str2               = "w" + SystemUtils.GetOSArchitecture().ToString();
                string userSelectedLocale = RegistryManager.Instance.UserSelectedLocale;
                SystemUtils.GetOSInfo(out osName, out string _, out string _);
                string urlOverideParams = "app_player_win_version=" + osName + "&source=" + str1 + "&app_player_os_arch=" + str2 + "&app_player_language=" + userSelectedLocale;
                urlOriginal = HTTPUtils.MergeQueryParams(urlOriginal, urlOverideParams, true);
            }
            catch (Exception ex)
            {
                Logger.Error("Failed to create url err: {0}", (object)ex.Message);
            }
            return(urlOriginal);
        }
 private void mPopupConrol_MouseUp(object sender, MouseButtonEventArgs e)
 {
     if (this.mMutePopup.IsOpen)
     {
         this.mMutePopup.IsOpen = false;
     }
     else
     {
         if (this.mClickHandler == null)
         {
             try
             {
                 HTTPUtils.SendRequestToClient("markNotificationInDrawer", new Dictionary <string, string>()
                 {
                     {
                         "vmname",
                         this.VmName
                     },
                     {
                         "id",
                         this.AndroidNotificationId
                     }
                 }, MultiInstanceStrings.VmName, 0, (Dictionary <string, string>)null, false, 1, 0, "bgp");
                 if (string.Compare(this.AppName, "Successfully copied files:", StringComparison.OrdinalIgnoreCase) == 0 || string.Compare(this.AppName, "Cannot copy files:", StringComparison.OrdinalIgnoreCase) == 0)
                 {
                     NotificationPopup.LaunchExplorer(this.mLblContent.Text);
                     return;
                 }
                 Logger.Info("launching " + this.AppName);
                 string packageName  = "com.bluestacks.appmart";
                 string activityName = "com.bluestacks.appmart.StartTopAppsActivity";
                 string fileName     = RegistryStrings.InstallDir + "\\HD-RunApp.exe";
                 if (!new JsonParser(this.VmName).GetAppInfoFromAppName(this.AppName, out packageName, out string _, out activityName))
                 {
                     Logger.Error("Failed to launch app: {0}. No info found in json. Starting home app", (object)this.AppName);
                     if (!string.IsNullOrEmpty(this.PackageName))
                     {
                         Process.Start(fileName, string.Format((IFormatProvider)CultureInfo.InvariantCulture, "-p {0} -a {1} -vmname:{2}", (object)this.PackageName, (object)activityName, (object)this.VmName));
                     }
                 }
                 else
                 {
                     string str = "-json \"" + new JObject()
                     {
                         {
                             "app_icon_url",
                             (JToken)""
                         },
                         {
                             "app_name",
                             (JToken)this.AppName
                         },
                         {
                             "app_url",
                             (JToken)""
                         },
                         {
                             "app_pkg",
                             (JToken)this.PackageName
                         }
                     }.ToString(Formatting.None).Replace("\"", "\\\"") + "\"";
                     Process.Start(fileName, string.Format((IFormatProvider)CultureInfo.InvariantCulture, "{0} -vmname {1}", (object)str, (object)this.VmName));
                 }
             }
 public void ProcessRequest(object stateInfo)
 {
     try
     {
         if (this.mCtx.Request.Url.AbsolutePath.StartsWith("/static/", StringComparison.OrdinalIgnoreCase))
         {
             this.StaticFileHandler(this.mCtx.Request, this.mCtx.Response);
         }
         else if (this.mCtx.Request.Url.AbsolutePath.StartsWith("/static2/", StringComparison.OrdinalIgnoreCase))
         {
             this.StaticFileChunkHandler(this.mCtx.Request, this.mCtx.Response, "");
         }
         else if (this.mCtx.Request.Url.AbsolutePath.StartsWith("/staticicon/", StringComparison.OrdinalIgnoreCase))
         {
             if (this.mCtx.Request.QueryString != null && this.mCtx.Request.QueryString.Count > 0)
             {
                 string index = HttpUtility.ParseQueryString(this.mCtx.Request.Url.Query).Get("oem");
                 if (!InstalledOem.InstalledCoexistingOemList.Contains(index))
                 {
                     return;
                 }
                 this.StaticFileChunkHandler(this.mCtx.Request, this.mCtx.Response, Path.Combine(RegistryManager.RegistryManagers[index].EngineDataDir, "UserData\\Gadget"));
             }
             else
             {
                 this.StaticFileChunkHandler(this.mCtx.Request, this.mCtx.Response, Path.Combine(RegistryManager.Instance.EngineDataDir, "UserData\\Gadget"));
             }
         }
         else if (this.mRoutes.ContainsKey(this.mCtx.Request.Url.AbsolutePath))
         {
             HTTPServer.RequestHandler mRoute = this.mRoutes[this.mCtx.Request.Url.AbsolutePath];
             if (mRoute == null)
             {
                 return;
             }
             if (this.mCtx.Request.UserAgent != null)
             {
                 Logger.Info("Request received {0}", (object)this.mCtx.Request.Url.AbsolutePath);
                 Logger.Debug("UserAgent = {0}", (object)this.mCtx.Request.UserAgent);
             }
             if (HTTPServer.Worker.IsTokenValid(this.mCtx.Request.Headers))
             {
                 mRoute(this.mCtx.Request, this.mCtx.Response);
             }
             else
             {
                 Logger.Warning("Token validation check failed, unauthorized access");
                 HTTPUtils.WriteErrorJson(this.mCtx.Response, "Unauthorized Access(401)");
                 this.mCtx.Response.StatusCode = 401;
             }
         }
         else
         {
             Logger.Warning("Exception: No Handler registered for " + this.mCtx.Request.Url.AbsolutePath);
             HTTPUtils.WriteErrorJson(this.mCtx.Response, "Request NotFound(404)");
             this.mCtx.Response.StatusCode = 404;
         }
     }
     catch (Exception ex)
     {
         Logger.Error("Exception while processing HTTP handler: " + ex.ToString());
         HTTPUtils.WriteErrorJson(this.mCtx.Response, "Internal Server Error(500)");
         this.mCtx.Response.StatusCode = 500;
     }
     finally
     {
         try
         {
             this.mCtx.Response.OutputStream.Close();
         }
         catch (Exception ex)
         {
             Logger.Warning("Exception during mCtx.Response.OutputStream.Close(): " + ex.ToString());
         }
     }
 }
Beispiel #9
0
 public static void Write(StringBuilder sb, HttpListenerResponse res)
 {
     HTTPUtils.Write(sb?.ToString(), res);
 }
Beispiel #10
0
        public static RequestData ParseRequest(HttpListenerRequest req, bool printData)
        {
            RequestData requestData1 = new RequestData();
            bool        flag         = false;
            string      s            = (string)null;

            requestData1.Headers       = req?.Headers;
            requestData1.RequestVmId   = 0;
            requestData1.RequestVmName = "Android";
            foreach (string allKey in requestData1.Headers.AllKeys)
            {
                if (requestData1.Headers[allKey].Contains("multipart"))
                {
                    s = "--" + requestData1.Headers[allKey].Substring(requestData1.Headers[allKey].LastIndexOf("=", StringComparison.OrdinalIgnoreCase) + 1);
                    Logger.Debug("boundary: {0}", (object)s);
                    flag = true;
                }
                if (allKey.Contains("oem", StringComparison.InvariantCultureIgnoreCase) && requestData1.Headers[allKey] != null)
                {
                    requestData1.Oem = requestData1.Headers[allKey];
                }
                else if (allKey == "vmid" && requestData1.Headers[allKey] != null)
                {
                    if (!requestData1.Headers[allKey].Equals("0", StringComparison.OrdinalIgnoreCase))
                    {
                        requestData1.RequestVmId = int.Parse(requestData1.Headers["vmid"], (IFormatProvider)CultureInfo.InvariantCulture);
                        if (requestData1.RequestVmName == "Android")
                        {
                            RequestData requestData2 = requestData1;
                            requestData2.RequestVmName = requestData2.RequestVmName + "_" + requestData1.Headers[allKey].ToString((IFormatProvider)CultureInfo.InvariantCulture);
                        }
                    }
                }
                else if (allKey == "vmname" && requestData1.Headers[allKey] != null)
                {
                    requestData1.RequestVmName = requestData1.Headers[allKey].ToString((IFormatProvider)CultureInfo.InvariantCulture);
                }
            }
            requestData1.QueryString = req.QueryString;
            if (!req.HasEntityBody)
            {
                return(requestData1);
            }
            Stream inputStream = req.InputStream;

            byte[]       buffer1      = new byte[16384];
            MemoryStream memoryStream = new MemoryStream();
            int          count1;

            while ((count1 = inputStream.Read(buffer1, 0, buffer1.Length)) > 0)
            {
                memoryStream.Write(buffer1, 0, count1);
            }
            byte[] array = memoryStream.ToArray();
            memoryStream.Close();
            inputStream.Close();
            Logger.Debug("byte array size {0}", (object)array.Length);
            string str1 = Encoding.UTF8.GetString(array);

            if (!flag)
            {
                if (!req.ContentType.Contains("application/json", StringComparison.InvariantCultureIgnoreCase))
                {
                    requestData1.Data = HttpUtility.ParseQueryString(str1);
                }
                else
                {
                    JObject             jobject             = JObject.Parse(str1);
                    NameValueCollection nameValueCollection = new NameValueCollection();
                    foreach (string name in jobject.Properties().Select <JProperty, string>((Func <JProperty, string>)(p => p.Name)).ToList <string>())
                    {
                        nameValueCollection.Add(name, jobject[name].ToString());
                    }
                    requestData1.Data = nameValueCollection;
                }
                return(requestData1);
            }
            byte[]     bytes1  = Encoding.UTF8.GetBytes(s);
            List <int> intList = HTTPUtils.IndexOf(array, bytes1);

            for (int index = 0; index < intList.Count - 1; ++index)
            {
                Logger.Info("Creating part");
                int    srcOffset1 = intList[index];
                int    num        = intList[index + 1];
                int    count2     = num - srcOffset1;
                byte[] bytes2     = new byte[count2];
                Logger.Debug("Start: {0}, End: {1}, Length: {2}", (object)srcOffset1, (object)num, (object)count2);
                Logger.Debug("byteData length: {0}", (object)array.Length);
                Buffer.BlockCopy((Array)array, srcOffset1, (Array)bytes2, 0, count2);
                Logger.Debug("bytePart length: {0}", (object)bytes2.Length);
                string input  = Encoding.UTF8.GetString(bytes2);
                Match  match1 = new Regex("(?<=Content\\-Type:)(.*?)(?=\\r\\n)").Match(input);
                Match  match2 = new Regex("(?<=filename\\=\\\")(.*?)(?=\\\")").Match(input);
                string name   = new Regex("(?<=name\\=\\\")(.*?)(?=\\\")").Match(input).Value.Trim();
                Logger.Info("Got name: {0}", (object)name);
                if (match1.Success && match2.Success)
                {
                    Logger.Debug("Found file");
                    Logger.Debug("Got contenttype: {0}", (object)match1.Value.Trim());
                    string path2 = match2.Value.Trim();
                    Logger.Info("Got filename: {0}", (object)path2);
                    int srcOffset2 = input.IndexOf("\r\n\r\n", StringComparison.OrdinalIgnoreCase) + "\r\n\r\n".Length;
                    Encoding.UTF8.GetBytes("\r\n" + s);
                    int    count3  = count2 - srcOffset2;
                    byte[] buffer2 = new byte[count3];
                    Logger.Debug("startindex: {0}, contentlength: {1}", (object)srcOffset2, (object)count3);
                    Buffer.BlockCopy((Array)bytes2, srcOffset2, (Array)buffer2, 0, count3);
                    string path1 = RegistryStrings.BstUserDataDir;
                    if (path2.StartsWith("tombstone", StringComparison.OrdinalIgnoreCase))
                    {
                        path1 = RegistryStrings.BstLogsDir;
                    }
                    try
                    {
                        string     path       = Path.Combine(path1, path2);
                        FileStream fileStream = System.IO.File.OpenWrite(path);
                        fileStream.Write(buffer2, 0, count3);
                        fileStream.Close();
                        requestData1.Files.Add(name, path);
                    }
                    catch (Exception ex)
                    {
                        Logger.Warning("Exception in generating file: " + ex.ToString());
                    }
                }
                else
                {
                    Logger.Info("No file in this part");
                    int    startIndex = input.LastIndexOf("\r\n\r\n", StringComparison.OrdinalIgnoreCase);
                    string str2       = input.Substring(startIndex, input.Length - startIndex).Trim();
                    if (printData)
                    {
                        Logger.Info("Got value: {0}", (object)str2);
                    }
                    else
                    {
                        Logger.Info("Value hidden");
                    }
                    requestData1.Data.Add(name, str2);
                }
            }
            return(requestData1);
        }
Beispiel #11
0
 public static RequestData ParseRequest(HttpListenerRequest req)
 {
     return(HTTPUtils.ParseRequest(req, true));
 }
        public static string GetUrlWithParams(
            string url,
            string clientVer  = null,
            string engVer     = null,
            string userLocale = null)
        {
            string str1          = "bgp";
            string str2          = clientVer ?? RegistryManager.Instance.ClientVersion;
            string str3          = engVer ?? RegistryManager.Instance.Version;
            string userGuid      = RegistryManager.Instance.UserGuid;
            string str4          = userLocale ?? RegistryManager.Instance.UserSelectedLocale;
            string partner       = RegistryManager.Instance.Partner;
            string campaignMd5   = RegistryManager.Instance.CampaignMD5;
            string str5          = RegistryManager.Instance.InstallationType.ToString();
            string pkgName       = GameConfig.Instance.PkgName;
            string webAppVersion = RegistryManager.Instance.WebAppVersion;
            string str6          = "oem=" + str1 + "&prod_ver=" + str2 + "&eng_ver=" + str3 + "&guid=" + userGuid + "&locale=" + str4 + "&launcher_version=" + webAppVersion;

            if (!string.IsNullOrEmpty(partner))
            {
                str6 += "&partner=";
            }
            string str7 = str6 + partner;

            if (!string.IsNullOrEmpty(campaignMd5))
            {
                str7 += "&campaign_md5=";
            }
            string str8 = str7 + campaignMd5;
            Uri    uri  = new Uri(url);

            if (uri.Host.Equals(WebHelper.sDefaultCloudHost.Host, StringComparison.InvariantCultureIgnoreCase) || uri.Host.Equals(WebHelper.sRegistryHost.Host, StringComparison.InvariantCultureIgnoreCase))
            {
                string registeredEmail = RegistryManager.Instance.RegisteredEmail;
                if (!string.IsNullOrEmpty(registeredEmail))
                {
                    str8 += "&email=";
                }
                string str9  = str8 + registeredEmail;
                string token = RegistryManager.Instance.Token;
                if (!string.IsNullOrEmpty(token))
                {
                    str9 += "&token=";
                }
                str8 = str9 + token;
            }
            string str10 = str8 + "&installation_type=" + str5;

            if (!string.IsNullOrEmpty(pkgName))
            {
                str10 += "&gaming_pkg_name=";
            }
            string urlOverideParams = str10 + pkgName;

            if (url != null && !url.Contains("://"))
            {
                url = "http://" + url;
            }
            url = HTTPUtils.MergeQueryParams(url, urlOverideParams, true);
            Logger.Debug("Returning updated URL: {0}", (object)url);
            return(url);
        }
        public static string SendRequest(
            string path,
            Dictionary <string, string> data,
            string vmName,
            out JObject response,
            string oem = "bgp")
        {
            int num1 = 60;
            int num2 = 3;

            response = (JObject)null;
            while (num1 > 0)
            {
                try
                {
                    if (num2 != 0)
                    {
                        --num2;
                    }
                    string json = path == "runex" || path == "run" || path == "powerrun" ? HTTPUtils.SendRequestToGuest(path, data, vmName, 3000, (Dictionary <string, string>)null, false, 1, 0, oem) : (!(path == "setWindowsAgentAddr") ? HTTPUtils.SendRequestToGuest(path, data, vmName, 0, (Dictionary <string, string>)null, false, 1, 0, oem) : HTTPUtils.SendRequestToGuest(path, data, vmName, 1000, (Dictionary <string, string>)null, false, 1, 0, oem));
                    Logger.Info("Got response for {0}: {1}", (object)path, (object)json);
                    response = JObject.Parse(json);
                    VmCmdHandler.s_Received = (string)response["result"];
                    if (VmCmdHandler.s_Received != "ok")
                    {
                        if (VmCmdHandler.s_Received != "error")
                        {
                            VmCmdHandler.s_Received = (string)null;
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (num2 != 0)
                    {
                        Logger.Error("Exception in SendRequest for {0}: {1}", (object)path, (object)ex.Message);
                    }
                    VmCmdHandler.s_Received = (string)null;
                }
                --num1;
                if (VmCmdHandler.s_Received != null)
                {
                    return(VmCmdHandler.s_Received);
                }
                if (num1 > 0)
                {
                    Thread.Sleep(1000);
                }
            }
            return((string)null);
        }
Beispiel #14
0
        private static string HttpUploadFileInternal(
            string url,
            string file,
            string paramName,
            string contentType,
            Dictionary <string, string> headers,
            Dictionary <string, string> data)
        {
            Logger.Info("Uploading {0} to {1}", (object)file, (object)url);
            string str1 = "---------------------------" + DateTime.Now.Ticks.ToString("x", (IFormatProvider)CultureInfo.InvariantCulture);

            byte[]         bytes1         = Encoding.ASCII.GetBytes("\r\n--" + str1 + "\r\n");
            Uri            destination    = new Uri(url);
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);

            httpWebRequest.ContentType = "multipart/form-data; boundary=" + str1;
            httpWebRequest.Method      = "POST";
            httpWebRequest.KeepAlive   = true;
            httpWebRequest.Timeout     = 300000;
            httpWebRequest.UserAgent   = Utils.GetUserAgent("bgp");
            if (!destination.Host.Contains("localhost") && !destination.Host.Contains("127.0.0.1"))
            {
                Uri proxy = httpWebRequest.Proxy.GetProxy(destination);
                Logger.Debug("URI of proxy = " + ((object)proxy != null ? proxy.ToString() : (string)null));
            }
            if (headers != null)
            {
                foreach (KeyValuePair <string, string> header in headers)
                {
                    httpWebRequest.Headers.Set(StringUtils.GetControlCharFreeString(header.Key), StringUtils.GetControlCharFreeString(header.Value));
                }
            }
            httpWebRequest.Headers.Add(HTTPUtils.GetRequestHeaderCollection(""));
            if (data == null)
            {
                data = new Dictionary <string, string>();
            }
            Stream requestStream = httpWebRequest.GetRequestStream();
            string format        = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";

            foreach (KeyValuePair <string, string> keyValuePair in data)
            {
                requestStream.Write(bytes1, 0, bytes1.Length);
                byte[] bytes2 = Encoding.UTF8.GetBytes(string.Format((IFormatProvider)CultureInfo.InvariantCulture, format, (object)keyValuePair.Key, (object)keyValuePair.Value));
                requestStream.Write(bytes2, 0, bytes2.Length);
            }
            requestStream.Write(bytes1, 0, bytes1.Length);
            byte[] bytes3 = Encoding.UTF8.GetBytes(string.Format((IFormatProvider)CultureInfo.InvariantCulture, "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n", (object)paramName, (object)file, (object)contentType));
            requestStream.Write(bytes3, 0, bytes3.Length);
            string str2 = Path.Combine(Environment.ExpandEnvironmentVariables("%TEMP%"), Path.GetFileName(file)) + "_bst";

            System.IO.File.Copy(file, str2);
            if (contentType.Equals("text/plain", StringComparison.InvariantCultureIgnoreCase))
            {
                string s        = System.IO.File.ReadAllText(str2);
                byte[] numArray = new byte[1048576];
                byte[] bytes2   = Encoding.UTF8.GetBytes(s);
                requestStream.Write(bytes2, 0, bytes2.Length);
            }
            else
            {
                FileStream fileStream = new FileStream(str2, FileMode.Open, FileAccess.Read);
                byte[]     buffer     = new byte[4096];
                int        count;
                while ((count = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    requestStream.Write(buffer, 0, count);
                }
                fileStream.Close();
            }
            System.IO.File.Delete(str2);
            byte[] bytes4 = Encoding.ASCII.GetBytes("\r\n--" + str1 + "--\r\n");
            requestStream.Write(bytes4, 0, bytes4.Length);
            requestStream.Close();
            string      str3        = (string)null;
            WebResponse webResponse = (WebResponse)null;

            try
            {
                webResponse = httpWebRequest.GetResponse();
                using (Stream responseStream = webResponse.GetResponseStream())
                {
                    using (StreamReader streamReader = new StreamReader(responseStream))
                    {
                        str3 = streamReader.ReadToEnd();
                        Logger.Info("File uploaded, server response is: {0}", (object)str3);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Error uploading file", (object)ex);
                webResponse?.Close();
                throw;
            }
            finally
            {
            }
            return(str3);
        }