Exemple #1
0
        private void InterceptRequest(Session session)
        {
            if (!session.hostname.EndsWith(s3Configuration.ServiceUrl))
              {
            return;
              }

              if (session.HTTPMethodIs("CONNECT"))
              {
            session.oFlags["x-replywithtunnel"] = "fake tunnel";
            return;
              }

              string bucket = string.Empty;
              if (!session.HostnameIs(s3Configuration.ServiceUrl))
              {
            string virtualHostedPath = session.hostname.Replace("." + s3Configuration.ServiceUrl, string.Empty);
            bucket = "/" + virtualHostedPath;
              }

              if(session.isHTTPS)
              {
            session.fullUrl = session.fullUrl.Replace("https", "http");
              }
              session.host = string.Format("127.0.0.1:{0}", s3Configuration.HostPort);
              session.PathAndQuery = string.Format("{0}{1}", bucket, session.PathAndQuery);
        }
Exemple #2
0
        public override void Handle(Session Session)
        {
            string ResponseJson = Session.GetResponseBodyAsString();
            EventListDungeons result = JsonConvert.DeserializeObject<EventListDungeons>(ResponseJson);

            lock (FFRKProxy.Instance.Cache.SyncRoot)
            {
                foreach (DataDungeon dungeon in result.Dungeons)
                {
                    DataCache.Dungeons.Key key = new DataCache.Dungeons.Key { DungeonId = dungeon.Id };
                    DataCache.Dungeons.Data data = null;
                    if (!FFRKProxy.Instance.Cache.Dungeons.TryGetValue(key, out data))
                    {
                        data = new DataCache.Dungeons.Data
                        {
                            Difficulty = dungeon.Difficulty,
                            Name = dungeon.Name,
                            Series = dungeon.SeriesId,
                            Type = dungeon.Type,
                            WorldId = dungeon.WorldId
                        };
                        FFRKProxy.Instance.Cache.Dungeons.Update(key, data);
                    }
                }
            }

            FFRKProxy.Instance.Database.BeginExecuteRequest(new DbOpRecordDungeonList(result));
            FFRKProxy.Instance.RaiseListDungeons(result);
        }
        public static HttpResponseMessage CreateResponseFromSession(Session session)
        {
            var response = new HttpResponseMessage
            {
                StatusCode = (HttpStatusCode)session.responseCode
            };
            var failedHeaders = new List<HTTPHeaderItem>();
            foreach (var header in session.oResponse.headers)
            {
                if (!response.Headers.TryAddWithoutValidation(header.Name, header.Value))
                {
                    failedHeaders.Add(header);
                }
            }

            if (session.ResponseBody.Length > 0)
            {
                response.Content = new ByteArrayContent(session.ResponseBody);
                foreach (var header in failedHeaders)
                {
                    response.Content.Headers.TryAddWithoutValidation(header.Name, header.Value);
                }
            }
            return response;
        }
 public static HttpRequestMessage CreateRequestFromSession(Session session)
 {
     var request = new HttpRequestMessage
     {
         RequestUri = new Uri(session.fullUrl, UriKind.RelativeOrAbsolute),
         Method = new HttpMethod(session.RequestMethod)
     };
     var failedHeaders = new List<HTTPHeaderItem>();
     foreach (var header in session.oRequest.headers)
     {
         if (!request.Headers.TryAddWithoutValidation(header.Name, header.Value))
         {
             failedHeaders.Add(header);
         }
     }
     if (session.RequestBody.Length > 0)
     {
         request.Content = new ByteArrayContent(session.RequestBody);
         foreach (var header in failedHeaders)
         {
             request.Content.Headers.TryAddWithoutValidation(header.Name, header.Value);
         }
     }
     return request;
 }
        void FiddlerApplication_BeforeResponse(FiddlerSession rpSession)
        {
            var rSession = rpSession.Tag as Session;
            if (rSession != null)
            {
                if (rSession.Status == SessionStatus.Request)
                    rSession.Status = SessionStatus.Responsed;

                var rApiSession = rSession as ApiSession;
                if (rApiSession != null)
                {
                    rApiSession.ResponseString = rpSession.GetResponseBodyAsString();
                    ApiParsers.Post(rApiSession);
                }

                var rResourceSession = rSession as ResourceSession;
                if (rResourceSession != null && ResourceCache.IsEnabled && rpSession.responseCode == 200 && !File.Exists(rResourceSession.CachePath) && rpSession.oResponse["Last-Modified"] != null)
                {
                    rResourceSession.Data = rpSession.ResponseBody;
                    rResourceSession.LastModifiedTime = Convert.ToDateTime(rpSession.oResponse["Last-Modified"]);
                    ResourceCache.SaveFile(rResourceSession);
                }

                if (rSession.Url.Contains("kcs/sound/titlecall/") || rSession.Url.Contains("api_start2"))
                    KanColleGame.Current.RaiseGameLaunchedEvent();
            }

            Debug.WriteLine("Response - " + rpSession.fullUrl);
        }
        public bool LoadFromCache(Session oSession)
        {
            bool success = false;
            string key = oSession.fullUrl;
            if (!cache.ContainsKey(key))
            {
                if (key.Contains('?')) {
                    key = key.Substring(0, key.IndexOf('?'));
                }
            }
            if (cache.ContainsKey(key)) 
            {
                CacheItem item = cache[key];
                if (item.CheckState == System.Windows.Forms.CheckState.Checked
                    && File.Exists(item.Local))
                {
                    oSession.utilCreateResponseAndBypassServer();
                    item.SetSessionResponse(oSession);                    
                    success = oSession.LoadResponseFromFile(item.Local);
                }
                
            }


            return success;
        }
        public void AutoTamperRequestBefore(Session oSession)
        {
            if (model.Enabled)
            {
                //  if (m_SimulateModem) {
                //    // Delay sends by 300ms per KB uploaded.
                //    oSession["request-trickle-delay"] = "30";
                //    // Delay receives by 150ms per KB downloaded.
                //    oSession["response-trickle-delay"] = "150";
                //}

                int requestDelay = SpeedConvert.covert(model.RequestDelaySpeed);
               int  reponseDelay = SpeedConvert.covert(model.ReponseDelaySpeed);

               oSession["request-trickle-delay"] = Convert.ToString(requestDelay);
               oSession["response-trickle-delay"] = Convert.ToString(reponseDelay);
            }
            else
            {
                oSession["request-trickle-delay"] = null;
                oSession["response-trickle-delay"] = null;
            }

               // oSession.oRequest["User-Agent"] = sUserAgent;
        }
        void LoadFile(string rpFilename, ResourceSession rpResourceSession, Session rpSession)
        {
            if (!rpSession.bBufferResponse)
                rpSession.utilCreateResponseAndBypassServer();

            rpSession.ResponseBody = File.ReadAllBytes(rpFilename);
            rpSession.oResponse["Server"] = "Apache";
            rpSession.oResponse["Connection"] = "close";
            rpSession.oResponse["Accept-Ranges"] = "bytes";
            rpSession.oResponse["Cache-Control"] = "max-age=18000, public";
            rpSession.oResponse["Date"] = DateTime.Now.ToString("R");

            if (rpFilename.EndsWith(".swf", StringComparison.OrdinalIgnoreCase))
                rpSession.oResponse["Content-Type"] = "application/x-shockwave-flash";
            else if (rpFilename.EndsWith(".mp3", StringComparison.OrdinalIgnoreCase))
                rpSession.oResponse["Content-Type"] = "audio/mpeg";
            else if (rpFilename.EndsWith(".png", StringComparison.OrdinalIgnoreCase))
                rpSession.oResponse["Content-Type"] = "image/png";
            else if (rpFilename.EndsWith(".css", StringComparison.OrdinalIgnoreCase))
                rpSession.oResponse["Content-Type"] = "text/css";
            else if (rpFilename.EndsWith(".js", StringComparison.OrdinalIgnoreCase))
                rpSession.oResponse["Content-Type"] = "application/x-javascript";

            rpResourceSession.State = NetworkSessionState.LoadedFromCache;
        }
        static void _AfterComplete(Session oSession)
        {
            if (!Settings.Current.CacheEnabled) return;
            if (!_Filter(oSession)) return;

            //服务器返回200,下载新的文件
            if (oSession.responseCode == 200)
            {
                string filepath = TaskRecord.GetAndRemove(oSession.fullUrl);

                //只有TaskRecord中有记录的文件才是验证的文件,才需要保存
                if (!string.IsNullOrEmpty(filepath))
                {
                    if (File.Exists(filepath))
                        File.Delete(filepath);

                    //保存下载文件并记录Modified-Time
                    try
                    {
                        oSession.SaveResponseBody(filepath);
                        //cache.RecordNewModifiedTime(oSession.fullUrl,
                        //	oSession.oResponse.headers["Last-Modified"]);
                        _SaveModifiedTime(filepath, oSession.oResponse.headers["Last-Modified"]);
                        //Debug.WriteLine("CACHR> 【下载文件】" + oSession.PathAndQuery);
                    }
                    catch (Exception ex)
                    {
                        Log.Exception(oSession, ex, "会话结束时,保存返回文件时发生异常");
                    }
                }
            }
        }
        bool ISessionExporter.ExportSessions(string sExportFormat, Session[] oSessions, Dictionary<string, object> dictOptions, EventHandler<ProgressCallbackEventArgs> evtProgressNotifications)
        {
            string fileName = string.Empty;

            fileName = Utilities.ObtainSaveFilename("Export As " + sExportFormat, "CSV Files (*.csv)|*.csv");

            if (String.IsNullOrEmpty(fileName))
            {
                return false;
            }

            try
            {
                StringBuilder csvOutput = new StringBuilder();

                //Header line
                csvOutput.AppendDelimiter("#", delimiter);
                csvOutput.AppendDelimiter("Result", delimiter);
                csvOutput.AppendDelimiter("Host", delimiter);
                csvOutput.Append("Path");

                csvOutput.AppendLine();

                //Loop through sessions
                foreach (Session session in oSessions)
                {
                    csvOutput.AppendDelimiter(session.id.ToString(), delimiter);
                    csvOutput.AppendDelimiter(session.responseCode.ToString(), delimiter);
                    csvOutput.AppendDelimiter(session.hostname, delimiter);
                    csvOutput.Append(session.PathAndQuery);

                    /*
                    public DateTime ClientBeginRequest;
                    public DateTime ClientBeginResponse;
                    public DateTime ClientConnected;
                    public DateTime ClientDoneRequest;
                    public DateTime ClientDoneResponse;
                    public int DNSTime;
                    public DateTime FiddlerBeginRequest;
                    public DateTime FiddlerGotRequestHeaders;
                    public DateTime FiddlerGotResponseHeaders;
                    public int GatewayDeterminationTime;
                    public int HTTPSHandshakeTime;
                    public DateTime ServerBeginResponse;
                    public DateTime ServerConnected;
                    public DateTime ServerDoneResponse;
                    public DateTime ServerGotRequest;
                    public int TCPConnectTime;
                     */
                }

                FiddlerApplication.Log.LogString(csvOutput.ToString());

                return true;
            }
            catch (Exception e)
            {
                return false;
            }
        }
