Skip to content
This repository was archived by the owner on Jan 23, 2023. It is now read-only.

Fix CookieException thrown for invalid HttpListener cookies - #19138

Merged
Priya91 merged 10 commits into
dotnet:masterfrom
hughbe:httplistener-cookies
May 10, 2017
Merged

Priya91 merged 10 commits into
dotnet:masterfrom
hughbe:httplistener-cookies

Conversation

@hughbe

@hughbe hughbe commented Apr 29, 2017 •

Copy link
Copy Markdown

Fixes #18482
Fixes #18486
Contributes to #18128

Best reviewed commit-by-commit, lot's of code movement here.

@hughbe

hughbe commented Apr 29, 2017 •

Copy link
Copy Markdown
Author


// This is a modified copy of CoookieCollection.InternalAdd, which is internal to System.Net.Primitives.
// It differs from the original in some subtle ways.
// Firstly, new Variant cookies will not overwrite older ones. We can't have this behaviour as Cookie.Variant

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If anyone has ideas for this, please let me know

cookie.Domain = CheckQuoted(_tokenizer.Value);
cookie.IsQuotedDomain = _tokenizer.Quoted;
// TODO: this is internal.
// cookie.IsQuotedDomain = _tokenizer.Quoted;

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Obviously this needs to be fixed before this goes in

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't have a way to solve this problem yet, I guess we can go with reflection option, add to this file here, and then explore options to expose the APIs tracked in issue #13607

cc @stephentoub @davidsh

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess we can go with reflection option

That might break this for UWP. Since we plan to take this managed listener implementation as the System.Net.HttpListener library for UWP, using reflection might not work the same. In the past, reflection APIs weren't supported in UWP. It might be better now....but something to investigate.

}

// They are equal here even if variants are still different.
return 0;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you can replace line 27 to end with return string.Compare(left.Path, right.Path, StringComparison.Ordinal)

