2

here's a little web-server function that gets a url and parses it, making sure that the client is not asking for a resource that's not under the server's root folder

function getUrl(url, resourceMap, rootFolder) {
    var path = require('path');
    if (typeof resourceMap[url] !== 'undefined') {
        return (path.join(rootFolder,resourceMap[url]));
    } 
    var absoluteURL = path.join(rootFolder,url);
    console.log("ROOT: "+rootFolder);
    console.log("NEW: "+absoluteURL);
    var regex = new RegExp('^' + rootFolder + '.*')
    if (absoluteURL.match(regex) === null) {
        console.log("FALSE");
        return (false);
    }
    return (absoluteURL);
}

As you can see I make sure that absoluteURL starts with rootFolder by using the regex '^' + rootFolder + '.*'

This worked well on Linux, but in windows it always returns false.

BTW the output is

ROOT: C:\Users\user\workspace
NEW: C:\Users\user\workspace\images\IMG_7102.JPG

So I know that parsing of the url is ok.

Amy ideas why? Thanks

Yotam
  • 9,789
  • 13
  • 47
  • 68

1 Answers1

4

On Windows, the \s in the path become escape characters in the regex.

You need to regex-escape it:

rootFolder.replace(/[-[\/{}()*+?.\\^$|]/g, "\\$&")
Community
  • 1
  • 1
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • but rootFolder is assigned to be 'C:\\users\\workspace' so there shouldn't be a problem as far as i understand – Yotam Dec 17 '12 at 21:02
  • @Yotam: I assume that's literal source. Those escapes are for the string literal; the actual value of the string has single `\`s. – SLaks Dec 17 '12 at 21:03