Exemple #11
0
        //This event fires when a client request is received by Fiddler
        static void _BeforeRequest(Session oSession)
        {
            if (!Settings.Current.CacheEnabled) return;
			if (!_Filter(oSession)) return;

            string filepath;
			var direction = cache.GotNewRequest(oSession.fullUrl, out filepath);
			
			if (direction == Direction.Return_LocalFile)
			{
				//返回本地文件
				oSession.utilCreateResponseAndBypassServer();
				oSession.ResponseBody = File.ReadAllBytes(filepath);
				_CreateResponseHeader(oSession, filepath);

				//Debug.WriteLine("CACHR> 【返回本地】" + filepath);
			}
			else if (direction == Direction.Verify_LocalFile)
			{
				//请求服务器验证文件
				//oSession.oRequest.headers["If-Modified-Since"] = result;
				oSession.oRequest.headers["If-Modified-Since"] = _GetModifiedTime(filepath);
				oSession.bBufferResponse = true;

				//Debug.WriteLine("CACHR> 【验证文件】" + oSession.PathAndQuery);
			}
			else 
			{ 
				//下载文件
			}
        }
Exemple #12
0
        private void GetAnswersFromResponse(Session session)
        {
            session.utilDecodeResponse();

            var responseString = System.Text.Encoding.UTF8.GetString(session.ResponseBody);

            try
            {
                var cheatInfo = JsonConvert.DeserializeObject<CheatInfo>(responseString);
                if (cheatInfo.session_elements.Count == 0) return;

                _userControl.AppendText(string.Empty);
                _userControl.ResetCount();

                foreach (var element in cheatInfo.session_elements)
                {
                    if (element.form_tokens.Count(t => t.options.Count > 0) > 0) _userControl.AppendText(element.form_tokens.First(f => f.options.Count > 0).options.First(o => o.correct).display_value);
                    else if (element.options.Count > 0) _userControl.AppendText(string.Join(" / ", element.options.Where(o => o.correct).Select(o => o.sentence)));
                    else if (!string.IsNullOrEmpty(element.translation)) _userControl.AppendText(element.translation);
                    else if (!string.IsNullOrEmpty(element.text)) _userControl.AppendText(element.text);
                    else if (element.correct_solutions.Count > 0) _userControl.AppendText(element.correct_solutions[0]);
                    else _userControl.AppendText(string.Empty);
                }
            }
            finally
            {
            }
        }