bool cookieExists = false;
foreach (Cookie addedCookie in cookies)
{
if (CookieComparer.Compare(cookie, addedCookie) == 0)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the only place you're using CookieCompaerer, you could inline it, or at least chnage it to just compare equality, which is quicker.
I know nothing about Cookies/this change but I assume htere's a reason you're not just using cookie.Equals (eg you want to ignore cookie.Value)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a copy of the code of CookieCollection.InternalAdd that I can't use because, well, it's internal. CookieCollection.InternalAdd uses this comparer for some reason. It'd be a backwards incompatible change to use cookie.Equals as I think cookie.Equals would return false for things cookiecomparer would return true.

@davidsh

davidsh commented Apr 29, 2017

Copy link
Copy Markdown
Contributor

Is this Cookie code copied from the existing sources? I really think we need a way to have only one copy of the code even though we might compile it into multiple libraries. We have solved this problem before putting the single copy of the code into a Common place and using ifdef in a sparing way to help change namespaces or whatever. But having multiple copies of this parsing code is going to get us into trouble when we have to make bug fixes.

cc: @CIPop @stephentoub

@hughbe

hughbe commented May 1, 2017

Copy link
Copy Markdown
Author

What I did was cut CookieParser and CookieComparer out of Cookie.cs in S.N.Primitives and moved them to their own files in Common.
The following commits modify the code that was previously exactly the same as it was before the cut and paste. This is needed as CookieParser reads and writes internal state in Cookie.
Obviously if you look at the TODOs, it's not quite ready yet.

@davidsh

davidsh commented May 2, 2017 •

Copy link
Copy Markdown
Contributor

What I did was cut CookieParser and CookieComparer out of Cookie.cs in S.N.Primitives and moved them to their own files in Common.

[edit]
After taking another look thru this, I do see that the internal classes were deleted and moved to the Common files. Thanks.

@hughbe

hughbe commented May 3, 2017

Copy link
Copy Markdown
Author

After taking another look thru this, I do see that the internal classes were deleted and moved to the Common files. Thanks.

No problem. I expect test failures as long until Commit 5 (c81b1f1) is reverted or replaced but I'm not sure how

@danmoseley

Copy link
Copy Markdown

@hughbe I'm confused where we're at. Are we waiting on something?

@danmoseley

Copy link
Copy Markdown

.. jus conscious that this must be committed before 5/10

@hughbe

hughbe commented May 5, 2017

Copy link
Copy Markdown
Author

I'm stumped by the OS X failures. Could the best thing to do be disable these tests on OSX, I don't know what's causing them

@hughbe

hughbe commented May 5, 2017

Copy link
Copy Markdown
Author

Oh wait that's a different PR, #19219

Priya gave some feedback last night which ill do today

@hughbe

hughbe commented May 6, 2017

Copy link
Copy Markdown
Author

Responded to PR feedback - and fixed a bug in my implementation of InternalAdd where variants were ignored.
Unfortunately, reflection seems like the only way

{
// We need to use Cookie.InternalSetName instead of the Cookie.set_Name wrapped in a try catch block, as
// Cookie.set_Name keeps the original name if the string is empty or null.
// Unfortunately this API is internal so we use reflection to access it. The method is cached for performance reasons.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Priya91 unfortunately, we can't do

try
{
    cookie.Name = name;
}
catch (CookieException)
{
    Debug.Assert(cookie.Name == string.Empty);
}

because if name is null or empty, Cookie.set_Name doesn't override the old name, whereas Cookie.InternalSetName does override the old name unconditionally

return result;
}

// NB: The only path is case sensitive as per spec. However, many Windows applications assume

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: "The only path" => "Only the path"

catch (CookieException)
{
Debug.Assert(cookie.Name == string.Empty);
}

@stephentoub stephentoub May 8, 2017 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why did this change away from using Cookie.InternalSetName? Will this behave identically?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And if string.Empty will always be rejected, should we special-case it to avoid the exception being thrown?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right, Cookie.set_Name and Cookie.InternalSetName have different properties when passing string.Empty to them.

Cookie:

public string Name
{
    get
    {
        return _name;
    }
    set
    {
        if (String.IsNullOrEmpty(value) || !InternalSetName(value))
        {
            throw new CookieException(SR.Format(SR.net_cookie_attribute, "Name", value == null ? "<null>" : value));
        }
    }
}

internal bool InternalSetName(string value)
{
    if (String.IsNullOrEmpty(value) || value[0] == '$' || value.IndexOfAny(ReservedToName) != -1)
    {
        _name = string.Empty;
        return false;
    }
    _name = value;
    return true;
}

Notice that if we pass string.Empty to set_Name, Cookie.Name stays the same as it was before, but if we pass string.Empty to InternalSetName, Cookie.Name is set to string.Empty.

I've worked around this by doing reflection. This is an older commit

{
// This cookie will be rejected
cookie.InternalSetName(string.Empty);
SetCookieName(cookie, string.Empty);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Isn't this going to just be a nop that throws an exception and eats it? Why call it at all?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(Same for all of the other call sites)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not any more, as we now call cookie.InternalSetName via reflection

continue;
}

// This is a modified copy of CoookieCollection.InternalAdd, which is internal to System.Net.Primitives.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: Coookie => Cookie

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is an old commit, the comment no longer exists :)

if (NetEventSource.IsEnabled) NetEventSource.Info(this, "uri:" + uri + " setCookieHeader:" + setCookieHeader);
CookieCollection cookies = new CookieCollection();
CookieParser parser = new CookieParser(setCookieHeader);
for (;;)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: I think while(true) is more readable but it doesn't really matter as they will compile identically


return s_internalAddMethod;
}
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It'd be more efficient to create and cache a delegate from this rather than using MethodInfo.Invoke each time.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you please clarify this @stephentoub? I'm trying to use Delegate.CreateDelegate or MethodInfo.CreateDelegate but they require us to know the instance to invoke Cookie.InternalSetMethod on

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

NVM, I've got it, thanks

