Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The only option is to include that block of code into each of my functions?

Several of my functions require the UniversalXPConnect privilege to be enabled.

netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');

So, my functions look like this:

function oneOfMyFunctions() {
    netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');

    // ...
}

Actually, I also try to catch the exception when the privilege is denied. Looks as follows:

try {
    netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');

    // ...
} catch (e) {
    // ...
}

I'd rather to make that a separate function and call it from within my functions as follows:

function oneOfMyFunctions() {
    if (enablePrivilege()) {
        // ...
    } else {
        // ...
    }
}

Given that the enablePrivilege function would be as follows:

function enablePrivilege() {
    try {
        netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
    } catch (e) {
        return false;
    }

    return true;
}

But, for security reasons, that is impossible as the privilege is granted only in the scope of the requesting function.

So, the only option is to include that block of code into each of my functions?

UPDATE:

As I am going to also try to catch some other exceptions I've ended up with the following design:

function readFile(path, start, length) {
    netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');

    var file = Components.classes['@mozilla.org/file/local;1'].createInstance(Components.interfaces.nsILocalFile);
    file.initWithPath(path);

    var istream = Components.classes['@mozilla.org/network/file-input-stream;1'].createInstance(Components.interfaces.nsIFileInputStream);
    istream.init(file, -1, -1, false);

    istream.QueryInterface(Components.interfaces.nsISeekableStream);
    istream.seek(0, start);

    var bstream = Components.classes['@mozilla.org/binaryinputstream;1'].createInstance(Components.interfaces.nsIBinaryInputStream);
    bstream.setInputStream(istream);

    return bstream.readBytes(length);
}

var filepath = 'C:\\test.txt', start = 440, length = 5;

try {
    console.log(readFile(filepath, start, length));
} catch (e) {
    if (e.name == 'Error') console.log('The privilege to read the file is not granted.');
    else console.log('An error happened trying to read the file.');
}
like image 507

1 Answers

You could make enablePrivilege a sort of wrapper function that accepts a function as a parameter that it then calls inside itself, like so

function enablePrivilege(funcParam) {
    //enable privileges, in try-catch
    funcParam();
}

so that when you call it like so

enablePrivilege(oneOfMyFunctions);

the function that needs the privileges should have them since it is called inside the scope of enablePrivilege.

like image 198
shelman Avatar answered Nov 10 '22 03:11

shelman