Skip to content

Commit

Permalink
Don't allow invalid node names in XML::Node#name=
Browse files Browse the repository at this point in the history
  • Loading branch information
RX14 committed Nov 2, 2017
1 parent 5f1d3e3 commit 9b410e0
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 1 deletion.
25 changes: 25 additions & 0 deletions spec/std/xml/xml_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,31 @@ describe XML do
root.name.should eq("last-name")
end

it "doesn't set invalid node name" do
doc = XML.parse(<<-XML
<?xml version='1.0' encoding='UTF-8'?>
<name>John</name>
XML
)
root = doc.root.not_nil!

expect_raises(XML::Error, "Invalid node name") do
root.name = " foo bar"
end

expect_raises(XML::Error, "Invalid node name") do
root.name = "foo bar"
end

expect_raises(XML::Error, "Invalid node name") do
root.name = "1foo"
end

expect_raises(XML::Error, "Invalid node name") do
root.name = "\0foo"
end
end

it "gets encoding" do
doc = XML.parse(<<-XML
<?xml version='1.0' encoding='UTF-8'?>
Expand Down
2 changes: 2 additions & 0 deletions src/xml/libxml2.cr
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,8 @@ lib LibXML
fun xmlGetNsList(doc : Doc*, node : Node*) : NS**

fun xmlSetProp(node : Node*, name : UInt8*, value : UInt8*) : Attr*

fun xmlValidateNameValue(value : UInt8*) : Int
end

LibXML.xmlGcMemSetup(
Expand Down
13 changes: 12 additions & 1 deletion src/xml/node.cr
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,18 @@ struct XML::Node
if document? || text? || cdata? || fragment?
raise XML::Error.new("Can't set name of XML #{type}", 0)
end
LibXML.xmlNodeSetName(self, name.to_s)

name = name.to_s

if name.includes? '\0'
raise XML::Error.new("Invalid node name: #{name.inspect} (contains null character)")
end

if LibXML.xmlValidateNameValue(name) == 0
raise XML::Error.new("Invalid node name: #{name.inspect}", 0)
end

LibXML.xmlNodeSetName(self, name)
end

# Returns the namespace for this node or `nil` if not found.
Expand Down

0 comments on commit 9b410e0

Please sign in to comment.