if (s_isQuotedDomainField == null)
{
FieldInfo field = typeof(Cookie).GetField("IsQuotedDomain", BindingFlags.NonPublic | BindingFlags.Instance);
Debug.Assert(field != null, "We need to use an internal property named IsQuotedDomain that is declared on Cookie.");

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"an internal property"... property or field?

for (;;)
{
Cookie cookie = parser.GetServer();
if (NetEventSource.IsEnabled) NetEventSource.Info(this, "CookieParser returned cookie:" + cookie?.ToString());

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: space after "CookieParser returned cookie:".
I think the logging doesn't make sense if the cookie is null as the string then will be "CookieParser returned cookie:" //EOL. I would move it after the cookie null check


internal Cookie GetServer()
{
Cookie cookie = _savedCookie;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: Declaration and assignment in one line

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry I don't understand this, could you clarify? The code is

            Cookie cookie = _savedCookie;
            _savedCookie = null;


do
{
bool first = cookie == null || cookie.Name == null || cookie.Name.Length == 0;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cookie.Name == null || cookie.Name.Length == 0 --> string.IsNullOrEmpty(cookie.Name)

// this is a new cookie, this token is for the next cookie.
_savedCookie = new Cookie();
int parsed;
if (int.TryParse(_tokenizer.Value, out parsed))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

inline declaration: if (int.TryParse(_tokenizer.Value, out int parsed))

{
versionSet = true;
int parsed;
if (int.TryParse(CheckQuoted(_tokenizer.Value), out parsed))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same here: inline declaration of int parsed

{
expiresSet = true;
int parsed;
if (int.TryParse(CheckQuoted(_tokenizer.Value), out parsed))

@ViktorHofer ViktorHofer May 8, 2017 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not using double.TryParse instead of int.TryParse? And inline declaration of parsed.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is that a breaking change? That means we'd now accept values of CookieToken.MaxAge that are doubles instead of integers only. Not sure that's intended

expiresSet = true;

DateTime expires;
if (DateTime.TryParse(CheckQuoted(_tokenizer.Value),

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: again inline declaration of DateTime expires.

{
commentUriSet = true;
Uri parsed;
if (Uri.TryCreate(CheckQuoted(_tokenizer.Value), UriKind.Absolute, out parsed))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: again inline declaration of Uri parsed

@danmoseley

Copy link
Copy Markdown

@hughbe do you expect to have this ready to merge by Wed ? No obligation: don't know your schedule. If not, someone may have to pick it up :)

@hughbe

hughbe commented May 8, 2017

Copy link
Copy Markdown
Author

I can respond to the PR feedback for this one tomorrow. Timezones may get in the way of any additional PR feedback after I commit the feedback though

@davidsh davidsh removed their assignment May 9, 2017
@hughbe

hughbe commented May 9, 2017

Copy link
Copy Markdown
Author

I've addressed all PR feedback apart from @ViktorHofer's "nit: Declaration and assignment in one line" which I don't quite understand ;)

@stephentoub

Copy link
Copy Markdown
Member

I rebased for Hugh to fix the merge conflict.

@Priya91

Priya91 commented May 9, 2017

Copy link
Copy Markdown
Contributor

I rebased for Hugh to fix the merge conflict.

Did you use that github tool or pulled down locally? I was not sure how the commits would be affected from the github link.

@stephentoub

stephentoub commented May 9, 2017 •

Copy link
Copy Markdown
Member

Did you use that github tool or pulled down locally?

I pulled it down locally:
git fetch upstream pull/19138/head:httplistener-cookies
git checkout httplistener-cookies
git fetch upstream
git rebase upstream/master
... // fix conflicts
git rebase --continue
git remote add hughbe https://github.com/hughbe/corefx.git
git push hughbe +httplistener-cookies
git remote remove hughbe

@hughbe

hughbe commented May 10, 2017

Copy link
Copy Markdown
Author

Thanks all

@Priya91
Priya91 merged commit 9b6844c into dotnet:master May 10, 2017
@hughbe
hughbe deleted the httplistener-cookies branch May 11, 2017 02:02
@karelz karelz modified the milestone: 2.0.0 May 13, 2017
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

10 participants