Esempio n. 1
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 
			{ 
				//下载文件
			}
        }
        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 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;
        }
Esempio n. 4
0
        private void FiddlerApplication_BeforeRequest(Session oSession)
        {
            if (!set.CacheEnabled) return;

            if (oSession.PathAndQuery.StartsWith("/kcsapi/api_req_furniture/music_play") && set.HackMusicRequestEnabled)
            {
                oSession.utilCreateResponseAndBypassServer();
                oSession.oResponse.headers.Add("Content-Type", "text/plain");
                oSession.utilSetResponseBody(@"svdata={""api_result"":1,""api_result_msg"":""\u6210\u529f"",""api_data"":{""api_coin"":" + fcoin.ToString() + @"}}");
            }
            else if (oSession.PathAndQuery.StartsWith("/kcsapi/api_get_member/picture_book") && set.HackBookEnabled)
            {
                oSession.utilCreateResponseAndBypassServer();
                oSession.oResponse.headers.Add("Content-Type", "text/plain");

                int type = 1; // 1: 舰娘图鉴, 2: 装备图鉴
                int no = 1;   // 页数
                var param = oSession.GetRequestBodyAsString().Split('&');
                foreach (var p in param)
                {
                    var kv = p.Split('=');
                    if (kv[0] == "api%5Ftype")
                    {
                        type = int.Parse(kv[1]);
                    }
                    else if (kv[0] == "api%5Fno")
                    {
                        no = int.Parse(kv[1]);
                    }
                }

                if (type == 1)
                {
                    oSession.utilSetResponseBody("svdata=" + ShipBookData.Generate(initData, no * 70 - 69, no * 70).ToJsonString());
                }
                else
                {
                    oSession.utilSetResponseBody("svdata=" + EquipmentBookData.Generate(initData, no * 50 - 49, no * 50).ToJsonString());
                }
            }
        }
        public static void BeforeRequest(Session oS)
        {
            var file = oS.url.Replace('/', '_').Split('?').First();
            var method = oS.HTTPMethodIs("GET") ? "GET"
                             : oS.HTTPMethodIs("POST") ? "POST"
                                   : oS.HTTPMethodIs("PUT") ? "PUT" : null;
            oS.utilCreateResponseAndBypassServer();
            var lines = File.ReadAllLines("./Api/Data/" + method + " " + file + ".txt");
            oS.oResponse.headers = Parser.ParseResponse(lines.First());
            oS.oResponse.headers.Add("Content-Type", "application/json");

            oS.utilSetResponseBody(String.Join(Environment.NewLine, lines.Skip(2).ToArray()));
        }
Esempio n. 6
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());
            }
        }
Esempio n. 7
0
        /// <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 void AutoTamperRequestBefore(Session session)
        {
            if (Settings.enabled && session.HostnameIs(reportHost) && !session.isFTP)
            {
                // TODO: We should offer an option to hide the reports from Fiddler; change "ui-strikeout" to "ui-hide" in the next line
                session["ui-strikeout"] = "CSPReportGenerator";

                if (!session.HTTPMethodIs("CONNECT"))
                {
                    session.utilCreateResponseAndBypassServer();
                    session.oResponse.headers.Add("Content-Type", "text/html");
                    session.ResponseBody = Encoding.UTF8.GetBytes("<!doctype html><HTML><BODY><H1>Report received.</H1></BODY></HTML>");

                    ProcessCSPReport(session);
                }
                else
                {
                    session["x-replywithtunnel"] = "CSPReportGenerator";
                }
            }
        }