Exemple #13
0
		private static kcsapi_ranking_getlist Serialize(Session session)
		{
			try
			{
				var djson = DynamicJson.Parse(session.GetResponseAsJson());
				var rankings = new kcsapi_ranking_getlist
				{
					api_count = Convert.ToInt32(djson.api_data.api_count),
					api_disp_page = Convert.ToInt32(djson.api_data.api_disp_page),
					api_page_count = Convert.ToInt32(djson.api_data.api_page_count),
				};

				var list = new List<kcsapi_ranking>();
				var serializer = new DataContractJsonSerializer(typeof(kcsapi_ranking));
				foreach (var x in (object[])djson.api_data.api_list)
				{
					try
					{
						list.Add(serializer.ReadObject(new MemoryStream(Encoding.UTF8.GetBytes(x.ToString()))) as kcsapi_ranking);
					}
					catch (SerializationException ex)
					{
						Debug.WriteLine(ex.Message);
					}
				}
				rankings.api_list = list.ToArray();
				return rankings;
			}
			catch (Exception ex)
			{
				Debug.WriteLine(ex);
				return null;
			}
		}
 public void AutoTamperRequestBefore(Session oSession)
 {
     if (cacheController != null)
     {
         cacheController.Filter(oSession);
     }
 }
 static void FiddlerApplication_ResponseHeadersAvailable(Session rpSession)
 {
     var rSession = rpSession.Tag as NetworkSession;
     var rContentLength = rpSession.oResponse["Content-Length"];
     if (!rContentLength.IsNullOrEmpty() && rSession != null)
         rSession.ContentLength = int.Parse(rContentLength);
 }
        public void AutoTamperRequestBefore(Session oSession)
        {
            // Check that our plugin has been enabled
            if (authTab.IsEnabled == false)
            {
                return;
            }

            // Clone our existing request
            HTTPRequestHeaders oNewHeaders = oSession.oRequest.headers.Clone() as HTTPRequestHeaders;
            byte[] requestBody = oSession.requestBodyBytes;

            // Look for any configuration data values to remove
            FiddlerApplication.Log.LogString(String.Format("COOKIE: {0}", oNewHeaders["Cookie"]));

            // Check that we haven't already sent a modified response
            if (!oSession.oFlags.ContainsKey("repeat-request"))
            {
                if (StripSessionFromRequest(oNewHeaders, ref requestBody))
                {
                    // Add our tracking flag
                    StringDictionary flags = new StringDictionary();
                    flags.Add("repeat-request", "true");
                    FiddlerApplication.oProxy.InjectCustomRequest(oNewHeaders, requestBody, flags);
                }
            }
        }
Exemple #17
0
        public bool ExportSessions(string sFormat, Session[] oSessions, Dictionary<string, object> dictOptions,
                                    EventHandler<ProgressCallbackEventArgs> evtProgressNotifications)
        {
            bool bResult = true;
            string sFilename = null;

            // [3] Ask the Fiddler GUI to obtain the filename to export to
            sFilename = Fiddler.Utilities.ObtainSaveFilename("Export As " + sFormat, "JMeter Files (*.jmx)|*.jmx");

            if (String.IsNullOrEmpty(sFilename)) return false;

            if (!Path.HasExtension(sFilename)) sFilename = sFilename + ".jmx";

            try
            {

                Encoding encUTF8NoBOM = new UTF8Encoding(false);
                JMeterTestPlan jMeterTestPlan = new JMeterTestPlan(oSessions, sFilename);
                System.IO.StreamWriter sw = new StreamWriter(sFilename, false, encUTF8NoBOM);
                sw.Write(jMeterTestPlan.getJmx());
                sw.Close();
            }
            catch (Exception eX)
            {
                Fiddler.FiddlerApplication.Log.LogString(eX.Message);
                Fiddler.FiddlerApplication.Log.LogString(eX.StackTrace);
                bResult = false;
            }
            return bResult;
        }
        public static Entry Export(Session session, bool requestOnly = false)
        {
            var entry = new Entry();
            entry.startedDateTime = session.Timers.ClientBeginRequest.ToString("o");
            entry.request = GetRequest(session);
            if (!requestOnly)
            {
                entry.response = GetResponse(session);
            }

            entry.timings = GetTimings(session.Timers);
            entry.comment = session["ui-comments"];

            entry.time = GetTotalTime(entry.timings);

            if (
                !string.IsNullOrEmpty(session["ui-comments"])
                // <-- not sure if this is correct, maybe a typo or missing assignation in BasicFormats?
                && !session.isFlagSet(SessionFlags.SentToGateway))
            {
                entry.serverIPAddress = session.m_hostIP;
            }
            entry.connection = session.clientPort.ToString(CultureInfo.InvariantCulture);
            return entry;
        }
        private void InspectSession(Session[] sessions)
        {
            var session = sessions[0];
            var requestBody = session.GetRequestBodyAsString();
            var responseBody = session.GetResponseBodyAsString();
            var requestHeaders = GetHeaders(session.RequestHeaders);

            var timers = session.Timers;
            var sessionTime = timers.ClientDoneResponse - timers.ClientBeginRequest;

            try
            {
                var inspector = new Inspector(requestBody, responseBody, requestHeaders, sessionTime);
                var actions = inspector.GetActionsData();
                var requestData = inspector.GetRequestData();
                var responseData = inspector.GetResponseData();

                RequestViewModel.Actions = new ObservableCollection<ActionBase>(actions);
                RequestViewModel.ErrorInfo = responseData.ErrorInfo;
                RequestInfoViewModel.SetSessionData(requestData, responseData, sessionTime, session.RequestBody.Length, session.ResponseBody.Length);
            }
            catch
            {
                RequestViewModel.Actions = new ObservableCollection<ActionBase>();
                RequestInfoViewModel.ClearSessionData();
            }
        }
        static void FiddlerApplication_BeforeResponse(Session oSession)
        {
            string url = oSession.url;
            DateTime start = oSession.Timers.ClientBeginRequest;
            DateTime end = oSession.Timers.ClientDoneResponse;
            TimeSpan t = end - start;

            if (oSession.host != filter)
                return;

            if(oSession.Timers.DNSTime > 0)
                Console.WriteLine("DNS TIME: {0}", oSession.Timers.DNSTime);

            if (!sdata.Keys.Contains(url))
                sdata[url] = new List<RequestAggregate>();

            RequestAggregate rq = new RequestAggregate()
            {
                data_size = oSession.GetResponseBodyAsString().Length,
                host = oSession.host,
                time = t.TotalMilliseconds
            };

            Monitor.Enter(sdata[url]);
            sdata[url].Add(rq);
            Monitor.Exit(sdata[url]);

            ConsoleColor c = Console.ForegroundColor;
            Console.ForegroundColor = ConsoleColor.DarkRed;
            Console.WriteLine("{0}  ==> {1}", oSession.url, end-start);
            Console.ForegroundColor = defaultColor;
        }
 static void FiddlerApplication_BeforeRequest(Session oSession)
 {
     ConsoleColor c = Console.ForegroundColor;
     Console.ForegroundColor = ConsoleColor.DarkGreen;
     Console.WriteLine("{0}", oSession.url);
     Console.ForegroundColor = defaultColor;
 }
 private CONNECTTunnel(Session oSess, ClientPipe oFrom, ServerPipe oTo)
 {
     this._mySession = oSess;
     this.pipeTunnelClient = oFrom;
     this.pipeTunnelRemote = oTo;
     this._mySession.SetBitFlag(SessionFlags.IsBlindTunnel, true);
 }
