private static void WriteFile(string sFilename, HTTPHeaders oH, byte[] arrData)
 {
     FileStream fileStream = new FileStream(sFilename, FileMode.Create, FileAccess.Write);
     if (oH != null)
     {
         HTTPRequestHeaders hTTPRequestHeader = oH as HTTPRequestHeaders;
         if (hTTPRequestHeader == null)
         {
             HTTPResponseHeaders hTTPResponseHeader = oH as HTTPResponseHeaders;
             if (hTTPResponseHeader != null)
             {
                 byte[] byteArray = hTTPResponseHeader.ToByteArray(true, true);
                 fileStream.Write(byteArray, 0, (int)byteArray.Length);
             }
         }
         else
         {
             byte[] numArray = hTTPRequestHeader.ToByteArray(true, true, true);
             fileStream.Write(numArray, 0, (int)numArray.Length);
         }
     }
     if (arrData != null)
     {
         fileStream.Write(arrData, 0, (int)arrData.Length);
     }
     fileStream.Close();
 }
Exemple #2
0
 private static int _GetEntityLengthFromHeaders(HTTPHeaders oHeaders, MemoryStream strmData)
 {
     if (oHeaders.ExistsAndEquals("Transfer-encoding", "chunked"))
     {
         long num;
         long num2;
         if (Utilities.IsChunkedBodyComplete(null, strmData, strmData.Position, out num, out num2))
         {
             return((int)(num2 - strmData.Position));
         }
         return((int)(strmData.Length - strmData.Position));
     }
     else
     {
         string text = oHeaders["Content-Length"];
         if (!string.IsNullOrEmpty(text))
         {
             long num3 = 0L;
             if (long.TryParse(text, NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out num3) && num3 >= 0L)
             {
                 return((int)num3);
             }
             return((int)(strmData.Length - strmData.Position));
         }
         else
         {
             if (oHeaders.ExistsAndContains("Connection", "close"))
             {
                 return((int)(strmData.Length - strmData.Position));
             }
             return(0);
         }
     }
 }
Exemple #3
0
        internal static bool ParseNVPHeaders(HTTPHeaders oHeaders, string[] sHeaderLines, int iStartAt, ref string sErrors)
        {
            bool result = true;
            int  i      = iStartAt;

            while (i < sHeaderLines.Length)
            {
                int            num = sHeaderLines[i].IndexOf(':');
                HTTPHeaderItem hTTPHeaderItem;
                if (num > 0)
                {
                    hTTPHeaderItem = oHeaders.Add(sHeaderLines[i].Substring(0, num), sHeaderLines[i].Substring(num + 1).TrimStart(new char[]
                    {
                        ' ',
                        '\t'
                    }));
                }
                else
                {
                    if (num == 0)
                    {
                        hTTPHeaderItem = null;
                        sErrors       += string.Format("Missing Header name #{0}, {1}\n", 1 + i - iStartAt, sHeaderLines[i]);
                        result         = false;
                    }
                    else
                    {
                        hTTPHeaderItem = oHeaders.Add(sHeaderLines[i], string.Empty);
                        sErrors       += string.Format("Missing colon in header #{0}, {1}\n", 1 + i - iStartAt, sHeaderLines[i]);
                        result         = false;
                    }
                }
                i++;
                bool flag = hTTPHeaderItem != null && i < sHeaderLines.Length && Parser.IsPrefixedWithWhitespace(sHeaderLines[i]);
                while (flag)
                {
                    FiddlerApplication.Log.LogString("[HTTPWarning] Header folding detected. Not all clients properly handle folded headers.");
                    hTTPHeaderItem.Value = hTTPHeaderItem.Value + " " + sHeaderLines[i].TrimStart(new char[]
                    {
                        ' ',
                        '\t'
                    });
                    i++;
                    flag = (i < sHeaderLines.Length && Parser.IsPrefixedWithWhitespace(sHeaderLines[i]));
                }
            }
            return(result);
        }
 internal static void OpenTextEditor(string sFilename, HTTPHeaders oH, byte[] arrData)
 {
     try
     {
         string path = CONFIG.GetPath("TextEditor");
         InspectorUtils.WriteFile(sFilename, oH, arrData);
         Process process = Process.Start(path, string.Concat((char)34, sFilename, (char)34));
         using (process)
         {
         }
     }
     catch (Exception exception1)
     {
         Exception exception = exception1;
         MessageBox.Show(string.Concat(exception.Message, "\n", sFilename), "TextEditor Failed");
     }
 }
Exemple #5
0
        internal static HttpHeaders GenerateHeaders(this Fiddler.HTTPHeaders httpHeaders)
        {
            var headers = new HttpHeaders();

            StringBuilder sb = new StringBuilder();

            foreach (HTTPHeaderItem pair in httpHeaders)
            {
                if (pair.Name.Equals("connection") ||
                    pair.Name.Equals("content-encoding") ||
                    pair.Name.Equals("proxy-connection") ||
                    pair.Name.Equals("transfer-encoding"))
                {
                    headers.Headers[pair.Name.ToLower()] = pair.Value.ToLower();
                }
                else
                {
                    headers.Headers[pair.Name.ToLower()] = pair.Value;
                }
                sb.Append(pair.Name + ": " + pair.Value + "\r\n");
            }

            typeof(HttpHeaders).GetProperty("HeadersInOrder").SetValue(headers, sb.ToString());

            headers.Connection      = headers.Headers.ContainsKey("connection") ? new string[] { headers.Headers["connection"] } : null;
            headers.ContentEncoding = headers.Headers.ContainsKey("content-encoding") ? headers.Headers["content-encoding"] : null;
            uint length;

            if (headers.Headers.ContainsKey("content-length") && uint.TryParse(headers.Headers["content-length"], out length))
            {
                headers.ContentLength = length;
            }
            else
            {
                headers.ContentLength = null;
            }
            headers.Host             = headers.Headers.ContainsKey("host") ? headers.Headers["host"] : null;
            headers.ProxyConnection  = headers.Headers.ContainsKey("proxy-connection") ? new string[] { headers.Headers["proxy-connection"] } : null;
            headers.Referer          = headers.Headers.ContainsKey("referer") ? headers.Headers["referer"] : null;
            headers.TransferEncoding = headers.Headers.ContainsKey("transfer-encoding") ? new string[] { headers.Headers["transfer-encoding"] } : null;

            return(headers);
        }