Esempio n. 9
0
        private void FiddlerApplication_BeforeRequest(Session oSession) {

            // using proxy
            if (Utility.Config.Instance.UseUpstreamProxy) {
                oSession["X-OverrideGateway"] = string.Format("{0}:{1}", Utility.Config.Instance.UpstreamProxyHost, Utility.Config.Instance.UpstreamProxyPort);
            }

            if (oSession.PathAndQuery.StartsWith("/kcs/")) {
                string filePath;
                var direction = Cache.GotNewRequest(oSession.PathAndQuery, out filePath);

                if (direction == Direction.Return_LocalFile) {

                    // 返回本地文件 
                    oSession.utilCreateResponseAndBypassServer();
                    oSession.oResponse.headers.HTTPResponseCode = 304;

                    Utility.Logger.Add("Request  > [使用本地文件]" + filePath);
                } else if (direction == Direction.Verify_LocalFile) {

                    // 請求驗證 
                    oSession.oRequest.headers["If-Modified-Since"] = GMTHelper._GetModifiedTime(filePath);
                    oSession.bBufferResponse = true;

                    Utility.Logger.Add("Request  > [驗證本地文件]" + oSession.PathAndQuery);
                } else if (direction == Direction.Discharge_Response) {

                    Utility.Logger.Add("Request  > [重新下載]" + oSession.PathAndQuery);
                }

            } else if (oSession.PathAndQuery.StartsWith("/kcsapi/")) {
                if (oSession.PathAndQuery.StartsWith("/kcsapi/api_start2")) {
                    oSession.bBufferResponse = true;
                }
            }
        }
        private static void EchoEntry(Session session)
        {
            Uri hostName = new Uri(string.Format("http://{0}/", session.oRequest["Host"]));
            Uri tableUrl = new Uri(session.fullUrl);
            string requestString = session.GetRequestBodyAsString();

            string timestamp = DateTime.UtcNow.ToString("o");
            string etag = string.Format("W/\"datetime'{0}'\"", Uri.EscapeDataString(timestamp));

            XElement request = XElement.Parse(requestString);

            request.SetAttributeValue(XNamespace.Xml + "base", hostName.AbsoluteUri);
            request.SetAttributeValue(TableConstants.Metadata + "etag", Uri.EscapeDataString(etag));

            string partitionKey = request.Descendants(TableConstants.OData + "PartitionKey").Single().Value;
            string rowKey = request.Descendants(TableConstants.OData + "RowKey").Single().Value;

            Uri entryUri = new Uri(string.Format(
                "{0}(PartitionKey='{1}',RowKey='{2}')",
                tableUrl.AbsoluteUri,
                Uri.EscapeUriString(partitionKey),
                Uri.EscapeUriString(rowKey)));

            XElement timestampElement = request.Descendants(TableConstants.OData + "Timestamp").Single();
            timestampElement.Value = timestamp;

            XElement updatedElement = request.Descendants(TableConstants.Atom + "updated").Single();
            updatedElement.Value = timestamp;

            XElement idElement = request.Descendants(TableConstants.Atom + "id").Single();
            idElement.Value = entryUri.AbsoluteUri;

            // Add link
            XElement linkElement = new XElement(
                TableConstants.Atom + "link",
                new XAttribute("rel", "edit"),
                new XAttribute("href", entryUri.PathAndQuery.Substring(1)));
            idElement.AddAfterSelf(linkElement);

            // Add category
            string accountName = hostName.Host.Substring(0, hostName.Host.IndexOf('.'));
            string categoryName = accountName + "." + tableUrl.PathAndQuery.Substring(1);
            idElement.AddAfterSelf(TableConstants.GetCategory(categoryName));

            // mark that we're going to tamper with it
            session.utilCreateResponseAndBypassServer();

            session.oResponse.headers = CreateResponseHeaders(entryUri.AbsoluteUri);
            session.oResponse.headers["ETag"] = etag;

            session.responseCode = 201;

            string responseString = request.ToString();
            session.utilSetResponseBody(responseString);
        }
        /// <summary>
        /// CreateTableError creates an error response from a table API.
        /// </summary>
        /// <param name="session">The session with which to tamper.</param>
        /// <param name="statusCode">The error code to return</param>
        /// <param name="messageCode">The string name for the error</param>
        /// <param name="message">The long error message to be returned.</param>
        private static void CreateTableError(Session session, int statusCode, string messageCode, string message)
        {
            session.utilCreateResponseAndBypassServer();
            session.oResponse.headers = CreateResponseHeaders(null);
            session.responseCode = statusCode;

            session.utilSetResponseBody(
                TableConstants.GetError(
                    messageCode,
                    string.Format(
                        "{0}\r\nRequestId:{1}\r\nTime:{2}",
                        message,
                        Guid.Empty.ToString(),
                        DateTime.UtcNow.ToString("o"))).ToString());
        }
        /// <summary>
        /// GetTableWithCode tampers with with the request to return the specific table and a success code.
        /// </summary>
        /// <param name="session"></param>
        /// <param name="statusCode"></param>
        private static void GetTableWithCode(Session session, int statusCode)
        {
            // Find relevant facts about this table creation.
            Uri hostName = new Uri(string.Format("http://{0}/", session.oRequest["Host"]));
            string requestString = session.GetRequestBodyAsString();

            string tableName = null;
            string tableUri = null;
            if (string.IsNullOrEmpty(requestString))
            {
                tableName = tableNameRegex.Match(session.url).Groups[1].Value;
            }
            else
            {
                XElement request = XElement.Parse(requestString);
                tableName = request.Descendants(TableConstants.OData + "TableName").Single().Value;
                tableUri = new Uri(hostName, string.Format("/Tables('{0}')", tableName)).AbsoluteUri;
            }

            // mark that we're going to tamper with it
            session.utilCreateResponseAndBypassServer();

            session.oResponse.headers = CreateResponseHeaders(tableUri);
            session.responseCode = statusCode;

            // Create the response XML
            XElement response = TableConstants.GetEntry(hostName.AbsoluteUri);

            response.Add(new XElement(TableConstants.Atom + "id", session.fullUrl));
            response.Add(new XElement(TableConstants.Title));
            response.Add(new XElement(TableConstants.Atom + "updated", DateTime.UtcNow.ToString("o")));
            response.Add(TableConstants.Author);

            response.Add(TableConstants.GetLink(tableName));

            string accountName = hostName.Host.Substring(0, hostName.Host.IndexOf('.'));
            response.Add(TableConstants.GetCategory(accountName + ".Tables"));

            // Add in the most important part -- the table name.
            response.Add(new XElement(
                TableConstants.Atom + "content",
                new XAttribute("type", "application/xml"),
                new XElement(
                    TableConstants.Metadata + "properties",
                    new XElement(
                        TableConstants.OData + "TableName",
                        tableName))));

            string responseString = response.ToString();
            session.utilSetResponseBody(responseString);
        }