Exemple #23
0
        private void GetHintsFromResponse(Session session)
        {
            session.utilDecodeResponse();

            var responseString = System.Text.Encoding.UTF8.GetString(session.ResponseBody);
            var regexStart = new Regex(@"^/\*\*/jQuery[0-9]{20}_[0-9]{10,15}\(");
            responseString = regexStart.Replace(responseString, string.Empty);
            var regexEnd = new Regex(@"\);$");
            responseString = regexEnd.Replace(responseString, string.Empty);

            try
            {
                var hintInfo = JsonConvert.DeserializeObject<DuoHint>(responseString);
                var hintString = string.Empty;
                foreach(var token in hintInfo.tokens.Where(t => t.hint_table != null).OrderBy(t => t.index))
                {
                    foreach(var row in token.hint_table.rows.Where(r => r.cells.Count > 0))
                    {
                        hintString += string.Join(", ", row.cells.Where(c => !string.IsNullOrEmpty(c.hint)).Select(c => c.hint.Trim()));
                        hintString += ", ";
                    }
                }

                _userControl.AppendText("\r\n" + hintString);
            }
            finally { }
        }
        static void FiddlerApplication_BeforeRequest(Session rpSession)
        {
            if (Preference.Current.Network.UpstreamProxy.Enabled)
                rpSession["x-OverrideGateway"] = Preference.Current.Network.UpstreamProxy.Address;

            var rRequest = rpSession.oRequest;

            var rFullUrl = rpSession.fullUrl;
            var rPath = rpSession.PathAndQuery;

            NetworkSession rSession;
            if (rPath.StartsWith("/kcsapi/"))
                rSession = new ApiSession(rFullUrl);
            else if (rPath.StartsWith("/kcs/") || rPath.StartsWith("/gadget/"))
                rSession = new ResourceSession(rFullUrl, rPath);
            else
                rSession = new NetworkSession(rFullUrl);

            rSession.RequestBodyString = Uri.UnescapeDataString(rpSession.GetRequestBodyAsString());

            rpSession.Tag = rSession;

            SessionSubject.OnNext(rSession);

            if (rFullUrl == GameConstants.GamePageUrl || rPath == "/gadget/js/kcs_flash.js")
                rpSession.bBufferResponse = true;

            var rResourceSession = rSession as ResourceSession;
            if (rResourceSession != null)
                CacheService.Instance.ProcessRequest(rResourceSession, rpSession);
        }
Exemple #25
0
        public void FilterAndInject(Session oSession)
        {
            Debug.Log("FilterAndInject: MatchRule check!" + oSession.fullUrl);
            // response content type is text/html
            if (bGlobalEnabled && oSession.oResponse.headers.ExistsAndContains("Content-Type", "text/html"))
            {
                Debug.Log("FilterAndInject: MatchRule check!");
                // request url is match the user's config rules
                if(this.MatchRule(oSession))
                {
                    oSession.utilDecodeResponse();
                    oSession.utilReplaceOnceInResponse(@"<head>", @"<head><script>" + sScriptText + "</script>", false);

                    // script tag add crossorigin 
                    oSession.utilReplaceInResponse(@"<script", @"<script crossorigin ");

                    oSession.oResponse.headers["Cache-Control"] = "no-cache";
                    oSession.oResponse.headers["Content-Length"] = oSession.responseBodyBytes.Length.ToString();
                }
            }

           // javascript request, add cross domain header
           if (oSession.fullUrl.Contains(".js"))
           {
               if (oSession.oResponse.headers["Access-Control-Allow-Origin"] == "")
               {
                   oSession.oResponse.headers["Access-Control-Allow-Origin"] = "*";
               }
           }
        }
Exemple #26
0
        //This event fires when a server response is received by Fiddler
        static void _BeforeResponse(Session oSession)
        {
			if (!_Filter(oSession)) return;
			if (oSession.responseCode == 304)
			{
				string filepath = TaskRecord.GetAndRemove(oSession.fullUrl);
				//只有TaskRecord中有记录的文件才是验证的文件,才需要修改Header
				if (!string.IsNullOrEmpty(filepath))
				{
					//服务器返回304,文件没有修改 -> 返回本地文件
					oSession.bBufferResponse = true;
					oSession.ResponseBody = File.ReadAllBytes(filepath);
					oSession.oResponse.headers.HTTPResponseCode = 200;
					oSession.oResponse.headers.HTTPResponseStatus = "200 OK";
					oSession.oResponse.headers["Last-Modified"] = oSession.oRequest.headers["If-Modified-Since"];
					oSession.oResponse.headers["Accept-Ranges"] = "bytes";
					oSession.oResponse.headers.Remove("If-Modified-Since");
					oSession.oRequest.headers.Remove("If-Modified-Since");
					if (filepath.EndsWith(".swf"))
						oSession.oResponse.headers["Content-Type"] = "application/x-shockwave-flash";

					//Debug.WriteLine(oSession.oResponse.headers.ToString());
					//Debug.WriteLine("");
					//Debug.WriteLine("CACHR> 【捕获 304】" + oSession.PathAndQuery);
					//Debug.WriteLine("		" + filepath);
				}
			}
        }
        public void AutoTamperResponseBefore(Session oSession)
        {
            DelayedResponsesInformation delayData = null;

            //
            // when fiddler initialized
            // sometimes an exception is thrown
            //
            try
            {
                delayData = fiddlerHook.GetDelayFor(
                    oSession.url,
                    oSession.GetResponseBodyAsString()
                    );
            }
            catch (Exception) { }

            if (delayData != null)
            {
                try
                {
                    Thread.Sleep(delayData.DelaySec * 1000);
                }
                catch (Exception) { }
            }
        }
        public override void Handle(Session Session)
        {
            GameState state = FFRKProxy.Instance.GameState;
            // Win or lose, finishing a battle means it's safe to record that encounter and its drops
            // since it won't be possible for the user to have the same drop set if they continue.
            if (state.ActiveBattle != null)
            {
                EventBattleInitiated original_battle = state.ActiveBattle;
                state.ActiveBattle = null;

                lock (FFRKProxy.Instance.Cache.SyncRoot)
                {
                    DataCache.Battles.Key key = new DataCache.Battles.Key { BattleId = original_battle.Battle.BattleId };
                    DataCache.Battles.Data data = null;
                    if (FFRKProxy.Instance.Cache.Battles.TryGetValue(key, out data))
                    {
                        data.Samples++;
                        data.HistoSamples++;
                    }
                }

                DbOpRecordBattleEncounter op = new DbOpRecordBattleEncounter(original_battle);
                FFRKProxy.Instance.Database.BeginExecuteRequest(op);
                FFRKProxy.Instance.RaiseBattleComplete(original_battle);
            }
        }
        internal void ProcessRequest(ResourceSession rpResourceSession, Session rpSession)
        {
            if (CurrentMode == CacheMode.Disabled)
                return;

            string rFilename;
            var rNoVerification = CheckFileInCache(rpResourceSession.Path, out rFilename);

            rpResourceSession.CacheFilename = rFilename;

            if (rNoVerification == null)
                return;

            if (!rNoVerification.Value)
            {
                var rTimestamp = new DateTimeOffset(File.GetLastWriteTime(rFilename));

                if (rpResourceSession.Path.OICContains("mainD2.swf") || rpResourceSession.Path.OICContains(".js") || !CheckFileVersionAndTimestamp(rpResourceSession, rTimestamp))
                {
                    rpSession.oRequest["If-Modified-Since"] = rTimestamp.ToString("R");
                    rpSession.bBufferResponse = true;

                    return;
                }
            }

            rpSession.utilCreateResponseAndBypassServer();
            LoadFile(rFilename, rpResourceSession, rpSession);
        }
 void FiddlerApplication_BeforeRequest(Session oSession)
 {
     if (oSession.LocalProcess.ToLower().Contains("skypebot2"))
     {
         oSession.Ignore();
     }
 }