Exemple #6
0
        internal static bool ParseNVPHeaders(HTTPHeaders oHeaders, string[] sHeaderLines, int iStartAt, ref string sErrors)
        {
            bool flag = true;

            for (int i = iStartAt; i < sHeaderLines.Length; i++)
            {
                int index = sHeaderLines[i].IndexOf(':');
                if (index > 0)
                {
                    oHeaders.Add(sHeaderLines[i].Substring(0, index), sHeaderLines[i].Substring(index + 1).Trim());
                }
                else
                {
                    sErrors = sErrors + string.Format("Missing colon in header #{0}, {1}\n", i - iStartAt, sHeaderLines[i]);
                    flag    = false;
                }
            }
            return(flag);
        }
        public static byte[] DecodeContent(byte[] body, Fiddler.HTTPHeaders headers)
        {
            if (headers.Exists("Content-Encoding"))
            {
                List <HTTPHeaderItem> headerItems = headers.FindAll("Content-Encoding");
                string encoding = null;
                if (headerItems != null)
                {
                    for (int idx = 0; idx < headerItems.Count; idx++)
                    {
                        encoding = headerItems[idx].Value;
                    }
                }

                if (encoding == null)
                {
                    encoding = "";
                }

                if (encoding.Equals("gzip"))
                {
                    body = Fiddler.Utilities.GzipExpand(body);
                }
                else if (encoding.Equals("deflate"))
                {
                    body = Fiddler.Utilities.DeflaterExpand(body);
                }
                else if (encoding.Equals("br"))
                {
                    body = Fiddler.Utilities.BrotliExpand(body);
                }
                else if (encoding.Equals("identity"))
                {
                    // body = session.ResponseBody;
                }
            }

            return(body);
        }
        /// <summary>
        /// Parse the HTTP payload to MAPI message.
        /// </summary>
        /// <param name="headers">The HTTP header.</param>
        /// <param name="currentSessionID">the current session ID.</param>
        /// <param name="bytesFromHTTP">The raw data from HTTP layer.</param>
        /// <param name="direction">The direction of the traffic.</param>
        /// <param name="bytes">The bytes provided for MAPI view layer.</param>
        /// <returns>The object parsed result</returns>
        public object ParseHTTPPayload(HTTPHeaders headers, int currentSessionID, byte[] bytesFromHTTP, TrafficDirection direction, out byte[] bytes)
        {
            object objectOut = null;
            byte[] emptyByte = new byte[0];
            bytes = emptyByte;

            if (bytesFromHTTP == null || bytesFromHTTP.Length == 0 || headers == null || !headers.Exists("X-RequestType"))
            {
                return null;
            }

            string requestType = headers["X-RequestType"];

            if (requestType == null)
            {
                return null;
            }
            try
            {
                if (direction == TrafficDirection.Out && headers.Exists("Transfer-Encoding") && headers["Transfer-Encoding"] == "chunked")
                {
                    bytesFromHTTP = Utilities.GetPaylodFromChunkedBody(bytesFromHTTP);
                    bytes = bytesFromHTTP;
                }
                else
                {
                    bytes = bytesFromHTTP;
                }

                Stream stream = new MemoryStream(bytesFromHTTP);
                MAPIInspector.currentSelectedSessionID = this.session.id;
                MAPIInspector.currentParsingSessionID = currentSessionID;
                if (direction == TrafficDirection.In)
                {
                    switch (requestType)
                    {
                        case "Connect":
                            {
                                ConnectRequestBody ConnectRequest = new ConnectRequestBody();
                                ConnectRequest.Parse(stream);
                                objectOut = ConnectRequest;
                                break;
                            }
                        case "Execute":
                            {
                                ExecuteRequestBody ExecuteRequest = new ExecuteRequestBody();
                                ExecuteRequest.Parse(stream);
                                objectOut = ExecuteRequest;
                                break;
                            }
                        case "Disconnect":
                            {
                                DisconnectRequestBody DisconnectRequest = new DisconnectRequestBody();
                                DisconnectRequest.Parse(stream);
                                objectOut = DisconnectRequest;
                                break;
                            }
                        case "NotificationWait":
                            {
                                NotificationWaitRequestBody NotificationWaitRequest = new NotificationWaitRequestBody();
                                NotificationWaitRequest.Parse(stream);
                                objectOut = NotificationWaitRequest;
                                break;
                            }
                        case "Bind":
                            {
                                BindRequest bindRequest = new BindRequest();
                                bindRequest.Parse(stream);
                                objectOut = bindRequest;
                                break;
                            }
                        case "Unbind":
                            {
                                UnbindRequest unbindRequest = new UnbindRequest();
                                unbindRequest.Parse(stream);
                                objectOut = unbindRequest;
                                break;
                            }
                        case "CompareMIds":
                            {
                                CompareMinIdsRequest compareMinIdsRequest = new CompareMinIdsRequest();
                                compareMinIdsRequest.Parse(stream);
                                objectOut = compareMinIdsRequest;
                                break;
                            }
                        case "DNToMId":
                            {
                                DnToMinIdRequest dnToMinIdRequest = new DnToMinIdRequest();
                                dnToMinIdRequest.Parse(stream);
                                objectOut = dnToMinIdRequest;
                                break;
                            }
                        case "GetMatches":
                            {
                                GetMatchesRequest getMatchesRequest = new GetMatchesRequest();
                                getMatchesRequest.Parse(stream);
                                objectOut = getMatchesRequest;
                                break;
                            }
                        case "GetPropList":
                            {
                                GetPropListRequest getPropListRequest = new GetPropListRequest();
                                getPropListRequest.Parse(stream);
                                objectOut = getPropListRequest;
                                break;
                            }
                        case "GetProps":
                            {
                                GetPropsRequest getPropsRequest = new GetPropsRequest();
                                getPropsRequest.Parse(stream);
                                objectOut = getPropsRequest;
                                break;
                            }
                        case "GetSpecialTable":
                            {
                                GetSpecialTableRequest getSpecialTableRequest = new GetSpecialTableRequest();
                                getSpecialTableRequest.Parse(stream);
                                objectOut = getSpecialTableRequest;
                                break;
                            }
                        case "GetTemplateInfo":
                            {
                                GetTemplateInfoRequest getTemplateInfoRequest = new GetTemplateInfoRequest();
                                getTemplateInfoRequest.Parse(stream);
                                objectOut = getTemplateInfoRequest;
                                break;
                            }
                        case "ModLinkAtt":
                            {
                                ModLinkAttRequest modLinkAttRequest = new ModLinkAttRequest();
                                modLinkAttRequest.Parse(stream);
                                objectOut = modLinkAttRequest;
                                break;
                            }
                        case "ModProps":
                            {
                                ModPropsRequest modPropsRequest = new ModPropsRequest();
                                modPropsRequest.Parse(stream);
                                objectOut = modPropsRequest;
                                break;
                            }
                        case "QueryRows":
                            {
                                QueryRowsRequest queryRowsRequest = new QueryRowsRequest();
                                queryRowsRequest.Parse(stream);
                                objectOut = queryRowsRequest;
                                break;
                            }
                        case "QueryColumns":
                            {
                                QueryColumnsRequest queryColumnsRequest = new QueryColumnsRequest();
                                queryColumnsRequest.Parse(stream);
                                objectOut = queryColumnsRequest;
                                break;
                            }
                        case "ResolveNames":
                            {
                                ResolveNamesRequest resolveNamesRequest = new ResolveNamesRequest();
                                resolveNamesRequest.Parse(stream);
                                objectOut = resolveNamesRequest;
                                break;
                            }
                        case "ResortRestriction":
                            {
                                ResortRestrictionRequest resortRestrictionRequest = new ResortRestrictionRequest();
                                resortRestrictionRequest.Parse(stream);
                                objectOut = resortRestrictionRequest;
                                break;
                            }
                        case "SeekEntries":
                            {
                                SeekEntriesRequest seekEntriesRequest = new SeekEntriesRequest();
                                seekEntriesRequest.Parse(stream);
                                objectOut = seekEntriesRequest;
                                break;
                            }
                        case "UpdateStat":
                            {
                                UpdateStatRequest updateStatRequest = new UpdateStatRequest();
                                updateStatRequest.Parse(stream);
                                objectOut = updateStatRequest;
                                break;
                            }
                        case "GetMailboxUrl":
                            {
                                GetMailboxUrlRequest getMailboxUrlRequest = new GetMailboxUrlRequest();
                                getMailboxUrlRequest.Parse(stream);
                                objectOut = getMailboxUrlRequest;
                                break;
                            }
                        case "GetAddressBookUrl":
                            {
                                GetAddressBookUrlRequest getAddressBookUrlRequest = new GetAddressBookUrlRequest();
                                getAddressBookUrlRequest.Parse(stream);
                                objectOut = getAddressBookUrlRequest;
                                break;
                            }
                        default:
                            {
                                objectOut = "Unavailable Response Type";
                                break;
                            }
                    }
                }
                else
                {
                    switch (requestType)
                    {
                        case "Connect":
                            {
                                ConnectResponseBody ConnectResponse = new ConnectResponseBody();
                                ConnectResponse.Parse(stream);
                                objectOut = ConnectResponse;
                                break;
                            }
                        case "Execute":
                            {
                                ExecuteResponseBody ExecuteResponse = new ExecuteResponseBody();
                                ExecuteResponse.Parse(stream);
                                objectOut = ExecuteResponse;
                                break;
                            }
                        case "Disconnect":
                            {

                                DisconnectResponseBody DisconnectResponse = new DisconnectResponseBody();
                                DisconnectResponse.Parse(stream);
                                objectOut = DisconnectResponse;
                                break;
                            }
                        case "NotificationWait":
                            {

                                NotificationWaitResponseBody NotificationWaitResponse = new NotificationWaitResponseBody();
                                NotificationWaitResponse.Parse(stream);
                                objectOut = NotificationWaitResponse;
                                break;
                            }
                        case "Bind":
                            {
                                BindResponse bindResponse = new BindResponse();
                                bindResponse.Parse(stream);
                                objectOut = bindResponse;
                                break;
                            }
                        case "Unbind":
                            {
                                UnbindResponse unbindResponse = new UnbindResponse();
                                unbindResponse.Parse(stream);
                                objectOut = unbindResponse;
                                break;
                            }
                        case "CompareMIds":
                            {
                                CompareMinIdsResponse compareMinIdsResponse = new CompareMinIdsResponse();
                                compareMinIdsResponse.Parse(stream);
                                objectOut = compareMinIdsResponse;
                                break;
                            }
                        case "DNToMId":
                            {
                                DnToMinIdResponse dnToMinIdResponse = new DnToMinIdResponse();
                                dnToMinIdResponse.Parse(stream);
                                objectOut = dnToMinIdResponse;
                                break;
                            }
                        case "GetMatches":
                            {
                                GetMatchesResponse getMatchesResponse = new GetMatchesResponse();
                                getMatchesResponse.Parse(stream);
                                objectOut = getMatchesResponse;
                                break;
                            }
                        case "GetPropList":
                            {
                                GetPropListResponse getPropListResponse = new GetPropListResponse();
                                getPropListResponse.Parse(stream);
                                objectOut = getPropListResponse;
                                break;
                            }
                        case "GetProps":
                            {
                                GetPropsResponse getPropsResponse = new GetPropsResponse();
                                getPropsResponse.Parse(stream);
                                objectOut = getPropsResponse;
                                break;
                            }
                        case "GetSpecialTable":
                            {
                                GetSpecialTableResponse getSpecialTableResponse = new GetSpecialTableResponse();
                                getSpecialTableResponse.Parse(stream);
                                objectOut = getSpecialTableResponse;
                                break;
                            }
                        case "GetTemplateInfo":
                            {
                                GetTemplateInfoResponse getTemplateInfoResponse = new GetTemplateInfoResponse();
                                getTemplateInfoResponse.Parse(stream);
                                objectOut = getTemplateInfoResponse;
                                break;
                            }
                        case "ModLinkAtt":
                            {
                                ModLinkAttResponse modLinkAttResponse = new ModLinkAttResponse();
                                modLinkAttResponse.Parse(stream);
                                objectOut = modLinkAttResponse;
                                break;
                            }
                        case "ModProps":
                            {
                                ModPropsResponse modPropsResponse = new ModPropsResponse();
                                modPropsResponse.Parse(stream);
                                objectOut = modPropsResponse;
                                break;
                            }
                        case "QueryRows":
                            {
                                QueryRowsResponse queryRowsResponse = new QueryRowsResponse();
                                queryRowsResponse.Parse(stream);
                                objectOut = queryRowsResponse;
                                break;
                            }
                        case "QueryColumns":
                            {
                                QueryColumnsResponse queryColumnsResponse = new QueryColumnsResponse();
                                queryColumnsResponse.Parse(stream);
                                objectOut = queryColumnsResponse;
                                break;
                            }
                        case "ResolveNames":
                            {
                                ResolveNamesResponse resolveNamesResponse = new ResolveNamesResponse();
                                resolveNamesResponse.Parse(stream);
                                objectOut = resolveNamesResponse;
                                break;
                            }
                        case "ResortRestriction":
                            {
                                ResortRestrictionResponse resortRestrictionResponse = new ResortRestrictionResponse();
                                resortRestrictionResponse.Parse(stream);
                                objectOut = resortRestrictionResponse;
                                break;
                            }
                        case "SeekEntries":
                            {
                                SeekEntriesResponse seekEntriesResponse = new SeekEntriesResponse();
                                seekEntriesResponse.Parse(stream);
                                objectOut = seekEntriesResponse;
                                break;
                            }
                        case "UpdateStat":
                            {
                                UpdateStatResponse updateStatResponse = new UpdateStatResponse();
                                updateStatResponse.Parse(stream);
                                objectOut = updateStatResponse;
                                break;
                            }
                        case "GetMailboxUrl":
                            {
                                GetMailboxUrlResponse getMailboxUrlResponse = new GetMailboxUrlResponse();
                                getMailboxUrlResponse.Parse(stream);
                                objectOut = getMailboxUrlResponse;
                                break;
                            }
                        case "GetAddressBookUrl":
                            {
                                GetAddressBookUrlResponse getAddressBookUrlResponse = new GetAddressBookUrlResponse();
                                getAddressBookUrlResponse.Parse(stream);
                                objectOut = getAddressBookUrlResponse;
                                break;
                            }
                        default:
                            {
                                objectOut = "Unavailable Response Type";
                                break;
                            }
                    }
                }
                return objectOut;
            }
            catch (MissingInformationException mException)
            {
                DialogResult confirmResult = MessageBox.Show("Do you want to spend more time to parse the related message?", "Confirmation", MessageBoxButtons.YesNo);
                if (confirmResult == DialogResult.Yes)
                {
                    DecodingContext.LogonFlagMapLogId = new Dictionary<byte, LogonFlags>();
                    DecodingContext.SetColumnProTagMap_Index = new Dictionary<uint, PropertyTag[]>();
                    DecodingContext.DestinationConfigure_OutputHandles = new List<uint>();
                    DecodingContext.PutBuffer_sourceOperation = new Dictionary<uint, SourceOperation>();
                    HandleContextInformation(mException.RopID, out objectOut, out bytes, mException.Parameters);

                    return objectOut;
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                objectOut = ex.ToString();
                return objectOut;
            }
        }
        private static List<NameValuePair> GetHeaders(HTTPHeaders headers)
        {
            var list = new List<NameValuePair>();

            foreach (HTTPHeaderItem item in headers)
            {
                list.Add(new NameValuePair
                             {
                                 name = item.Name,
                                 value = item.Value
                             });
            }
            return list;
        }
        private static List<Cookie> GetCookies(HTTPHeaders oHeaders)
        {
            var cookies = new List<Cookie>();

            if (oHeaders is HTTPRequestHeaders)
            {
                string cookiesString = oHeaders["Cookie"];
                if (!string.IsNullOrEmpty(cookiesString))
                {
                    cookies.AddRange(
                        from cookieString in cookiesString.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
                        select cookieString.Trim()
                        into trimmedCookieString
                        where trimmedCookieString.Length >= 1
                        select new Cookie
                                   {
                                       name = Utilities.TrimAfter(trimmedCookieString, '='),
                                       value = Utilities.TrimBefore(trimmedCookieString, '=')

                                       // #TODO - fully parse cookie string
                                       //,
                                       //comment = "",
                                       //domain = "",
                                       //expires = "",
                                       //httpOnly = false,
                                       //path = "",
                                       //secure = false
                                   });
                }
            }
            return cookies;
        }
Exemple #11
0
        /// <summary>
        /// Parse the HTTP payload to MAPI message.
        /// </summary>
        /// <param name="headers">The HTTP header.</param>
        /// <param name="bytesFromHTTP">The raw data from HTTP layer.</param>
        /// <param name="direction">The direction of the traffic.</param>
        public void ParseHTTPPayload(HTTPHeaders headers, byte[] bytesFromHTTP, TrafficDirection direction)
        {
            if (bytesFromHTTP.Length == 0 || headers == null || !headers.Exists("X-RequestType"))
            {
                return;
            }

            string requestType = headers["X-RequestType"];

            if (requestType == null)
            {
                return;
            }
            try
            {
                if (direction == TrafficDirection.Out && headers.Exists("Transfer-Encoding") && headers["Transfer-Encoding"] == "chunked")
                {
                    bytesFromHTTP = Utilities.GetPaylodFromChunkedBody(bytesFromHTTP);
                    this.oMAPIControl.MAPIHexBox.ByteProvider = new StaticByteProvider(bytesFromHTTP);
                }
                else
                {
                    this.oMAPIControl.MAPIHexBox.ByteProvider = new StaticByteProvider(bytesFromHTTP);
                }

                this.oMAPIControl.MAPIHexBox.ByteProvider.ApplyChanges();
                Stream stream = new MemoryStream(bytesFromHTTP);
                int result = 0;
                if (direction == TrafficDirection.In)
                {
                    this.oMAPIViewControl.BeginUpdate();
                    TreeNode topNode = new TreeNode(requestType + "Request:");

                switch (requestType)
                {
                    case "Connect":
                        {
                            ConnectRequestBody ConnectRequest = new ConnectRequestBody();
                            ConnectRequest.Parse(stream);
                            topNode = ConnectRequest.AddNodesForTree(ConnectRequest, 0, out result);
                            break;
                        }
                    case "Execute":
                        {
                            ExecuteRequestBody ExecuteRequest = new ExecuteRequestBody();
                            ExecuteRequest.Parse(stream);
                            topNode = ExecuteRequest.AddNodesForTree(ExecuteRequest, 0, out result);
                            break;
                        }
                    case "Disconnect":
                        {
                            DisconnectRequestBody DisconnectRequest = new DisconnectRequestBody();
                            DisconnectRequest.Parse(stream);
                            topNode = DisconnectRequest.AddNodesForTree(DisconnectRequest, 0, out result);
                            break;
                        }
                    case "NotificationWait":
                        {
                            NotificationWaitRequestBody NotificationWaitRequest = new NotificationWaitRequestBody();
                            NotificationWaitRequest.Parse(stream);
                            topNode = NotificationWaitRequest.AddNodesForTree(NotificationWaitRequest, 0, out result);
                            break;
                        }
                    case "Bind":
                        {
                            BindRequest bindRequest = new BindRequest();
                            bindRequest.Parse(stream);
                            topNode = bindRequest.AddNodesForTree(bindRequest, 0, out result);
                            break;
                        }
                    default:
                        {
                            this.oMAPIControl.MAPIRichTextBox.Visible = true;
                            this.oMAPIControl.MAPIRichTextBox.Text = "Unavailable Request Type.";
                            break;
                        }
                }

                this.oMAPIViewControl.Nodes.Add(topNode);
                topNode.Expand();
                this.oMAPIViewControl.EndUpdate();

            }
            else
            {
                this.oMAPIViewControl.BeginUpdate();
                TreeNode topNode = new TreeNode(requestType + "Response:");

                switch (requestType)
                {
                    case "Connect":
                        {
                            ConnectResponseBody ConnectResponse = new ConnectResponseBody();
                            ConnectResponse.Parse(stream);
                            topNode = ConnectResponse.AddNodesForTree(ConnectResponse, 0, out result);
                            if (ConnectResponse.StatusCode == 0)
                            {
                                string text = topNode.Text.Replace("Response", "SuccessResponse");
                                topNode.Text = text;
                            }
                            else
                            {
                                string text = topNode.Text.Replace("Response", "FailureResponse");
                                topNode.Text = text;
                            }
                            break;
                        }
                    case "Execute":
                        {
                            ExecuteResponseBody ExecuteResponse = new ExecuteResponseBody();
                            ExecuteResponse.Parse(stream);
                            topNode = ExecuteResponse.AddNodesForTree(ExecuteResponse, 0, out result);
                            if (ExecuteResponse.StatusCode == 0)
                            {
                                string text = topNode.Text.Replace("Response", "SuccessResponse");
                                topNode.Text = text;
                            }
                            else
                            {
                                string text = topNode.Text.Replace("Response", "FailureResponse");
                                topNode.Text = text;
                            }
                            break;
                        }
                    case "Disconnect":
                        {

                            DisconnectResponseBody DisconnectResponse = new DisconnectResponseBody();
                            DisconnectResponse.Parse(stream);
                            topNode = DisconnectResponse.AddNodesForTree(DisconnectResponse, 0, out result);
                            if (DisconnectResponse.StatusCode == 0)
                            {
                                string text = topNode.Text.Replace("Response", "SuccessResponse");
                                topNode.Text = text;
                            }
                            else
                            {
                                string text = topNode.Text.Replace("Response", "FailureResponse");
                                topNode.Text = text;
                            }
                            break;
                        }
                    case "NotificationWait":
                        {

                            NotificationWaitResponseBody NotificationWaitResponse = new NotificationWaitResponseBody();
                            NotificationWaitResponse.Parse(stream);
                            topNode = NotificationWaitResponse.AddNodesForTree(NotificationWaitResponse, 0, out result);
                            if (NotificationWaitResponse.StatusCode == 0)
                            {
                                string text = topNode.Text.Replace("Response", "SuccessResponse");
                                topNode.Text = text;
                            }
                            else
                            {
                                string text = topNode.Text.Replace("Response", "FailureResponse");
                                topNode.Text = text;
                            }
                            break;
                        }
                    case "Bind":
                        {
                            BindResponse bindResponse = new BindResponse();
                            bindResponse.Parse(stream);
                            topNode = bindResponse.AddNodesForTree(bindResponse, 0, out result);
                            if (bindResponse.StatusCode == 0)
                            {
                                string text = topNode.Text.Replace("Response", "SuccessResponse");
                                topNode.Text = text;
                            }
                            else
                            {
                                string text = topNode.Text.Replace("Response", "FailureResponse");
                                topNode.Text = text;
                            }
                            break;
                        }
                    default:
                        {
                            this.oMAPIControl.MAPIRichTextBox.Visible = true;
                            this.oMAPIControl.MAPIRichTextBox.Text = "Unavailable Response Type.";
                            break;
                        }
                }

                    this.oMAPIViewControl.Nodes.Add(topNode);
                    topNode.Expand();
                    this.oMAPIViewControl.EndUpdate();
                }
            }
            catch (Exception ex)
            {
                this.oMAPIControl.MAPIRichTextBox.Visible = true;
                this.oMAPIControl.MAPIRichTextBox.Text = ex.ToString();
                this.oMAPIViewControl.EndUpdate();
            }
        }
        /// <summary>
        /// Parse the HTTP payload to FSSHTTP and WOPI message.
        /// </summary>
        /// <param name="responseHeaders">The HTTP response header.</param>
        /// <param name="bytesFromHTTP">The raw data from HTTP layer.</param>
        /// <param name="direction">The direction of the traffic.</param>
        /// <returns>The object parsed result</returns>
        public object ParseHTTPPayloadForFSSHTTP(HTTPHeaders responseHeaders, byte[] bytesFromHTTP, TrafficDirection direction)
        {
            object objectOut = null;
            byte[] emptyByte = new byte[0];

            if (bytesFromHTTP == null || bytesFromHTTP.Length == 0)
            {
                return null;
            }

            try
            {
                if (direction == TrafficDirection.Out && responseHeaders.Exists("Transfer-Encoding") && responseHeaders["Transfer-Encoding"] == "chunked")
                {
                    bytesFromHTTP = Utilities.GetPaylodFromChunkedBody(bytesFromHTTP);
                }

                Stream stream = new MemoryStream(bytesFromHTTP);
                StreamReader reader = new StreamReader(stream);
                string text = reader.ReadToEnd();

                Regex SOAPRegex = new Regex(@"\<s:Envelop.*\<\/s:Envelope\>"); // extract envelop from http payload.
                if (SOAPRegex.Match(text).Success)
                {
                    XmlDocument doc = new XmlDocument();
                    string soapbody = SOAPRegex.Match(text).Value;

                    if (direction == TrafficDirection.In)
                    {
                        Regex FSSHTTPRequestRegex = new Regex("xsi:type=\"\\w*\"\\s"); // remove xsi:type in xml message. this xsi:type is used for inherit in xmlSerializer.
                        string FSSHTTPRequest = FSSHTTPRequestRegex.Replace(soapbody, string.Empty);
                        MemoryStream ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(FSSHTTPRequest ?? ""));
                        XmlSerializer serializer = new XmlSerializer(typeof(RequestEnvelope));
                        RequestEnvelope requestEnvelop = (RequestEnvelope)serializer.Deserialize(ms);
                        objectOut = requestEnvelop.Body;

                        // if SubRequestData has fsshttpb messages do parser.
                        if (requestEnvelop.Body.RequestCollection != null)
                        {
                            TryParseFSSHTTPBRequestMessage(requestEnvelop.Body.RequestCollection.Request, bytesFromHTTP);
                        }
                    }
                    else
                    {
                        MemoryStream ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(soapbody ?? ""));
                        XmlSerializer serializer = new XmlSerializer(typeof(ResponseEnvelope));
                        ResponseEnvelope responseEnvelop = (ResponseEnvelope)serializer.Deserialize(ms);
                        objectOut = responseEnvelop.Body;

                        // if SubResponseData has fsshttpb messages do parser.
                        if (responseEnvelop.Body.ResponseCollection != null)
                        {
                            TryParseFSSHTTPBResponseMessage(responseEnvelop.Body.ResponseCollection.Response, bytesFromHTTP);
                        }
                    }
                }
                return objectOut;
            }
            catch (Exception ex)
            {
                objectOut = ex.ToString();
                return objectOut;
            }
        }
 private static ArrayList getCookies(HTTPHeaders oHeaders)
 {
     ArrayList list = new ArrayList();
     if (oHeaders is HTTPRequestHeaders)
     {
         string str = oHeaders["Cookie"];
         if (!string.IsNullOrEmpty(str))
         {
             foreach (string str2 in str.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
             {
                 string sString = str2.Trim();
                 if (sString.Length >= 1)
                 {
                     Hashtable hashtable = new Hashtable();
                     hashtable.Add("name", Utilities.TrimAfter(sString, '='));
                     hashtable.Add("value", Utilities.TrimBefore(sString, '='));
                     list.Add(hashtable);
                 }
             }
         }
         return list;
     }
     foreach (HTTPHeaderItem item in oHeaders)
     {
         if (item.Name == "Set-Cookie")
         {
             Hashtable hashtable2 = new Hashtable();
             string str4 = item.Value;
             string str5 = Utilities.TrimAfter(str4, ';');
             hashtable2.Add("name", Utilities.TrimAfter(str5, '='));
             hashtable2.Add("value", Utilities.TrimBefore(str5, '='));
             string str6 = Utilities.TrimBefore(str4, ';');
             if (!string.IsNullOrEmpty(str6))
             {
                 DateTime time;
                 if (str6.IndexOf("httpOnly", StringComparison.OrdinalIgnoreCase) > -1)
                 {
                     hashtable2.Add("httpOnly", "true");
                 }
                 if (str6.IndexOf("secure", StringComparison.OrdinalIgnoreCase) > -1)
                 {
                     hashtable2.Add("_secure", "true");
                 }
                 Regex regex = new Regex("expires\\s?=\\s?[\"]?(?<TokenValue>[^\";]*)");
                 Match match = regex.Match(str6);
                 if ((match.Success && (match.Groups["TokenValue"] != null)) && DateTime.TryParse(match.Groups["TokenValue"].Value, out time))
                 {
                     hashtable2.Add("expires", time.ToString("o"));
                 }
                 regex = new Regex("domain\\s?=\\s?[\"]?(?<TokenValue>[^\";]*)");
                 match = regex.Match(str6);
                 if (match.Success && (match.Groups["TokenValue"] != null))
                 {
                     hashtable2.Add("domain", match.Groups["TokenValue"].Value);
                 }
                 match = new Regex("path\\s?=\\s?[\"]?(?<TokenValue>[^\";]*)").Match(str6);
                 if (match.Success && (match.Groups["TokenValue"] != null))
                 {
                     hashtable2.Add("path", match.Groups["TokenValue"].Value);
                 }
             }
             list.Add(hashtable2);
         }
     }
     return list;
 }
 private static ArrayList getHeadersAsArrayList(HTTPHeaders oHeaders)
 {
     ArrayList list = new ArrayList();
     foreach (HTTPHeaderItem item in oHeaders)
     {
         Hashtable hashtable = new Hashtable(2);
         hashtable.Add("name", item.Name);
         hashtable.Add("value", item.Value);
         list.Add(hashtable);
     }
     return list;
 }
        /// <summary>
        /// Parse the HTTP payload to WOPI message.
        /// </summary>
        /// <param name="requestHeaders">The HTTP request header.</param>
        /// <param name="responseHeaders">The HTTP response header.</param>
        /// <param name="url">url for a HTTP message.</param>
        /// <param name="bytesFromHTTP">The raw data from HTTP layer.</param>
        /// <param name="direction">The direction of the traffic.</param>
        /// <returns>The object parsed result</returns>
        public object ParseHTTPPayloadForWOPI(HTTPHeaders requestHeaders, HTTPHeaders responseHeaders, string url, byte[] bytesFromHTTP, out string binaryStructureRopName, TrafficDirection direction)
        {
            object objectOut = null;
            binaryStructureRopName = string.Empty;
            try
            {
                if (direction == TrafficDirection.Out && responseHeaders.Exists("Transfer-Encoding") && responseHeaders["Transfer-Encoding"] == "chunked")
                {
                    bytesFromHTTP = Utilities.GetPaylodFromChunkedBody(bytesFromHTTP);
                }

                Stream stream = new MemoryStream(bytesFromHTTP);
                StreamReader reader = new StreamReader(stream);
                string text = reader.ReadToEnd();
                WOPIOperations operation = GetWOPIOperationName(requestHeaders, url);
                if (direction == TrafficDirection.In)
                {
                    switch (operation)
                    {
                        case WOPIOperations.PutRelativeFile:
                            objectOut = bytesFromHTTP;
                            binaryStructureRopName = "PutRelativeFile";
                            break;
                        case WOPIOperations.PutFile:
                            objectOut = bytesFromHTTP;
                            binaryStructureRopName = "PutFile";
                            break;
                        case WOPIOperations.ExecuteCellStorageRelativeRequest:
                        case WOPIOperations.ExecuteCellStorageRequest:
                            byte[] cellreq = bytesFromHTTP;
                            MemoryStream ms;
                            if (requestHeaders.Exists("Content-Encoding") && requestHeaders["Content-Encoding"] == "gzip")
                            {
                                cellreq = Fiddler.Utilities.GzipExpand(cellreq);
                                ms = new MemoryStream(cellreq);
                            }
                            else
                            {
                                ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(text ?? ""));
                            }
                            XmlSerializer serializer = new XmlSerializer(typeof(RequestEnvelope));
                            RequestEnvelope requestEnvelop = (RequestEnvelope)serializer.Deserialize(ms);
                            objectOut = requestEnvelop.Body;

                            if (requestEnvelop.Body.RequestCollection != null)
                            {
                                TryParseFSSHTTPBRequestMessage(requestEnvelop.Body.RequestCollection.Request, bytesFromHTTP);
                            }
                            break;
                        case WOPIOperations.PutUserInfo:
                            objectOut = text;
                            break;
                        case WOPIOperations.Discovery:
                        case WOPIOperations.CheckFileInfo:
                        case WOPIOperations.Lock:
                        case WOPIOperations.RefreshLock:
                        case WOPIOperations.RevokeRestrictedLink:
                        case WOPIOperations.Unlock:
                        case WOPIOperations.UnlockAndRelock:
                        case WOPIOperations.GetLock:
                        case WOPIOperations.DeleteFile:
                        case WOPIOperations.ReadSecureStore:
                        case WOPIOperations.RenameFile:
                        case WOPIOperations.GetRestrictedLink:
                        case WOPIOperations.CheckFolderInfo:
                        case WOPIOperations.GetFile:
                        case WOPIOperations.EnumerateChildren:
                            objectOut = string.Format("{0} operation's request body is null", operation.ToString());
                            break;
                        default:
                            throw new Exception("The WOPI operations type is not right.");
                    }
                }
                else
                {
                    string status = this.session.ResponseHeaders.HTTPResponseStatus.Replace(" " + this.session.ResponseHeaders.StatusDescription, string.Empty);
                    if (Convert.ToUInt32(status) != 200)// the status is not success
                        return null;

                    ResponseBodyBase responseBody = new ResponseBodyBase();
                    switch (operation)
                    {
                        case WOPIOperations.Discovery:
                            MemoryStream discoveryms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(text ?? ""));
                            XmlSerializer discoverySerializer = new XmlSerializer(typeof(wopidiscovery));
                            wopidiscovery discoveryres = (wopidiscovery)discoverySerializer.Deserialize(discoveryms);
                            objectOut = discoveryres;
                            break;
                        case WOPIOperations.CheckFileInfo:
                            objectOut = WOPISerilizer.JsonToObject<CheckFileInfo>(text);
                            break;
                        case WOPIOperations.CheckFolderInfo:
                            objectOut = WOPISerilizer.JsonToObject<CheckFolderInfo>(text);
                            break;
                        case WOPIOperations.PutRelativeFile:
                            objectOut = WOPISerilizer.JsonToObject<PutRelativeFile>(text);
                            break;
                        case WOPIOperations.ReadSecureStore:
                            objectOut = WOPISerilizer.JsonToObject<ReadSecureStore>(text);
                            break;
                        case WOPIOperations.EnumerateChildren:
                            objectOut = WOPISerilizer.JsonToObject<EnumerateChildren>(text);
                            break;
                        case WOPIOperations.RenameFile:
                            objectOut = WOPISerilizer.JsonToObject<RenameFile>(text);
                            break;
                        case WOPIOperations.ExecuteCellStorageRelativeRequest:
                        case WOPIOperations.ExecuteCellStorageRequest:
                            {
                                byte[] cellres = bytesFromHTTP;
                                MemoryStream ms;
                                string res;
                                if (responseHeaders.Exists("Content-Encoding") && responseHeaders["Content-Encoding"] == "gzip")
                                {
                                    cellres = Fiddler.Utilities.GzipExpand(cellres);
                                    string res_sub = System.Text.Encoding.UTF8.GetString(cellres);
                                    res = string.Format("{0}{1}{2}", @"<Body>", res_sub, "</Body>");
                                }
                                else
                                {
                                    res = string.Format("{0}{1}{2}", @"<Body>", text, "</Body>");
                                }
                                ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(res ?? ""));
                                XmlSerializer serializer = new XmlSerializer(typeof(ResponseEnvelopeBody));
                                ResponseEnvelopeBody body = (ResponseEnvelopeBody)serializer.Deserialize(ms);
                                objectOut = body;

                                // if SubResponseData has fsshttpb messages do parser.
                                if (body.ResponseCollection != null)
                                {
                                    TryParseFSSHTTPBResponseMessage(body.ResponseCollection.Response, bytesFromHTTP);
                                }
                                break;
                            }
                        case WOPIOperations.GetFile:
                            objectOut = bytesFromHTTP;
                            binaryStructureRopName = "GetFile";
                            break;
                        case WOPIOperations.DeleteFile:
                        case WOPIOperations.Lock:
                        case WOPIOperations.GetRestrictedLink:
                        case WOPIOperations.PutFile:
                        case WOPIOperations.RefreshLock:
                        case WOPIOperations.RevokeRestrictedLink:
                        case WOPIOperations.Unlock:
                        case WOPIOperations.UnlockAndRelock:
                        case WOPIOperations.GetLock:
                        case WOPIOperations.PutUserInfo:
                            objectOut = string.Format("{0} operation's response body is null", operation.ToString());
                            break;
                        default:
                            throw new Exception("The WOPI operations type is not right.");
                    }
                }
                return objectOut;
            }
            catch (Exception ex)
            {
                objectOut = ex.ToString();
                return objectOut;
            }
        }
 protected void SetHeaders(HTTPHeaders header)
 {
     validHeader = (header["Content-Type"] == "application/vnd.ms-sync.wbxml");
 }