Esempio n. 13
0
        static void LoadFromCacheCore(FiddlerSession rpSession, ResourceSession rpResourceSession, string rpPath)
        {
            rpSession.utilCreateResponseAndBypassServer();
            rpSession.ResponseBody = File.ReadAllBytes(rpPath);

            rpResourceSession.LoadedBytes = rpSession.ResponseBody.Length;
            rpResourceSession.Status = SessionStatus.LoadedFromCache;
        }
Esempio n. 14
0
        private void ProcessBeginRequest(Session oS)
        {
            var info = new SessionInfo(oS);

            oS.host = info.Host;
            oS.PathAndQuery = info.PathAndQuery;

            switch (info.Type)
            {
                case SessionType.Record:
                    RecordSession(oS, info);
                    break;

                case SessionType.Playback:
                    PlaybackSession(oS, info);
                    break;
                case SessionType.InvalidMimeType:
                    oS.utilCreateResponseAndBypassServer();
                    oS.responseCode = 500;
                    oS.utilSetResponseBody("Invalid MIME type");

                    break;
                case SessionType.Export:
                    oS.utilCreateResponseAndBypassServer();
                    oS.responseCode = 200;
                    // #TODO: set content-type etc
                    Tape tape = _store.Select(info.UserId + "." + info.TapeId);
                    if (tape == null)
                    {
                        oS.utilCreateResponseAndBypassServer();
                        oS.responseCode = 404;
                        oS.utilSetResponseBody("Tape not found");
                        return;
                    }
                    oS.oResponse.headers["Content-Type"] = "text/json";
                    oS.utilSetResponseBody(JsonConvert.SerializeObject(tape, Formatting.Indented));

                    break;

            }
        }