Exemple #31
0
        public bool CheckFilterRule(Fiddler.Session oSession)
        {
            //默认不过滤,符合条件数据才过滤
            bool filterSign = false;

            if (SaveCookieSign && (oSession.fullUrl.StartsWith(String.Format("https://{0}", ProxyUrl)) || oSession.fullUrl.StartsWith(String.Format("http://{0}", ProxyUrl))))
            {
                filterSign = true;
            }
            return(filterSign);
        }
Exemple #32
0
 private void naviEvent(Fiddler.Session oS, string type)
 {
     try {
         string svdata = oS.GetResponseBodyAsString();
         string json   = svdata.Substring(7);
         JToken temp   = JToken.Parse(json);
         OnMapNavigateEvent(new NavigateEventArgs(type, temp["api_data"]));
     } catch (Exception exception) {
         Debug.Print(exception.ToString());
     }
 }
Exemple #33
0
        /// <summary>
        /// Adds the specified Fiddler session to the end of the collection in a thread-safe fashion.
        /// </summary>
        /// <param name="session">The session to add to the collection.</param>
        public void Add(Fiddler.Session session)
        {
            lock (_lock)
            {
                // Create some room in the session list if the maximum size has been reached.
                if (_list.Count == MaximumSessionElements)
                {
                    Trace.TraceInformation("Maximum session element threshold reached ({0}); removing {1} oldest elements.", MaximumSessionElements, SessionListAdjustmentSize);
                    _list.RemoveRange(0, SessionListAdjustmentSize);
                }

                // Add specified session to the running session list.
                _list.Add(session);
            }
        }
 /// <summary>
 /// Event listener to fiddler application.
 /// </summary>
 /// <param name="session"></param>
 private void FiddlerApplication_AfterSessionComplete(Fiddler.Session session)
 {
     myListBox.Dispatcher.BeginInvoke(new UpdateUI(() =>
     {
         String fullURL = session.fullUrl;
         if (fullURL.Length != 0)
         {
             fullURL = Filter.iShttps(fullURL);
             if (Filter.FitrarPictures(fullURL) == false)
             {
                 lista.Add(fullURL);
                 myListBox.Items.Add(fullURL);
             }
         }
     }));
 }
Exemple #35
0
        private static void setUpstreamProxyHandler(Fiddler.Session requestingSession)
        {
            if (requestingSession.isHTTPS || requestingSession.port == 443)
            {
                if (useHttpsGateway)
                {
                    requestingSession["X-OverrideGateway"] = httpsGateway;
                }
                return;
            }

            if (useHttpGateway)
            {
                requestingSession["X-OverrideGateway"] = httpGateway;
            }
        }
Exemple #36
0
 public void FiddlerApplication_BeforeResponse(Fiddler.Session oSession)
 {
     lock (fiddlerLockObj)
     {
         try
         {
             String url = oSession.fullUrl;
             if (CheckFilterRule(oSession))
             {
                 String cookieRequestVal = oSession.oRequest.headers["Cookie"];
             }
         }
         catch (Exception ex)
         { MessageBox.Show(String.Format("BeforeResponse异常:" + ex.Message)); }
     }
 }
Exemple #37
0
        private static void BeforeRequestCallback(Fiddler.Session oS)
        {
            // In order to enable response tampering, buffering mode must
            // be enabled; this allows FiddlerCore to permit modification of
            // the response in the BeforeResponse handler rather than streaming
            // the response to the client as the response comes in.
            oS.bBufferResponse = true;

            if ((oS.hostname == sSecureEndpointHostname) && (oS.port == 7777))
            {
                oS.utilCreateResponseAndBypassServer();
                oS.oResponse.headers.HTTPResponseStatus = "200 Ok";
                oS.oResponse["Content-Type"]            = "text/html; charset=UTF-8";
                oS.oResponse["Cache-Control"]           = "private, max-age=0";
                oS.utilSetResponseBody("<html><body>Request for https://" + sSecureEndpointHostname + ":7777 received. Your request was:<br /><plaintext>" + oS.oRequest.headers.ToString());
            }
        }
Exemple #38
0
        //Before Request
        void FiddlerApplication_BeforeRequest(Fiddler.Session oSession)
        {
            string url = oSession.url;

            if (CheckUrl(oSession) == false || CheckDomain(oSession) == false)
            {
                //start a new thread to insert the rejected url
                if (RKey.GetValue("RegisterTraffic").ToString() == "true")
                {
                    Thread myThread = new Thread(() => InsertUrl(url, false));
                    myThread.Start();
                }

                //Redirect from the blocked website
                oSession.url = RedirectUrl;
            }
        }
Exemple #39
0
 private void battleEvent(Fiddler.Session oS, string type)
 {
     try {
         string svdata = oS.GetResponseBodyAsString();
         string json   = svdata.Substring(7);
         JToken temp   = JToken.Parse(json);
         if (type == "end")
         {
             OnBattleFinishEvent(new BattleEventArgs(type, temp["api_data"]));
         }
         else
         {
             OnBattleStartEvent(new BattleEventArgs(type, temp["api_data"]));
         }
     } catch (Exception exception) {
         Debug.Print(exception.ToString());
     }
 }
        /// <summary>
        ///	This is where the hack happens
        /// </summary>
        /// <param name="oS"></param>
        static void OnBeforeRequest(Fiddler.Session oS)
        {
            // Console.WriteLine("Before request for:\t" + oS.fullUrl);
            // In order to enable response tampering, buffering mode MUST
            // be enabled; this allows FiddlerCore to permit modification of
            // the response in the BeforeResponse handler rather than streaming
            // the response to the client as the response comes in.
            oS.bBufferResponse = false;

            if (oS.fullUrl.StartsWith("https://wpflights.trafficmanager.net/RestUpdateProvisioningService.svc/UpdateChoices?"))
            {
                oS.utilCreateResponseAndBypassServer();
                oS.oResponse.headers.SetStatus(200, "Ok");
                oS.oResponse["Content-Type"]  = "application/xml; charset=utf-8";
                oS.oResponse["Cache-Control"] = "private, max-age=0";
                // Read the XML config.
                oS.utilSetResponseBody(File.ReadAllText("WPFlights.xml"));
                FiddlerApplication.Log.LogFormat("Sending custom Flighting Response");
            }
        }
        public PassiveCheckResult RunCheck(Fiddler.Session fiddlerSession)
        {
            if (fiddlerSession.isHTTPS && fiddlerSession.oResponse.headers.Exists("set-cookie"))
            {
                string cookie = fiddlerSession.oResponse.headers["set-cookie"];

                if (cookie != null && cookie.Length > 0)
                {
                    string[] parts      = cookie.Split(';');
                    string   cookiename = parts[0];
                    cookiename = cookiename.Split('=')[0];

                    if (parts != null && parts.Length > 0)
                    {
                        bool isSecured   = false;
                        bool isDomainSet = false;

                        parts.ForEach(v =>
                        {
                            if (v.Trim().ToLower() == "secure")
                            {
                                isSecured = true;
                            }

                            if (v.Trim().ToLower().StartsWith("domain"))
                            {
                                isDomainSet = true;
                            }
                        });

                        if (!isSecured)
                        {
                            return(PassiveCheckResult.CreateFailure(this, fiddlerSession.fullUrl, "Cookie not marked as secure"));
                        }
                    }
                }
            }

            return(PassiveCheckResult.CreatePass(this, fiddlerSession.fullUrl));
        }
        private static void TranslateSession(Fiddler.Session sess)
        {
            var handler = AfterSessionComplete;

            if (handler == null)
            {
                return;
            }

            if (sess.RequestMethod == "CONNECT")
            {
                return;
            }
            if (string.IsNullOrWhiteSpace(sess.RequestMethod))
            {
                return;
            }

            sess.utilDecodeRequest();
            sess.utilDecodeResponse();

            handler(new Session(sess));
        }
