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); }
private void HandleFiddlerSessionComplete(Session session) { // Ignore HTTPS connect requests if (session.RequestMethod == "CONNECT") { return; } if (session.hostname.ToLower() != this.HostToSniff) { return; } string url = session.fullUrl.ToLower(); var extensions = new List<string> { ".ico", ".gif", ".jpg", ".png", ".axd", ".css" }; foreach (var ext in extensions) { if (url.Contains(ext)) { return; } } if (session == null || session.oRequest == null || session.oRequest.headers == null) { return; } string headers = session.oRequest.headers.ToString(); var reqBody = session.GetRequestBodyAsString(); Console.WriteLine(headers); if (!string.IsNullOrEmpty(reqBody)) { Console.WriteLine(string.Join(Environment.NewLine, reqBody.Split(new char[] {'&'}))); } Console.WriteLine(Environment.NewLine); // if you wanted to capture the response //string respHeaders = session.oResponse.headers.ToString(); //var respBody = session.GetResponseBodyAsString(); }
void FiddlerApplication_BeforeRequest(FiddlerSession rpSession) { var rStopwatch = Stopwatch.StartNew(); if (EnableUpstreamProxy) rpSession["x-OverrideGateway"] = UpstreamProxy; var rRequest = rpSession.oRequest; var rPath = rpSession.PathAndQuery; var rIsGame = rPath.StartsWith("/kcs"); var rIsResource = rPath.StartsWith("/kcs/") && !rPath.StartsWith("/kcs/mainD2.swf"); if (rPath.Contains("/kcs/mainD2.swf")) GameToken(rpSession.fullUrl); Session rSession; if (!rIsGame) rSession = new Session(rpSession.fullUrl); else if (rIsResource) { var rResourceSession = new ResourceSession(rpSession.fullUrl, rpSession.PathAndQuery.Substring(1)); rSession = rResourceSession; LoadFromCache(rpSession, rResourceSession); } else { var rUrl = rpSession.PathAndQuery; var rPosition = rUrl.IndexOf("/kcsapi/"); if (rPosition != -1) rUrl = rUrl.Substring(rPosition + 8); rSession = new ApiSession(rpSession.fullUrl, rUrl) { RequestBody = Uri.UnescapeDataString(rpSession.GetRequestBodyAsString()) }; } rpSession.Tag = rSession; rSession.Stopwatch = rStopwatch; if (rSession.Status != SessionStatus.LoadedFromCache) rSession.Status = SessionStatus.Request; NewSession(rSession); Debug.WriteLine("Request - " + rpSession.fullUrl); }
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()); } } }
private static async void ReportAsync(Session oSession) { if (!Config.Current.ReportToKancolleDB) return; foreach (var api in apinames) if (oSession.PathAndQuery.Contains(api)) { try { var request = HttpUtility.HtmlDecode(oSession.GetRequestBodyAsString()); request = regextoken.Replace(request, ""); var response = oSession.GetResponseBodyAsString().Replace("svdata=", ""); var wrq = WebRequest.CreateHttp("http://api.kancolle-db.net/2/"); wrq.Method = "POST"; wrq.ContentType = "application/x-www-form-urlencoded"; var data = "token=" + HttpUtility.UrlEncode(Config.Current.KancolleDBToken) + "&agent=LZXNXVGPejgSnEXLH2ur"//伪装为KCV + "&url=" + HttpUtility.UrlEncode(oSession.fullUrl) + "&requestbody=" + HttpUtility.UrlEncode(request) + "&responsebody=" + HttpUtility.UrlEncode(response); wrq.ContentLength = Encoding.UTF8.GetByteCount(data); using (var sw = new StreamWriter(await wrq.GetRequestStreamAsync())) { sw.Write(data); sw.Flush(); } using (var wrs = wrq.GetResponse() as HttpWebResponse) { System.Diagnostics.Debug.WriteLine(wrs.StatusCode); } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex); } } }
private void ProcessCSPReport(Session session) { string requestBody = session.GetRequestBodyAsString(); if (requestBody.Length > 0) { try { CSPReport cspReport = CSPReport.Parse(requestBody); if (cspReport.cspReport != null && cspReport.cspReport.documentUri != null) { logger.Log("Got report for " + cspReport.cspReport.documentUri + " via " + session.fullUrl); } logger.Log("Adding " + cspReport.ToString()); collector.Add(cspReport, session.PathAndQuery == "/unsafe-eval" ? CSPRuleCollector.InterpretBlank.UnsafeEval : CSPRuleCollector.InterpretBlank.UnsafeInline); logger.Log("Total " + collector.ToString()); } catch (Exception exception) { logger.Log("Invalid CSP - " + exception); } } }
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> /// 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); }
private static PostData GetPostData(Session oS) { var postData = new PostData(); string contentType = oS.oRequest["Content-Type"]; postData.mimeType = Utilities.TrimAfter(contentType, ';'); if (contentType.StartsWith("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase)) { postData.@params = GetQueryString("http://fake/path?" + oS.GetRequestBodyAsString()); return postData; } postData.text = oS.GetRequestBodyAsString(); return postData; }
private void FiddlerApplication_AfterSessionComplete(Session sess) { // Ignore HTTPS connect requests if (sess.RequestMethod == "CONNECT") return; if (CaptureConfiguration.ProcessId > 0) { if (sess.LocalProcessID != 0 && sess.LocalProcessID != CaptureConfiguration.ProcessId) return; } if (!string.IsNullOrEmpty(CaptureConfiguration.CaptureDomain)) { if (sess.hostname.ToLower() != CaptureConfiguration.CaptureDomain.Trim().ToLower()) return; } if (CaptureConfiguration.IgnoreResources) { string url = sess.fullUrl.ToLower(); var extensions = CaptureConfiguration.ExtensionFilterExclusions; foreach (var ext in extensions) { if (url.Contains(ext)) return; } var filters = CaptureConfiguration.UrlFilterExclusions; foreach (var urlFilter in filters) { if (url.Contains(urlFilter)) return; } } if (sess == null || sess.oRequest == null || sess.oRequest.headers == null) return; string headers = sess.oRequest.headers.ToString(); string contentType = sess.oRequest.headers.Where(hd => hd.Name.ToLower() == "content-type") .Select(hd => hd.Name) .FirstOrDefault(); string reqBody = null; if (sess.RequestBody.Length > 0) { if (sess.requestBodyBytes.Contains((byte)0) || contentType.StartsWith("image/")) reqBody = "b64_" + Convert.ToBase64String(sess.requestBodyBytes); else { //reqBody = Encoding.Default.GetString(sess.ResponseBody); reqBody = sess.GetRequestBodyAsString(); } } // if you wanted to capture the response //string respHeaders = session.oResponse.headers.ToString(); //var respBody = Encoding.UTF8.GetString(session.ResponseBody); // replace the HTTP line to inject full URL string firstLine = sess.RequestMethod + " " + sess.fullUrl + " " + sess.oRequest.headers.HTTPVersion; int at = headers.IndexOf("\r\n"); if (at < 0) return; headers = firstLine + "\r\n" + headers.Substring(at + 1); string output = headers + "\r\n" + (!string.IsNullOrEmpty(reqBody) ? reqBody + "\r\n" : string.Empty) + Separator + "\r\n\r\n"; // must marshal and synchronize to UI thread //BeginInvoke(new Action<string>((text) => //{ // try // { // txtCapture.AppendText(text); // } // catch (Exception e) // { // App.Log(e); // } // UpdateButtonStatus(); //}), output); }
/// <summary> /// Gets triggered before the request has been made /// </summary> /// <param name="objSession"></param> private void FiddlerApplication_BeforeRequest(Session objSession) { try { //Declarations Utility objUtility = new Utility(); DBUtility objDBUtility = new DBUtility(); //Declarations String strContentType = String.Empty; //Uncomment this if tampering of response is required //objSession.bBufferResponse = true; //Get the content type strContentType = objSession.oRequest.headers["Accept"]; //If its an HTML request or else the configuration has been set to capture all the requests if (strContentType.Contains("text/html") || _enConfiguration == Config.CaptureAll) { //Get the request headers HTTPRequestHeaders objRequestHeaders = objSession.oRequest.headers; //Construct the network data NetworkData objNetworkData = new NetworkData { ClientIP = objSession.clientIP, HostName = objSession.hostname, URLFullPath = objSession.fullUrl, IsHTTPS = objSession.isHTTPS, RequestedAt = objSession.Timers.ClientBeginRequest.ToString(), RequestType = objRequestHeaders.HTTPMethod }; //Get the request body String strRequestBody = objSession.GetRequestBodyAsString(); //If its a POST request if (objNetworkData.RequestType == "POST") //Get the request parameters objNetworkData.RequestParameters = objUtility.GetRequestParameters(strRequestBody); else if (objNetworkData.RequestType == "GET") { String [] arrQueryString = objNetworkData.URLFullPath.Split(new Char[] { '?' }); if(arrQueryString.Length > 1) objNetworkData.RequestParameters = objUtility.GetRequestParameters(arrQueryString[1]); } //Update the capture to Mongo DB if (_enConfiguration != Config.CaptureOnlyWithRequestParameters || objNetworkData.RequestParameters.Count > 0) objDBUtility.AddData("NetworkData", "NetworkData", objNetworkData); } } catch (Exception ex) { Utility.DisplayException("FiddlerApplication_BeforeRequest", ex); } }
/*设置返回值*/ public string setResponseBody(string response_ta_value, List<Para> paraValue_list, Session oSession, UserTabpage oPage) { string[] requestPar = null; oSession["ui-color"] = "brown"; if (oPage.getRequestType_cb().Text == "GET") { string url = oSession.url; requestPar = url.Split(new char[2] { '?', '&' }); } else if(oPage.getRequestType_cb().Text == "POST") { string url = oSession.GetRequestBodyAsString(); requestPar = url.Split(new char[1] { '&' }); } foreach (Para para in paraValue_list) { if (para.getParaTypeComboBox().Text == "读取") { foreach (string ii in requestPar) { if (ii.Contains(para.getParaName())) { para.setParaValue(ii.ToString().Substring(ii.ToString().IndexOf("=") + 1)); } } } } oPage.updatepPreview_response1(); if(oPage.getCheckBox2().Checked) { oPage.getResponseTextBoxValue().Text += "|" + oPage.getPreviewTextbox().Text; } /*将大括号中符合规定的值替换*/ Regex reg = new Regex(@"(?<={)[^{}]+(?=})"); MatchCollection mc = reg.Matches(response_ta_value); if (paraValue_list.Count == 0) { foreach (Match m in mc) { if (m.Value == "json") { response_ta_value = response_ta_value.Replace("{" + m.Value + "}", this.jsonTOurlencode(oPage.getPreviewTextbox().Text)); } else if (m.Value == "sign") { response_ta_value = response_ta_value.Replace("{" + m.Value + "}", this.Sign(oPage.getSignValue_text().Text, paraValue_list, oPage)); } } } else { foreach (Match m in mc) { foreach(Para para in paraValue_list) { if(m.Value == para.getParaName()) { if (para.getParaTypeComboBox().Text == "MD5") { response_ta_value = response_ta_value.Replace("{" + m.Value + "}", this.Sign(para.getParaValue(), paraValue_list, oPage)); } else { response_ta_value = response_ta_value.Replace("{" + m.Value + "}", para.getParaValue()); } } else if(m.Value == "json") { response_ta_value = response_ta_value.Replace("{" + m.Value + "}", this.jsonTOurlencode(oPage.getPreviewTextbox().Text)); } else if(m.Value == "sign") { response_ta_value = response_ta_value.Replace("{" + m.Value + "}", this.Sign(oPage.getSignValue_text().Text, paraValue_list, oPage)); } } } } return response_ta_value; }
/// <summary> /// Gets triggered before the request has been made /// </summary> /// <param name="objSession"></param> private void FiddlerApplication_BeforeRequest(Session objSession) { try { CreateCertificateIfRequired(); //Declarations String strContentType = String.Empty; String strRequestedParameters = String.Empty; //Get the flag whether its an allowable URL Website website = _snifferConfigHandler.GetWebsite(objSession.fullUrl); //Check whether a matching website was found _IsAllowedURL = website != null; //Sniff out only if this URL was in the list of websites if (_IsAllowedURL) { //Get the content type strContentType = objSession.oRequest.headers["Accept"]; //If its not a capture onl only HTML requests or it has to be HTML only content //Get the request headers HTTPRequestHeaders objRequestHeaders = objSession.oRequest.headers; //Construct the network data NetworkData objNetworkData = new NetworkData { URLFullPath = objSession.fullUrl, IsHTTPS = objSession.isHTTPS, SentOn = objSession.Timers.ClientBeginRequest.ToString(), Site = website }; //Get the request body String strRequestBody = objSession.GetRequestBodyAsString(); //If its a POST request if (objRequestHeaders.HTTPMethod == "POST") //Get the request parameters strRequestedParameters = strRequestBody; else if (objRequestHeaders.HTTPMethod == "GET") { String[] arrQueryString = objNetworkData.URLFullPath.Split(new Char[] { '?' }); if (arrQueryString.Length > 1) strRequestedParameters = arrQueryString[1]; } //TO DO: Capture only if the content has any PII data if (objNetworkData.ContainsPII(_snifferConfigHandler.Person, strRequestedParameters)) //Update the capture to Mongo DB _DBUtility.AddData(objNetworkData); } else { //Uncomment this if tampering of response is required //objSession.bBufferResponse = true; //objSession.Abort(); } } catch (ThreadAbortException ex) { ShutDown(); } catch (Exception ex) { Utility.Logger.Log("FiddlerApplication_BeforeRequest: " + ex.Message); ShutDown(); } }
private string PostServer(Session oSession) { string token = textBox2.Text; // TODO: ユーザー毎のトークンを設定 string agent = ""; // TODO: アプリ毎のトークンを設定 string url = oSession.fullUrl; string requestBody = HttpUtility.HtmlDecode(oSession.GetRequestBodyAsString()); requestBody = Regex.Replace(requestBody, @"&api(_|%5F)token=[0-9a-f]+|api(_|%5F)token=[0-9a-f]+&?", ""); // api_tokenを送信しないように削除 string responseBody = oSession.GetResponseBodyAsString(); responseBody.Replace("svdata=", ""); try { WebRequest req = WebRequest.Create("http://api.kancolle-db.net/2/"); req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; System.Text.Encoding enc = System.Text.Encoding.GetEncoding("utf-8"); string postdata = "token=" + HttpUtility.UrlEncode(token) + "&" + "agent=" + HttpUtility.UrlEncode(agent) + "&" + "url=" + HttpUtility.UrlEncode(url) + "&" + "requestbody=" + HttpUtility.UrlEncode(requestBody) + "&" + "responsebody=" + HttpUtility.UrlEncode(responseBody); byte[] postDataBytes = System.Text.Encoding.ASCII.GetBytes(postdata); req.ContentLength = postDataBytes.Length; Stream reqStream = req.GetRequestStream(); reqStream.Write(postDataBytes, 0, postDataBytes.Length); reqStream.Close(); WebResponse res = req.GetResponse(); HttpWebResponse httpRes = (HttpWebResponse)res; Stream resStream = res.GetResponseStream(); StreamReader sr = new StreamReader(resStream, enc); string response = sr.ReadToEnd(); sr.Close(); return oSession.responseCode + ": " + response; } catch (WebException ex) { if (ex.Status == WebExceptionStatus.ProtocolError) { HttpWebResponse error = (HttpWebResponse)ex.Response; return error.ResponseUri + " " + oSession.responseCode + ": " + error.StatusDescription; } return ex.Message; } }
private static Hashtable getPostData(Session oS) { Hashtable hashtable = new Hashtable(); string sString = oS.oRequest["Content-Type"]; hashtable.Add("mimeType", Utilities.TrimAfter(sString, ';')); if (sString.StartsWith("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase)) { hashtable.Add("params", getQueryString("http://fake/path?" + oS.GetRequestBodyAsString())); return hashtable; } hashtable.Add("text", oS.GetRequestBodyAsString()); return hashtable; }
private void FiddlerApplication_AfterSessionComplete(Session sess) { // Ignore HTTPS connect requests if (sess.RequestMethod == "CONNECT") return; //if (CaptureConfiguration.ProcessId > 0) //{ // if (sess.LocalProcessID != 0 && sess.LocalProcessID != CaptureConfiguration.ProcessId) // return; //} //if (!string.IsNullOrEmpty(CaptureConfiguration.CaptureDomain)) //{ // if (sess.hostname.ToLower() != CaptureConfiguration.CaptureDomain.Trim().ToLower()) // return; //} //if (sess.hostname.ToLower() != "bet365" && sess.hostname.ToLower() != "www.bet365.com") //{ // return; //} //if (CaptureConfiguration.IgnoreResources) //{ // string url = sess.fullUrl.ToLower(); // var extensions = CaptureConfiguration.ExtensionFilterExclusions; // foreach (var ext in extensions) // { // if (url.Contains(ext)) // return; // } // var filters = CaptureConfiguration.UrlFilterExclusions; // foreach (var urlFilter in filters) // { // if (url.Contains(urlFilter)) // return; // } //} if (sess == null || sess.oRequest == null || sess.oRequest.headers == null) return; string headers = sess.oRequest.headers.ToString(); var reqBody = sess.GetRequestBodyAsString(); // if you wanted to capture the response string respHeaders = sess.oResponse.headers.ToString(); var respBody = sess.GetResponseBodyAsString(); // replace the HTTP line to inject full URL //string firstLine = sess.RequestMethod + " " + sess.fullUrl + " " + sess.oRequest.headers.HTTPVersion; //int at = headers.IndexOf("\r\n"); //if (at < 0) // return; //headers = firstLine + "\r\n" + headers.Substring(at + 1); //string output = headers + "\r\n" + // (!string.IsNullOrEmpty(reqBody) ? reqBody + "\r\n" : string.Empty) + // Separator + "\r\n\r\n"; var output = string.Format("Headers: {0}; /n Body: {1}; /n RHeaders: {2}; /n RBody: {3}",headers, reqBody, respHeaders, respBody); //BeginInvoke(new Action<string>((text) => //{ // txtCapture.AppendText(text); // UpdateButtonStatus(); //}), output); Console.WriteLine(output); }
private void PostToServer( Session oSession ) { string oauth = OAuth; string url = oSession.fullUrl; string request = oSession.GetRequestBodyAsString(); string response = oSession.GetResponseBodyAsString(); request = RequestRegex.Replace( request, "" ); try { //* using ( System.Net.WebClient wc = new System.Net.WebClient() ) { wc.Headers["User-Agent"] = "ElectronicObserver/v" + SoftwareInformation.VersionEnglish; if ( Proxy != null ) { wc.Proxy = Proxy; } System.Collections.Specialized.NameValueCollection post = new System.Collections.Specialized.NameValueCollection(); post.Add( "token", oauth ); // agent key for 'ElectronicObserver' // https://github.com/about518/kanColleDbPost/issues/3#issuecomment-105534030 post.Add( "agent", "L57Mi4hJeCYinbbBSH5K" ); post.Add( "url", url ); post.Add( "requestbody", request ); post.Add( "responsebody", response ); wc.UploadValuesCompleted += ( sender, e ) => { if ( e.Error != null ) { // 結構頻繁に出るのでレポートは残さない方針で 申し訳ないです //Utility.ErrorReporter.SendErrorReport( e.Error, string.Format( "艦これ統計データベースへの {0} の送信に失敗しました。", url.Substring( url.IndexOf( "/api" ) + 1 ) ) ); Utility.Logger.Add( 1, string.Format( "艦これ統計データベースへの {0} の送信に失敗しました。{1}", url.Substring( url.IndexOf( "/api" ) + 1 ), e.Error.Message ) ); } else { Utility.Logger.Add( 1, string.Format( "艦これ統計データベースへ {0} を送信しました。", url.Substring( url.IndexOf( "/api" ) + 1 ) ) ); } }; wc.UploadValuesAsync( new Uri( "http://api.kancolle-db.net/2/" ), post ); } //*/ } catch ( Exception ex ) { Utility.ErrorReporter.SendErrorReport( ex, "艦これ統計データベースへの送信中にエラーが発生しました。" ); } }
public void FilterAndRecord(Session oSession) { Debug.Log("oSession.host.ToLower: " + oSession.host.ToLower() + ", Global.sRosinDomain:" + Global.sRosinDomain); Debug.Log("oSession.fullUrl:" + oSession.fullUrl); Debug.Log("rosin target url:" + ("http://" + oSession.host + "/?__rosin__")); // 支持https的请求 // 由于https的请求需要服务器的配合,单凭fiddler没办法模拟,所以这里使用一个到页面所在https的请求,带上标识,拦截掉 if (oSession.host.ToLower() == Global.sRosinDomain || oSession.fullUrl == ("https://" + oSession.host + "/?__rosin__")) { string sRequestBodyString = oSession.GetRequestBodyAsString(); if(sRequestBodyString != "") { List<LogItem> logList = JsonConvert.DeserializeObject<List<LogItem>>(sRequestBodyString); if (logList.Count > 0) { bool isNew = false; string sFileName = logList[0].key + ".txt"; string sFileDir = FiddlerPath.RosinLogDir + @"\" + sFileName; string sContent = ""; if (!File.Exists(sFileDir)) { isNew = true; } if (isNew) { sContent += "Page URL: " + oSession.oRequest.headers["Referer"] + "\r\n"; sContent += "Create Date: " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\r\n"; sContent += "\r\n"; } foreach (LogItem item in logList) { sContent += "[" + TimeFormat.GetTime(item.time).ToString("yyyy-MM-dd HH:mm:ss") + "] [" + item.level + "]" + item.content.ToString() + "\r\n"; } FileStreamManager.Instance().Write(logList[0].key, sFileDir, sContent); // 先写日志,在去记录,避免出现读数据空的情况 if (isNew) { this.RecordPageUrl(logList[0].key, oSession); } // dispatch event RosinWrite(this, new EventArgs()); } } //if (oSession.port == 443) //{ // oSession["x-replywithfile"] = "rosinhttps.dat"; //} //else //{ oSession["x-replywithfile"] = "rosinpost.dat"; //} oSession["ui-hide"] = "true"; // 这个接口在低版本没有,会报错 // Fiddler Web Debugger (v2.4.5.0) Built: 2013年8月15日 // oSession.Ignore(); // 忽略该次请求,fiddler中将看不到这个请求,但是实际上该次请求还是发出去了,所以要自己模拟一个响应 return; } }