Esempio n. 15
0
        /// <summary>
        /// Fiddler からのリクエスト発行時にプロキシを挟む設定を行います。
        /// </summary>
        /// <param name="requestingSession">通信を行おうとしているセッション。</param>
        private void Fiddler_BeforeRequest(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<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 = 403;
                requestingSession.oResponse.headers.HTTPResponseStatus = "403 Forbidden";
                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;
        }
Esempio n. 16
0
 private static void _returnRootCert(Session oS)
 {
     oS.utilCreateResponseAndBypassServer();
     oS.oResponse.headers["Connection"] = "close";
     oS.oResponse.headers["Cache-Control"] = "max-age=0";
     byte[] buffer = CertMaker.getRootCertBytes();
     if (buffer != null)
     {
         oS.oResponse.headers["Content-Type"] = "application/x-x509-ca-cert";
         oS.responseBodyBytes = buffer;
         oS.oResponse.headers["Content-Length"] = oS.responseBodyBytes.Length.ToString();
     }
     else
     {
         oS.responseCode = 0x194;
         oS.oResponse.headers["Content-Type"] = "text/html; charset=UTF-8";
         oS.utilSetResponseBody("No root certificate was found. Have you enabled HTTPS traffic decryption in Fiddler yet?".PadRight(0x200, ' '));
     }
     FiddlerApplication.DoResponseHeadersAvailable(oS);
     oS.ReturnResponse(false);
 }
        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;
        }
Esempio n. 18
0
        // api 모드 실행
        void runApiMode(Session oSession)
        {
            PLinkApiType data = router(oSession.PathAndQuery);

            if (data == null) {
                oSession.oRequest.pipeClient.End();
            } else {
                SetDiabledCache(oSession);
                // 새로운 응답 만들기
                oSession.utilCreateResponseAndBypassServer();
                oSession.oResponse.headers.HTTPResponseCode = 200;
                oSession.oResponse.headers.HTTPResponseStatus = "200 OK";
                oSession.oResponse.headers["Content-Type"] = data.ContentType;
                SetDiabledCacheAfter(oSession);
                oSession.utilSetResponseBody(data.Body);
            }
        }
Esempio n. 19
0
        public void AutoTamperRequestBefore(Session oSession)
        {
            if (!IsEnabled)
            {
                return;
            }

            string fullString = oSession.fullUrl.ToLower();

            if (fullString.EndsWith("imposter.js") && EnableAutoReload)
            {
                oSession.utilCreateResponseAndBypassServer();
                var js = Path.GetFullPath("Scripts\\imposter.js");
                oSession.LoadResponseFromFile(js);
                oSession.ResponseHeaders.Add("x-imposter", js);
            }

            if (fullString.ToLower().Contains("/imposter-poll-for-changes?profileid=") && EnableAutoReload)
            {
                var profileIdIndex = fullString.ToLower().IndexOf("/imposter-poll-for-changes?profileid=");
                var profileIdFragment = fullString.Substring(profileIdIndex + "/imposter-poll-for-changes?profileid=".Length);

                Guid profileId;
                var success = Guid.TryParse(profileIdFragment, out profileId);

                oSession.utilCreateResponseAndBypassServer();
                oSession.ResponseHeaders.Add("x-imposter", "AUTO RELOAD");

                if (success && _enabledProfiles.Any(p => p.ProfileId == profileId && p.HasChanges))
                {
                    oSession.utilSetResponseBody("true");
                    _enabledProfiles.ForEach(p => p.HasChanges = false);
                }
                else
                {
                    oSession.utilSetResponseBody("false");
                }
            }

            foreach (var profile in _enabledProfiles)
            {
                var path = profile.GetFileMatch(fullString);

                if (path == null)
                {
                    continue;
                }

                oSession.utilCreateResponseAndBypassServer();
                oSession.LoadResponseFromFile(path);
                oSession.ResponseHeaders.Add("x-imposter", path);
                if (oSession.ViewItem != null)
                {
                    oSession.ViewItem.BackColor = Color.SkyBlue;
                }
                // Only swap for the first match
                break;
            }
        }