Exemple #17
0
 internal static bool ParseNVPHeaders(HTTPHeaders oHeaders, string[] sHeaderLines, int iStartAt, ref string sErrors)
 {
     bool flag = true;
     int index = iStartAt;
     HTTPHeaderItem item = null;
     while (index < sHeaderLines.Length)
     {
         int length = sHeaderLines[index].IndexOf(':');
         if (length > 0)
         {
             item = oHeaders.Add(sHeaderLines[index].Substring(0, length), sHeaderLines[index].Substring(length + 1).TrimStart(new char[] { ' ', '\t' }));
         }
         else if (length == 0)
         {
             item = null;
             sErrors = sErrors + string.Format("Missing Header name #{0}, {1}\n", (1 + index) - iStartAt, sHeaderLines[index]);
             flag = false;
         }
         else
         {
             item = oHeaders.Add(sHeaderLines[index], string.Empty);
             sErrors = sErrors + string.Format("Missing colon in header #{0}, {1}\n", (1 + index) - iStartAt, sHeaderLines[index]);
             flag = false;
         }
         index++;
         for (bool flag2 = ((item != null) && (index < sHeaderLines.Length)) && IsPrefixedWithWhitespace(sHeaderLines[index]); flag2; flag2 = (index < sHeaderLines.Length) && IsPrefixedWithWhitespace(sHeaderLines[index]))
         {
             FiddlerApplication.Log.LogString("[HTTPWarning] Header folding detected. Not all clients properly handle folded headers.");
             item.Value = item.Value + " " + sHeaderLines[index].TrimStart(new char[] { ' ', '\t' });
             index++;
         }
     }
     return flag;
 }
        /// <summary>
        /// Get the WOPI operation
        /// </summary>
        /// <param name="headers">Http headers</param>
        /// <param name="url">url for a session</param>
        /// <returns>The operation name</returns>
        public WOPIOperations GetWOPIOperationName(HTTPHeaders headers, string url)
        {
            if (url.EndsWith("hosting/discovery"))
                return WOPIOperations.Discovery;

            if (headers.Exists("X-WOPI-Override"))
            {
                switch (headers["X-WOPI-Override"] as string)
                {
                    case "PUT_RELATIVE":
                        return WOPIOperations.PutRelativeFile;
                    case "UNLOCK":
                        return WOPIOperations.Unlock;
                    case "REFRESH_LOCK":
                        return WOPIOperations.RefreshLock;
                    case "DELETE":
                        return WOPIOperations.DeleteFile;
                    case "READ_SECURE_STORE":
                        return WOPIOperations.ReadSecureStore;
                    case "GET_RESTRICTED_LINK":
                        return WOPIOperations.GetRestrictedLink;
                    case "REVOKE_RESTRICTED_LINK":
                        return WOPIOperations.RevokeRestrictedLink;
                    case "PUT":
                        return WOPIOperations.PutFile;
                    case "LOCK":
                        if (headers.Exists("X-WOPI-OldLock"))
                        {
                            return WOPIOperations.UnlockAndRelock;
                        }
                        else
                        {
                            return WOPIOperations.Lock;
                        }
                    case "COBALT":
                        if (headers.Exists("X-WOPI-RelativeTarget"))
                        {
                            return WOPIOperations.ExecuteCellStorageRelativeRequest;
                        }
                        else
                        {
                            return WOPIOperations.ExecuteCellStorageRequest;
                        }
                    default:
                        return WOPIOperations.Unknown;
                }
            }

            if (url.EndsWith("/contents"))
            {
                return WOPIOperations.GetFile;
            }

            if (url.EndsWith("/children"))
            {
                return WOPIOperations.EnumerateChildren;
            }

            if (url.Contains("/files/"))
            {
                return WOPIOperations.CheckFileInfo;
            }

            if (url.Contains("/folders/"))
            {
                return WOPIOperations.CheckFolderInfo;
            }

            return WOPIOperations.Unknown;
        }