Exemple #43
0
 static void _AfterComplete(Session oSession)
 {
 }
Exemple #44
0
 private static void raiseResponseHeadersAvailable(Fiddler.Session session)
 {
     InvokeAfterReadResponseHeaders(new HttpResponse(session.GenerateStatusLine(), session.ResponseHeaders.GenerateHeaders(), null));
 }
Exemple #45
0
 private static void raiseAfterSessionComplete(Fiddler.Session session)
 {
     InvokeAfterSessionComplete(session.ToNekoxySession());
 }
Exemple #46
0
 public FiddlerSessionBrowsingResponse(Fiddler.Session session)
 {
     this.session = session;
 }
Exemple #47
0
        public void FiddlerApplication_BeforeRequest(Fiddler.Session oSession)
        {
            lock (fiddlerLockObj)
            {
                try
                {
                    if (CheckFilterRule(oSession))
                    {
                        oSession.bBufferResponse = true;

                        #region 人寿替换请求
                        if (oSession.fullUrl.Equals("https://ins.chinalife-p.com.cn/workbench/workbench/login.html"))
                        {
                            oSession.fullUrl = "https://ins.chinalife-p.com.cn/workbench/workbench/index.html";
                        }
                        #endregion

                        String           requestCookie      = oSession.oRequest.headers["Cookie"].ToString();
                        FiddlerCacheInfo cookieRequestModel = new FiddlerCacheInfo(requestCookie);
                        if (CookieModel != null)
                        {
                            //如果全部相等
                            //if (CookieModel.CookieStr.Equals(cookieRequestModel.CookieStr)) { return; }
                            #region 更新cookie,不能完全替换
                            int changeCookieSign = 0;
                            foreach (var requestItem in cookieRequestModel.CookieDic)
                            {
                                if (CookieModel.CookieDic.ContainsKey(requestItem.Key) && !String.IsNullOrEmpty(requestItem.Value))
                                {
                                    if (ProxyUrl.Contains("ins.chinalife-p.com.cn"))
                                    {
                                        if (requestItem.Value.Contains("AlteonP73workbench"))
                                        {
                                            CookieModel.CookieDic[requestItem.Key] = requestItem.Value;
                                            Log(String.Format("fiddler 键值对需要更新:{0}={1}", requestItem.Key, requestItem.Value));
                                            changeCookieSign++;
                                        }
                                    }
                                    else
                                    {
                                        //CookieModel.CookieDic[requestItem.Key] = requestItem.Value;
                                        //SetRichText(String.Format("fiddler 键值对需要更新:{0}={1}", requestItem.Key, requestItem.Value));
                                        //标记需要更新
                                        changeCookieSign++;
                                    }
                                }
                                else
                                {
                                    CookieModel.CookieDic.Add(requestItem.Key, requestItem.Value);
                                    Log(String.Format("fiddler 键值对需要新增:{0}={1}", requestItem.Key, requestItem.Value));
                                    changeCookieSign++;
                                }
                            }
                            if (changeCookieSign > 0)
                            {
                                //生成新的cookieSb
                                StringBuilder newCookieSb = new StringBuilder();
                                foreach (var item in CookieModel.CookieDic)
                                {
                                    newCookieSb.Append(String.Format(";{0}={1}", item.Key, item.Value));
                                }
                                String newCookieStr = newCookieSb.ToString().Trim(new char[] { ';' }).Trim();
                                if (!String.IsNullOrEmpty(newCookieStr))
                                {
                                    CookieModel = new FiddlerCacheInfo(newCookieStr);
                                    Log(String.Format("fiddler更新Cookie为:{0}", newCookieStr));
                                }
                            }
                            #endregion
                            if (!oSession.oRequest.headers.Exists("Cookie"))
                            {
                                oSession.oRequest.headers.Add("Cookie", "");
                            }
                            oSession.oRequest.headers["Cookie"] = CookieModel.CookieStr;
                            Log(String.Format("fiddler修改了请求:{0}", oSession.fullUrl.ToString()));
                        }
                    }
                }
                catch (Exception ex)
                { MessageBox.Show(String.Format("BeforeRequest异常:" + ex.Message)); }
            }
        }
Exemple #48
0
        private static void BeforeResponseCallback(Fiddler.Session oSession)
        {
            string url = oSession.url.ToLower();

            foreach (ReplaceMapEntry entry in replaceMap)
            {
                if (url.Contains(entry.sourcePath))
                {
                    string replacementFile = string.Empty;
                    if (!entry.sourcePath.EndsWith("/"))
                    {
                        replacementFile = entry.destinationPath;
                    }
                    else
                    {
                        if (url.Contains(".js") ||
                            url.Contains(".css") ||
                            url.Contains(".png") ||
                            url.Contains(".html") ||
                            url.Contains(".htm"))
                        {
                            int startIndex = url.IndexOf(entry.sourcePath);
                            startIndex     += entry.sourcePath.Length;
                            replacementFile = url.Substring(startIndex, (url.Length - startIndex));

                            int queryParam = replacementFile.IndexOf("?");
                            if (queryParam > 0)
                            {
                                replacementFile = replacementFile.Substring(0, queryParam);
                            }

                            replacementFile = replacementFile.Replace("/", "\\");
                            replacementFile = entry.destinationPath + replacementFile;
                        }
                    }

                    if (!string.IsNullOrEmpty(replacementFile))
                    {
                        try
                        {
                            if (oSession.bHasResponse)
                            {
                                if (replacementFile.EndsWith(".png"))
                                {
                                    byte[] buffer = File.ReadAllBytes(replacementFile);
                                    if (buffer != null && buffer.Length > 0)
                                    {
                                        oSession.responseBodyBytes           = buffer;
                                        oSession.oResponse["Content-Length"] = buffer.Length.ToString();
                                        oSession.oResponse["Content-Type"]   = "image/png";

                                        Util.PrintMessage("Replaced " + replacementFile);
                                    }
                                    else
                                    {
                                        throw (new Exception());
                                    }
                                }
                                else //for text files
                                {
                                    string buffer = File.ReadAllText(replacementFile);
                                    if (buffer != null && buffer.Length > 0)
                                    {
                                        oSession.utilDecodeResponse();
                                        oSession.utilSetResponseBody(buffer);
                                        oSession.responseCode = 200;

                                        if (replacementFile.EndsWith(".js"))
                                        {
                                            oSession.oResponse.headers.Add("Content-Type", "application/x-javascript");
                                        }
                                        else if (replacementFile.EndsWith(".css"))
                                        {
                                            oSession.oResponse.headers.Add("Content-Type", "text/css");
                                        }
                                        else if (replacementFile.EndsWith(".html") || replacementFile.EndsWith(".htm"))
                                        {
                                            oSession.oResponse.headers.Add("Content-Type", "text/html");
                                        }

                                        Util.PrintMessage("Replaced " + replacementFile);
                                    }
                                    else
                                    {
                                        throw (new Exception());
                                    }
                                }
                            }
                            else
                            {
                                Util.PrintMessage("Waiting for response");
                            }
                        }
                        catch (Exception ex)
                        {
                            Util.PrintError("Could not replace file " + replacementFile + ". Error: " + ex.Message);
                        }
                    }

                    break;
                }
            }
        }