Esempio n. 20
0
 private void RecordSession(Session oS, SessionInfo info)
 {
     try
     {
         if (_secured)
         {
             Tape tape = _store.Select(info.UserId + "." + info.TapeId);
             if (tape == null)
             {
                 oS.utilCreateResponseAndBypassServer();
                 oS.responseCode = 404;
                 oS.utilSetResponseBody("Tape not found");
                 return;
             }
             if (!tape.OpenForRecording)
             {
                 oS.utilCreateResponseAndBypassServer();
                 oS.responseCode = 412;
                 oS.utilSetResponseBody("Tape is not open for recording");
                 return;
             }
             string ip = GetClientIp(oS);
             if (ip != tape.AllowedIpAddress)
             {
                 oS.utilCreateResponseAndBypassServer();
                 oS.responseCode = 403;
                 oS.utilSetResponseBody("IP " + GetClientIp(oS) + " not allowed to record.");
                 return;
             }
         }
         oS.bBufferResponse = true;
         RecordCache.TryAdd(oS, info);
     }
     catch
     {
         oS.utilCreateResponseAndBypassServer();
         oS.responseCode = 500;
         oS.utilSetResponseBody("Exception occurred");
     }
 }
Esempio n. 21
0
        void sendResponse(Session oSession, int code, string content_type, byte[] data)
        {
            oSession.utilCreateResponseAndBypassServer();
            oSession.oResponse.headers.HTTPResponseCode = code;

            string status = Util.getStatus(code);

            oSession.oResponse.headers.HTTPResponseStatus = status;

            oSession.oResponse.headers["Content-Type"] = content_type;
            //oSession.oResponse.headers["Content-Length"] = data.Length.ToString();

            log(data.ToString());

            oSession.ResponseBody = data;
        }
Esempio n. 22
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;
        }
Esempio n. 23
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();
                byte[] file;
                using (var fs = File.Open(filepath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    file = new byte[fs.Length];
                    fs.Read(file, 0, (int)fs.Length);
                }
                oSession.ResponseBody = file;
                _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
            {
                //下载文件
            }
        }
Esempio n. 24
0
        private void PlaybackSession(Session oS, SessionInfo info)
        {
            try
            {
                string tapeId = info.UserId + "." + info.TapeId;
                Tape tape = _store.Select(tapeId);
                if (tape == null)
                {
                    oS.utilCreateResponseAndBypassServer();
                    oS.responseCode = 404;
                    oS.utilSetResponseBody("Tape not found");
                    return;
                }

                // time to find matching session
                Entry entry = HttpArchiveTranscoder.Export(oS, true);

                Entry matchedEntry = _store.MatchEntry(tapeId, entry);

                if (matchedEntry == null)
                {
                    oS.utilCreateResponseAndBypassServer();
                    oS.responseCode = 404;
                    oS.utilSetResponseBody("Matching entry not found");
                }
                else
                {
                    Session matchedSession = HttpArchiveTranscoder.Import(matchedEntry);
                    oS.utilCreateResponseAndBypassServer();
                    // #TODO: figger me out
                    // odd, fiddler is compressing respose when it is not compressed from server
                    //oS.responseBodyBytes = matchedSession.responseBodyBytes;

                    oS.utilSetResponseBody(matchedEntry.response.content.text);
                    oS.oResponse.headers = (HTTPResponseHeaders)matchedSession.oResponse.headers.Clone();

                    // #TODO: figger me out
                    oS.oResponse.headers["Content-Length"] = matchedEntry.response.content.text.Length.ToString();
                    // #TODO: figger me out
                    oS.oResponse.headers.Remove("Content-Encoding");
                }
            }
            catch
            {
                oS.utilCreateResponseAndBypassServer();
                oS.responseCode = 500;
                oS.utilSetResponseBody("Exception occurred");

                throw;
            }
        }