Exemple #49
0
 private void FiddlerApplication_AfterSessionComplete(Fiddler.Session oS)
 {
     Console.WriteLine("Finished session: (" + DateTime.Now + ")\t" + oS.fullUrl);
 }
Exemple #50
0
 public HttpResponse(Fiddler.Session sess)
 {
     this.StatusLine = new HttpStatusLine(sess);
     this.Body       = (byte[])sess.responseBodyBytes.Clone();
     this.Headers    = new HttpHeaders(sess.ResponseHeaders, sess);
 }
Exemple #51
0
 public void AutoTamperRequestBefore(Fiddler.Session oSession)
 {
 }
 public WebTestSession(Fiddler.Session Session)
 {
     this.m_session = Session;
 }
Exemple #53
0
        bool CheckUrl(Fiddler.Session oSession)
        {
            string url = oSession.url;

            //Check if it is in custom table
            MySqlConnection Conn = new MySqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]);

            try
            {
                RegistryKey reg      = Registry.CurrentUser.OpenSubKey("Noriy");
                string      username = reg.GetValue("username").ToString();

                int size1 = url.IndexOf('/');

                string domain1 = "";

                string domain2 = url;

                if (url.Substring(0, 4) == "www.")
                {
                    domain2 = url.Substring(4, domain2.Length - 4);
                }

                int size2 = domain2.IndexOf('/');

                if (size1 < 1)
                {
                    domain1 = url;
                }
                else
                {
                    domain1 = url.Substring(0, size1);
                }

                if (size2 > 1)
                {
                    domain2 = domain2.Substring(0, size2);
                }

                if (domain1 != domain2)
                {
                    Conn.Open();

                    string searchQuery1 = "select count(*) from " + username + "_custom where Url like '%" + domain1 + "%'";
                    string searchQuery2 = "select count(*) from " + username + "_custom where Url like '%" + domain2 + "%'";

                    MySqlCommand Command1 = new MySqlCommand(searchQuery1, Conn);
                    MySqlCommand Command2 = new MySqlCommand(searchQuery2, Conn);

                    int count1 = Convert.ToInt32(Command1.ExecuteScalar().ToString());
                    int count2 = Convert.ToInt32(Command2.ExecuteScalar().ToString());

                    if (count1 > 0 || count2 > 0)
                    {
                        return(false);
                    }

                    Conn.Close();
                }
                else
                {
                    Conn.Open();
                    string       searchQuery2 = "select count(*) from " + username + "_custom where Url like '%" + domain2 + "%'";
                    MySqlCommand Command2     = new MySqlCommand(searchQuery2, Conn);
                    int          count2       = Convert.ToInt32(Command2.ExecuteScalar().ToString());



                    if (count2 > 0)
                    {
                        return(false);
                    }

                    Conn.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

            return(true);
        }
Exemple #54
0
        /// <summary>
        /// Fiddler からのリクエスト発行時にプロキシを挟む設定を行います。
        /// </summary>
        /// <param name="requestingSession">通信を行おうとしているセッション。</param>
        private void Fiddler_BeforeRequest(Fiddler.Session requestingSession)
        {
            if (requestingSession.hostname == "kancolleviewer.local")
            {
                requestingSession.utilCreateResponseAndBypassServer();
                var path       = requestingSession.PathAndQuery;
                var queryIndex = path.IndexOf('?');
                if (queryIndex >= 0)
                {
                    path = path.Substring(0, queryIndex);
                }

                Action <Fiddler.Session> handler;
                if (localRequestHandlers.TryGetValue(path, out handler))
                {
                    requestingSession.oResponse.headers.HTTPResponseCode   = 200;
                    requestingSession.oResponse.headers.HTTPResponseStatus = "200 OK";
                    handler?.Invoke(requestingSession);
                }
                else
                {
                    requestingSession.oResponse.headers.HTTPResponseCode   = 410;
                    requestingSession.oResponse.headers.HTTPResponseStatus = "410 Gone";
                }
                return;
            }

            var settings = this.UpstreamProxySettings;

            if (settings == null)
            {
                return;
            }

            var compiled = settings.CompiledRules;

            if (compiled == null)
            {
                settings.CompiledRules = compiled = ProxyRule.CompileRule(settings.Rules);
            }
            var result = ProxyRule.ExecuteRules(compiled, requestingSession.RequestMethod, new Uri(requestingSession.fullUrl));

            if (result.Action == ProxyRule.MatchAction.Block)
            {
                requestingSession.utilCreateResponseAndBypassServer();
                requestingSession.oResponse.headers.HTTPResponseCode   = 450;
                requestingSession.oResponse.headers.HTTPResponseStatus = "450 Blocked As Requested";
                return;
            }

            if (KanColleClient.Current.Settings.DisallowSortieWithHeavyDamage)
            {
                if (KanColleClient.Current.Homeport.Organization.Fleets.Any(x => x.Value.IsInSortie && x.Value.State.Situation.HasFlag(Models.FleetSituation.HeavilyDamaged)))
                {
                    if (requestingSession.PathAndQuery.Length > 7 &&
                        requestingSession.PathAndQuery.Substring(0, 7) == "/kcsapi" &&
                        (requestingSession.PathAndQuery.Contains("battle") || requestingSession.PathAndQuery.Contains("sortie")) &&
                        !requestingSession.PathAndQuery.Contains("practice") &&
                        !requestingSession.PathAndQuery.Contains("result"))
                    {
                        requestingSession.utilCreateResponseAndBypassServer();
                        requestingSession.oResponse.headers.HTTPResponseCode   = 450;
                        requestingSession.oResponse.headers.HTTPResponseStatus = "450 Blocked As Requested";
                        return;
                    }
                }
            }

            if (result.Action == ProxyRule.MatchAction.Proxy && result.Proxy != null)
            {
                requestingSession["X-OverrideGateway"] = result.Proxy;
                if (result.ProxyAuth != null && !requestingSession.RequestHeaders.Exists("Proxy-Authorization"))
                {
                    requestingSession["X-OverrideGateway"] = result.Proxy;
                    requestingSession.RequestHeaders.Add("Proxy-Authorization", result.ProxyAuth);
                }
            }

            requestingSession.bBufferResponse = false;
        }
Exemple #55
0
 static bool _Filter(Session oSession)
 {
     return(oSession.PathAndQuery.StartsWith("/kcs/"));
 }
Exemple #56
0
 public HTTPSamplerProxy(Fiddler.Session session)
 {
     this.session = session;
 }
Exemple #57
0
 public Session(Fiddler.Session sess)
 {
     Request  = new HttpRequest(sess);
     Response = new HttpResponse(sess);
     _sess    = sess;
 }
Exemple #58
0
 public SessionEventArgs(Fiddler.Session oS, Core core)
 {
     Session = new Session(oS, core);
 }
Exemple #59
0
 public void AutoTamperResponseAfter(Fiddler.Session oSession)
 {
 }
Exemple #60
0
        void FiddlerApplication_AfterSessionComplete(Fiddler.Session oSession)
        {
            if (true)             //oSession.fullUrl.Contains("125.6.189.247"))  //宿毛湾泊地サーバのIP
            {
                var responseResult = oSession.GetResponseBodyAsString();
                Debug.WriteLine(responseResult);
                if (oSession.fullUrl.Contains("/kcsapi/"))
                {
                    Console.WriteLine(string.Format("Session{0}({3}):HTTP {1} for {2}", oSession.id, oSession.responseCode, oSession.fullUrl, oSession.oResponse.MIMEType));
                    Debug.WriteLine(string.Format("Session{0}({3}):HTTP {1} for {2}", oSession.id, oSession.responseCode, oSession.fullUrl, oSession.oResponse.MIMEType));

                    try
                    {
                        var jsonData = DynamicJson.Parse(responseResult.Replace("svdata=", string.Empty));

                        //装備のデータリスト(jsonData.api_data.api_mst_slotitem)を取得しログに吐く
                        try
                        {
                            object[] slotitemsLog = jsonData.api_data.api_mst_slotitem;
                            using (var log = new StreamWriter(new FileStream("Start2_EquipLog.txt", FileMode.Create)))
                            {
                                foreach (var slotitem in slotitemsLog)
                                {
                                    log.WriteLine(slotitem);
                                }
                            }

                            //艦娘のデータリスト(jsonData.api_data.api_mst_ship)を取得しログに吐く

                            object[] shipsLog = jsonData.api_data.api_mst_ship;
                            using (var log = new StreamWriter(new FileStream("Start2_ShipLog.txt", FileMode.Create)))
                            {
                                foreach (var ship in shipsLog)
                                {
                                    log.WriteLine(ship);
                                }
                            }
                        }catch (Exception excep) {
                            //Console.WriteLine(excep);
                        }

                        if (oSession.fullUrl.Contains("api_start2"))
                        {
                            start2 = jsonData;
                            //using (var log = new StreamWriter(new FileStream("start2_log.txt", FileMode.Append)))
                            //{
                            //	log.WriteLine(start2);

                            //}
                            object[] slotitems = jsonData.api_data.api_mst_slotitem;
                            foreach (var slotitem in slotitems)
                            {
                                //Console.WriteLine(slotitem.ToString());
                                start2.SlotItemList.Add(slotitem);
                            }
                            object[] ships = jsonData.api_data.api_mst_ship;
                            foreach (var ship in ships)
                            {
                                //Console.WriteLine(ship.ToString());
                                start2.SlotItemList.Add(ship);
                            }
                        }

                        if (oSession.fullUrl.Contains("api_req_kousyou/createitem"))                        //開発時のapiリクエスト
                        {
                            fleetMaterial.NowMaterial.Fuel       = jsonData.api_data.api_material[0];
                            fleetMaterial.NowMaterial.Ammunition = jsonData.api_data.api_material[1];
                            fleetMaterial.NowMaterial.Steel      = jsonData.api_data.api_material[2];
                            fleetMaterial.NowMaterial.Bauxite    = jsonData.api_data.api_material[3];


                            //Console.WriteLine(fleetMaterial.BeforeMaterial);
                            //Console.WriteLine(fleetMaterial.NowMaterial);

                            Material recipeMaterial = new Material();
                            recipeMaterial.Fuel       = fleetMaterial.BeforeMaterial.Fuel - fleetMaterial.NowMaterial.Fuel;
                            recipeMaterial.Ammunition = fleetMaterial.BeforeMaterial.Ammunition - fleetMaterial.NowMaterial.Ammunition;
                            recipeMaterial.Steel      = fleetMaterial.BeforeMaterial.Steel - fleetMaterial.NowMaterial.Steel;
                            recipeMaterial.Bauxite    = fleetMaterial.BeforeMaterial.Bauxite - fleetMaterial.NowMaterial.Bauxite;


                            KaihatsuResult kaihatsuResult = new KaihatsuResult();
                            kaihatsuResult.Recipe       = recipeMaterial;
                            kaihatsuResult.FlagShipName = "";
                            kaihatsuResult.FlagShipLv   = 0;
                            kaihatsuResult.FleetLv      = 0;

                            if (jsonData.api_data.api_create_flag == 1)
                            {
                                //kaihatsuResult = "成功";
                                //equipName = jsonData.api_data.api_slot_item.api_slotitem_id;
                                kaihatsuResult.IsSuccess = true;
                                int itemId = int.Parse(jsonData.api_data.api_slot_item.api_slotitem_id.ToString());
                                kaihatsuResult.ItemName = start2.getItemName(itemId);
                            }
                            else
                            {
                                //kaihatsuResult = "失敗";
                                //equipName = jsonData.api_data.api_fdata;
                                kaihatsuResult.IsSuccess = false;
                                kaihatsuResult.ItemName  = jsonData.api_data.api_fdata;

                                int itemId = int.Parse(jsonData.api_data.api_fdata.Split(',')[1]);
                                //Console.WriteLine("itemId={0}",itemId);
                                kaihatsuResult.ItemName = start2.getItemName(itemId);
                            }


                            kaihatsuResultList.Add(kaihatsuResult);                             //開発結果の追加

                            using (var log = new StreamWriter(new FileStream("kaihatsuResult_log.txt", FileMode.Append)))
                            {
                                log.WriteLine(kaihatsuResult);                                 //ログを残す
                            }


                            //Console.WriteLine("レシピ:" +recipeFuel +"/" +recipeAmmunition +"/"+recipeSteel +"/" +recipeBauxite +"\t開発結果:" +kaihatsuResult +"\t装備id (?):" +equipName);
                            Console.WriteLine(kaihatsuResultList[(kaihatsuResultList.Count - 1)]);
                        }
                        else if (oSession.fullUrl.Contains("api_port/port"))                        //母港開いた時のリクエスト
                        {
                            fleetMaterial.NowMaterial.Fuel       = jsonData.api_data.api_material[0].api_value;
                            fleetMaterial.NowMaterial.Ammunition = jsonData.api_data.api_material[1].api_value;
                            fleetMaterial.NowMaterial.Steel      = jsonData.api_data.api_material[2].api_value;
                            fleetMaterial.NowMaterial.Bauxite    = jsonData.api_data.api_material[3].api_value;

                            Console.WriteLine(fleetMaterial.NowMaterial);
                        }
                        else
                        {
                            //material = "うんこ";
                        }

                        fleetMaterial.BeforeMaterial = (Material)fleetMaterial.NowMaterial.Clone();
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine(e);
                    }
                }
            }
        }