1
0
mirror of https://github.com/Ylianst/MeshAgent synced 2025-12-06 00:13:33 +00:00

Updated proxy support

This commit is contained in:
Bryan Roe
2020-06-09 14:25:28 -07:00
parent e448456d9e
commit fedd70072b
6 changed files with 432 additions and 280 deletions

View File

@@ -382,216 +382,23 @@ void MeshAgent_sendConsoleText(duk_context *ctx, char *format, ...)
}
int MeshAgent_GetSystemProxy(MeshAgentHostContainer *agent, char *buffer, size_t bufferSize)
int MeshAgent_GetSystemProxy(MeshAgentHostContainer *agent, char *inBuffer, size_t inBufferLen)
{
#ifndef __APPLE__
int retVal = 0;
#endif
#ifdef _POSIX
#ifndef __APPLE__
// Linux and FreeBSD
for (char **env = environ; *env; ++env)
{
int envLen = (int)strnlen_s(*env, INT_MAX);
int i = ILibString_IndexOf(*env, envLen, "=", 1);
if (i > 0)
{
if (i == 11 && (strncmp(*env, "https_proxy", 11) == 0 || strncmp(*env, "HTTPS_PROXY", 11) == 0))
{
if (ILibString_StartsWith(*env + i + 1, envLen - i - 1, "http://", 7) != 0)
{
strcpy_s(buffer, bufferSize, *env + i + 8);
retVal = envLen - i - 8;
}
else if(ILibString_StartsWith(*env + i + 1, envLen - i - 1, "https://", 8) != 0)
{
strcpy_s(buffer, bufferSize, *env + i + 9);
retVal = envLen - i - 9;
}
else
{
strcpy_s(buffer, bufferSize, *env + i + 1);
retVal = envLen - i - 1;
}
break;
}
}
}
if (retVal == 0)
{
// Check /etc/environment just in case it wasn't exported
#ifdef _FREEBSD
// FreeBSD Only
char getProxy[] = "(function getProxies(){\
var child = require('child_process').execFile('/bin/sh', ['sh']);\
child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });\
child.stdin.write('cat /etc/login.conf | grep :setenv= | awk -F\":setenv=\" \\'{ if(!($1 ~ /^#/)) { print $2 } }\\' | tr \"\\,\" \"\\n\" | awk -F= \\'{ if($1==\"https_proxy\") { gsub(/\\\\\\\\c/, \":\", $2); print $2 } }\\'\\n\\exit\\n');\
child.waitExit();\
return(child.stdout.str.trim().split('\\n')[0].split('//')[1]);\
})();";
#else
// Linux Only
char getProxy[] = "require('proxy-helper').getProxy()";
#endif
// Linux and FreeBSD
if (duk_peval_string(agent->meshCoreCtx, getProxy) == 0)
{
duk_size_t proxyLen;
char *proxy = (char*)duk_get_lstring(agent->meshCoreCtx, -1, &proxyLen);
if (proxy != NULL && proxyLen > 0) { strcpy_s(buffer, bufferSize, proxy); }
retVal = (int)proxyLen;
}
duk_pop(agent->meshCoreCtx);
}
return(retVal);
#else
// MacOS Only
char getProxyies[] = "(function getProxies(){\
var ret = {};\
var child = require('child_process').execFile('/bin/sh', ['sh']);\
child.stdout.str = '';\
child.stdout.on('data', function(chunk) { this.str += chunk.toString(); });\
child.stdin.write('system_profiler SPNetworkDataType | grep \"Proxy\" \\nexit\\n');\
child.waitExit();\
var lines = child.stdout.str.split('\\n');\
for (var i in lines)\
{\
if (lines[i])\
{\
var val = lines[i].split(':')[1].trim().toLowerCase();\
var tokens = lines[i].split(':')[0].trim().split(' ');\
var key = tokens[0].toLowerCase();\
var t = tokens[2].toLowerCase();\
if (!ret[key]) { ret[key] = {}; }\
ret[key][t] = val;\
}\
}\
return(ret);\
})();";
if (duk_peval_string(agent->meshCoreCtx, getProxyies) == 0)
duk_size_t bufferLen = 0;
if (duk_peval_string(agent->meshCoreCtx, "require('proxy-helper').getProxy();") == 0) // [string]
{
if (duk_has_prop_string(agent->meshCoreCtx, -1, "http"))
char *buffer = (char*)duk_get_lstring(agent->meshCoreCtx, -1, &bufferLen);
if (bufferLen <= inBufferLen)
{
duk_get_prop_string(agent->meshCoreCtx, -1, "http");
}
else if (duk_has_prop_string(agent->meshCoreCtx, -1, "https"))
{
duk_get_prop_string(agent->meshCoreCtx, -1, "https");
memcpy_s(inBuffer, inBufferLen, buffer, bufferLen);
}
else
{
duk_pop(agent->meshCoreCtx);
return(0); // No Proxies detected
}
if (strcmp(Duktape_GetStringPropertyValue(agent->meshCoreCtx, -1, "enabled", "no"), "yes") == 0)
{
char *proxyserver, *proxyport;
duk_size_t proxyserverLen, proxyportLen;
proxyserver = (char*)Duktape_GetStringPropertyValueEx(agent->meshCoreCtx, -1, "server", NULL, &proxyserverLen);
proxyport = (char*)Duktape_GetStringPropertyValueEx(agent->meshCoreCtx, -1, "port", "8080", &proxyportLen);
strncpy_s(buffer, bufferSize, proxyserver, proxyserverLen);
strncpy_s(buffer + proxyserverLen, bufferSize - proxyserverLen, ":", 1);
strncpy_s(buffer + proxyserverLen + 1, bufferSize - proxyserverLen - 1, proxyport, proxyportLen);
duk_pop(agent->meshCoreCtx);
return(proxyserverLen + 1 + proxyportLen);
}
else
{
// Proxy is disabled
duk_pop(agent->meshCoreCtx);
return(0);
bufferLen = 0;
}
}
else
{
return(0);
}
#endif
#else
// Windows Only
char getProxy[] = "(function () {\
var isroot = false;\
var servers = [];\
/* First we need to see if we are running as admin */\
var GM = require('_GenericMarshal');\
var advapi = GM.CreateNativeProxy('Advapi32.dll');\
advapi.CreateMethod('AllocateAndInitializeSid');\
advapi.CreateMethod('CheckTokenMembership');\
advapi.CreateMethod('FreeSid');\
var NTAuthority = GM.CreateVariable(6);\
NTAuthority.toBuffer().writeInt8(5, 5);\
var AdministratorsGroup = GM.CreatePointer();\
if (advapi.AllocateAndInitializeSid(NTAuthority, 2, 32, 544, 0, 0, 0, 0, 0, 0, AdministratorsGroup).Val != 0)\
{\
var member = GM.CreateInteger();\
if (advapi.CheckTokenMembership(0, AdministratorsGroup.Deref(), member).Val != 0)\
{\
if (member.toBuffer().readUInt32LE() != 0) { isroot = true; }\
}\
advapi.FreeSid(AdministratorsGroup.Deref());\
}\
var reg = require('win-registry');\
if (isroot)\
{\
/* If running as admin, enumerate the users to find proxy settings */\
var users = reg.QueryKey(reg.HKEY.Users);\
var keys;\
for (var i in users.subkeys)\
{\
try\
{\
value = reg.QueryKey(reg.HKEY.Users, users.subkeys[i] + '\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings', 'ProxyEnable');\
if (value == 1)\
{\
value = reg.QueryKey(reg.HKEY.Users, users.subkeys[i] + '\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings', 'ProxyServer');\
servers.push(value);\
}\
}\
catch (e)\
{\
}\
}\
return (servers);\
}\
else\
{\
/* We're not admin, so we can only check HKEY_LOCAL_USERS for proxy settings */\
try\
{\
if (reg.QueryKey(reg.HKEY.CurrentUser, 'Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Internet Settings', 'ProxyEnable') == 1)\
{\
servers.push(reg.QueryKey(reg.HKEY.CurrentUser, 'Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Internet Settings', 'ProxyServer'));\
}\
}\
catch (e)\
{\
}\
return (servers);\
}\
})();";
if (duk_peval_string(agent->meshCoreCtx, getProxy) == 0)
{
if (duk_get_length(agent->meshCoreCtx, -1) > 0) // [array]
{
duk_get_prop_index(agent->meshCoreCtx, -1, 0); // [array][0];
char *tmp;
duk_size_t tmpLen;
tmp = (char*)duk_get_lstring(agent->meshCoreCtx, -1, &tmpLen);
strncpy_s(buffer, bufferSize, tmp, tmpLen);
duk_pop(agent->meshCoreCtx); // [array]
retVal = (int)tmpLen;
}
}
duk_pop(agent->meshCoreCtx); // ...
return(retVal);
#endif
duk_pop(agent->meshCoreCtx); // ...
return((int)bufferLen);
}
#ifdef _POSIX
size_t MeshAgent_Linux_ReadMemFile(char *path, char **buffer)
@@ -3617,7 +3424,13 @@ void MeshServer_ConnectEx(MeshAgentHostContainer *agent)
agent->proxyServer = ILibWebClient_SetProxy(reqToken, proxyHost, proxyPort, proxyUsername, proxyPassword);
if (agent->proxyServer != NULL)
{
memcpy_s(&(ILibDuktape_GetNewGlobalTunnel(agent->meshCoreCtx)->proxyServer), sizeof(struct sockaddr_in6), agent->proxyServer, sizeof(struct sockaddr_in6));
ILibDuktape_globalTunnel_data *proxy = ILibDuktape_GetNewGlobalTunnel(agent->meshCoreCtx);
memcpy_s(&(proxy->proxyServer), sizeof(struct sockaddr_in6), agent->proxyServer, sizeof(struct sockaddr_in6));
if (proxyUsername != NULL && proxyPassword != NULL)
{
memcpy_s(proxy->proxyUser, sizeof(proxy->proxyUser), proxyUsername, strnlen_s(proxyUsername, sizeof(proxy->proxyUser)));
memcpy_s(proxy->proxyPass, sizeof(proxy->proxyPass), proxyPassword, strnlen_s(proxyPassword, sizeof(proxy->proxyPass)));
}
}
}
}

View File

@@ -1309,7 +1309,14 @@ duk_ret_t ILibDuktape_HttpStream_http_request(duk_context *ctx)
duk_put_prop_string(ctx, -2, "host");
duk_push_int(ctx, (int)ntohs(globalTunnel->proxyServer.sin6_port));
duk_put_prop_string(ctx, -2, "port"); // [options][proxy]
if (globalTunnel->proxyUser[0] != 0 && globalTunnel->proxyPass[0] != 0)
{
duk_push_string(ctx, globalTunnel->proxyUser); duk_put_prop_string(ctx, -2, "username");
duk_push_string(ctx, globalTunnel->proxyPass); duk_put_prop_string(ctx, -2, "password");
}
duk_put_prop_string(ctx, -2, "proxy"); // [options]
duk_pop(ctx); // ...
}

File diff suppressed because one or more lines are too long

32
modules/awk-helper.js Normal file
View File

@@ -0,0 +1,32 @@
/*
Copyright 2020 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
var child = { stdin: { str: '', write: function (v) { this.str += v.trim(); } } };
//child.stdin.write('\nexit\n');
child.stdin.write('\n\n\n');
require('clipboard')(child.stdin.str);
if (process.platform == 'linux')
{
console.log('clipboard active for 5 seconds');
var t = setTimeout(function () { process.exit(); }, 5000);
}
else
{
process.exit();
}

View File

@@ -6,20 +6,34 @@ function gnome_getProxySettings(uid)
child.stderr.str = ''; child.stderr.on('data', function (c) { });
child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
child.stdin.write('gsettings list-recursively org.gnome.system.proxy | tr "\\n" "\\|" | tr "\\\'" "\\`" | awk \'{ count=split($0, res, "|");')
child.stdin.write('exc="[]";');
child.stdin.write('for(a=0;a<count;++a)');
child.stdin.write('gsettings list-recursively org.gnome.system.proxy | tr "\\n" "\\|" | awk \'');
child.stdin.write('{');
child.stdin.write('split(res[a], modecheck, " ");');
child.stdin.write('if(modecheck[2] == "mode")');
child.stdin.write('{');
child.stdin.write('split(modecheck[3], prx, "`"); mode = prx[2];');
child.stdin.write('}');
child.stdin.write('if(modecheck[1]=="org.gnome.system.proxy.http" && modecheck[2]=="host") { split(modecheck[3], hst, "`"); host = hst[2]; }');
child.stdin.write('if(modecheck[1]=="org.gnome.system.proxy.http" && modecheck[2]=="port") { port = modecheck[3]; }');
child.stdin.write('if(modecheck[1]=="org.gnome.system.proxy" && modecheck[2]=="ignore-hosts") { exc = substr(res[a], 36); gsub("`", "\\"", exc); }');
child.stdin.write('}');
child.stdin.write('printf "{\\"mode\\": \\"%s\\", \\"host\\": \\"%s\\", \\"port\\": %s, \\"exceptions\\": %s}", mode, host, port, exc; }\'\nexit\n');
child.stdin.write(' count=split($0, res, "|");')
child.stdin.write(' exc="[]"; auth=""; pwd=""; username=""; enabled="";');
child.stdin.write(' for(a=0;a<count;++a)');
child.stdin.write(' {');
child.stdin.write(' split(res[a], modecheck, " ");');
child.stdin.write(' if(modecheck[2] == "mode")');
child.stdin.write(' {');
child.stdin.write(' split(modecheck[3], prx, "\\047"); mode = prx[2];');
child.stdin.write(' }');
child.stdin.write(' if(modecheck[1]=="org.gnome.system.proxy.http" && modecheck[2]=="host") { split(modecheck[3], hst, "\\047"); host = hst[2]; }');
child.stdin.write(' if(modecheck[1]=="org.gnome.system.proxy.http" && modecheck[2]=="port") { port = modecheck[3]; }');
child.stdin.write(' if(modecheck[1]=="org.gnome.system.proxy.http" && modecheck[2]=="use-authentication") { auth=modecheck[3]; }');
child.stdin.write(' if(modecheck[1]=="org.gnome.system.proxy" && modecheck[2]=="ignore-hosts") { exc = substr(res[a], 36); gsub("\\047", "\\"", exc); }');
child.stdin.write(' if(modecheck[1]=="org.gnome.system.proxy.http" && modecheck[2]=="enabled") { enabled = modecheck[3]; }');
child.stdin.write(' if(modecheck[1]=="org.gnome.system.proxy.http" && modecheck[2]=="authentication-user")');
child.stdin.write(' {');
child.stdin.write(' split(res[a],dummy,"\\047"); username=dummy[2];');
child.stdin.write(' }');
child.stdin.write(' if(modecheck[1]=="org.gnome.system.proxy.http" && modecheck[2]=="authentication-password")');
child.stdin.write(' {');
child.stdin.write(' pwd=substr(res[a],53);');
child.stdin.write(' }');
child.stdin.write(' }');
child.stdin.write(' if(pwd~/^\\047/) { gsub("\\"", "\\\\\\"", pwd); gsub("\\047", "\\"", pwd); }');
child.stdin.write(' printf "{\\"mode\\": \\"%s\\", \\"enabled\\": %s, \\"host\\": \\"%s\\", \\"port\\": %s, \\"authEnabled\\": %s, \\"username\\": \\"%s\\", \\"password\\": %s, \\"exceptions\\": %s}", mode, enabled, host, port, auth, username, pwd, exc;');
child.stdin.write("}'\nexit\n");
child.waitExit();
try
{

View File

@@ -20,16 +20,25 @@ function linux_getProxy()
// Check Environment Variabels
if(require('fs').existsSync('/etc/environment'))
{
var e = require('fs').readFileSync('/etc/environment').toString();
var tokens = e.split('\\n');
for(var line in tokens)
{
var val = tokens[line].split('=');
if(val.length == 2 && (val[0].trim() == 'http_proxy' || val[0].trim() == 'https_proxy'))
{
return(val[1].split('//')[1]);
}
}
var child = require('child_process').execFile('/bin/sh', ['sh']);
child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
child.stdin.write('cat /etc/environment | grep = | ' + "tr '\\n' '`' | awk -F'`' '");
child.stdin.write('{');
child.stdin.write(' host=""; port=""; username=""; password=""; ')
child.stdin.write(' for(i=1;i<NF;++i)');
child.stdin.write(' {');
child.stdin.write(' if($i~/^#/) { continue; }');
child.stdin.write(' split($i,tokens,"=");');
child.stdin.write(' if(tokens[1]=="HTTP_PROXY")');
child.stdin.write(' { ');
child.stdin.write(' proxy=substr($i,2+length(tokens[1]));');
child.stdin.write(' printf "http://%s", proxy;');
child.stdin.write(' break;');
child.stdin.write(' } ');
child.stdin.write(' }');
child.stdin.write("}'\nexit\n");
child.waitExit();
if (child.stdout.str.trim() != '') { return (child.stdout.str.trim()); }
}
// Check profile.d
@@ -39,8 +48,7 @@ function linux_getProxy()
child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
child.stdin.write("cat /etc/profile.d/proxy_setup | awk '" + '{ split($2, tok, "="); if(tok[1]=="http_proxy") { print tok[2]; }}\'\nexit\n');
child.waitExit();
child.ret = child.stdout.str.trim().split('\n')[0].split('//')[1];
if(child.ret != '') { return(child.ret); }
return (child.stdout.str.trim().split('\n')[0]);
}
// Check gsettings
@@ -51,57 +59,251 @@ function linux_getProxy()
for (var i in ids)
{
setting = require('linux-gnome-helpers').getProxySettings(ids[i]);
if (setting.mode == 'manual') { return(setting.host + ':' + setting.port);}
if (setting.mode == 'manual')
{
if (setting.authEnabled)
{
return ('http://' + setting.username + ':' + setting.password + '@' + setting.host + ':' + setting.port);
}
else
{
return ('http://' + setting.host + ':' + setting.port);
}
}
}
}
// check apt proxy setting fro /etc/apt/apt.conf.d/proxy.conf
if (require('fs').existsSync('/etc/apt/apt.conf.d/proxy.conf'))
{
var child = require('child_process').execFile('/bin/sh', ['sh']);
child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
child.stderr.on('data', function (c) { console.log(c.toString()); });
child.stdin.write("cat /etc/apt/apt.conf.d/proxy.conf | tr '\\n' '`' | awk -F'`' '{");
child.stdin.write('for(n=1;n<NF;++n) { ln=split($n,tok,"::"); split(tok[ln],px,"\\""); split(px[2],x,"://"); if(x[2]!="") { print x[2]; break; } }');
child.stdin.write("cat /etc/apt/apt.conf.d/proxy.conf | tr '\\n' '`' | awk -F'`' '");
child.stdin.write('{');
child.stdin.write(' for(n=1;n<NF;++n) ');
child.stdin.write(' {');
child.stdin.write(' if($n~/^#/) { continue; }')
child.stdin.write(' if($n~/^Acquire::http::proxy /)');
child.stdin.write(' {');
child.stdin.write(' split($n, dummy, "Acquire::http::proxy ");');
child.stdin.write(' print substr(dummy[2],2,length(dummy[2])-3);');
child.stdin.write(' break;');
child.stdin.write(' }');
child.stdin.write(' }');
child.stdin.write("}'\nexit\n");
child.waitExit();
if (child.stdout.str.trim() != "") { return (child.stdout.str.trim()); }
}
// check apt proxy setting fro /etc/apt/apt/apt.conf
if (require('fs').existsSync('/etc/apt/apt.conf'))
{
var child = require('child_process').execFile('/bin/sh', ['sh']);
child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
child.stderr.on('data', function (c) { console.log(c.toString()); });
child.stdin.write("cat /etc/apt/apt.conf | tr '\\n' '`' | awk -F'`' '");
child.stdin.write('{');
child.stdin.write(' for(n=1;n<NF;++n) ');
child.stdin.write(' {');
child.stdin.write(' if($n~/^#/) { continue; }')
child.stdin.write(' if($n~/^Acquire::http::proxy /)');
child.stdin.write(' {');
child.stdin.write(' split($n, dummy, "Acquire::http::proxy ");');
child.stdin.write(' print substr(dummy[2],2,length(dummy[2])-3);');
child.stdin.write(' break;');
child.stdin.write(' }');
child.stdin.write(' }');
child.stdin.write("}'\nexit\n");
child.waitExit();
if (child.stdout.str.trim() != "") { return (child.stdout.str.trim()); }
}
// check yum proxy setting
if (require('fs').existsSync('/etc/yum.conf'))
{
var child = require('child_process').execFile('/bin/sh', ['sh']);
child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
child.stderr.on('data', function (c) { console.log(c.toString()); });
child.stdin.write('cat /etc/yum.conf | grep "proxy=" | ' + "tr '\\n' '`' | awk -F'`' '{");
child.stdin.write('for(n=1;n<NF;++n) { cl=split($n,c,"#"); split($n,px,"://"); if(px[2]!="" && cl==1) { print px[2]; break; } }');
child.stdin.write('cat /etc/yum.conf | grep "proxy" | ' + "tr '\\n' '`' | awk -F'`' '");
child.stdin.write('{');
child.stdin.write(' host=""; port=""; username=""; password="";');
child.stdin.write(' for(n=1;n<NF;++n)');
child.stdin.write(' {');
child.stdin.write(' if($n~/^#/) { continue; }');
child.stdin.write(' split($n,tokens,"=");');
child.stdin.write(' if(tokens[1]=="proxy")');
child.stdin.write(' {');
child.stdin.write(' split(tokens[2],dummy,"://");');
child.stdin.write(' split(dummy[2],url,":");');
child.stdin.write(' host = url[1];');
child.stdin.write(' port = url[2]; if(port=="") { port = "8080"; }');
child.stdin.write(' }');
child.stdin.write(' if(tokens[1]=="proxy_username") { username = tokens[2]; }');
child.stdin.write(' if(tokens[1]=="proxy_password") { password = tokens[2]; }');
child.stdin.write(' }');
child.stdin.write(' if(host!="" && port!="")');
child.stdin.write(' {');
child.stdin.write(' if(username!="" && password!="")');
child.stdin.write(' {');
child.stdin.write(' printf "http://%s:%s@%s:%s", username, password, host, port; ');
child.stdin.write(' }');
child.stdin.write(' else');
child.stdin.write(' {');
child.stdin.write(' printf "http://%s:%s", host, port; ');
child.stdin.write(' }');
child.stdin.write(' }');
child.stdin.write("}'\nexit\n");
child.waitExit();
if (child.stdout.str.trim() != "") { return (child.stdout.str.trim()); }
}
// openSUSE proxy setting
if (require('fs').existsSync('/etc/sysconfig/proxy'))
{
var child = require('child_process').execFile('/bin/sh', ['sh']);
child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
child.stderr.on('data', function (c) { console.log(c.toString()); });
child.stdin.write('cat /etc/sysconfig/proxy | grep PROXY_ENABLED= | awk \'{');
child.stdin.write('split($0,res,"\\""); if(res[2]=="yes") { print res[2]; }')
child.stderr.on('data', function (c) { });
child.stdin.write('cat /etc/sysconfig/proxy /root/.curlrc | grep = | ' + "tr '\\n' '`' | awk -F'`' '");
child.stdin.write('{');
child.stdin.write(' proxy=""; enabled=""; username=""; password=""; ')
child.stdin.write(' for(i=1;i<NF;++i)');
child.stdin.write(' {');
child.stdin.write(' if($i~/^#/) { continue; }');
child.stdin.write(' split($i,tokens,"=");');
child.stdin.write(' if(tokens[1]=="PROXY_ENABLED")');
child.stdin.write(' {');
child.stdin.write(' split(tokens[2],dummy,"\\"");');
child.stdin.write(' enabled = dummy[2];');
child.stdin.write(' }');
child.stdin.write(' if(tokens[1]=="HTTP_PROXY")');
child.stdin.write(' { ');
child.stdin.write(' split(tokens[2],dummy,"\\"");');
child.stdin.write(' proxy = dummy[2];');
child.stdin.write(' } ');
child.stdin.write(' if(tokens[1]~/^proxy-user/)');
child.stdin.write(' {');
child.stdin.write(' cred = substr($i,1+index($i,"="));');
child.stdin.write(' cred = substr(cred, index(cred, "\\""));');
child.stdin.write(' if(cred~/^"/) { cred = substr(cred,2,length(cred)-2); }');
child.stdin.write(' username=substr(cred,0,index(cred,":")-1);');
child.stdin.write(' password=substr(cred,1+index(cred,":"));');
child.stdin.write(' }');
child.stdin.write(' }');
child.stdin.write(' if(enabled=="yes" && proxy!="") ');
child.stdin.write(' {');
child.stdin.write(' if(username=="" || password=="") ');
child.stdin.write(' {');
child.stdin.write(' print proxy;');
child.stdin.write(' }');
child.stdin.write(' else ');
child.stdin.write(' {');
child.stdin.write(' split(proxy,dummy, "://");');
child.stdin.write(' printf "%s://%s:%s@%s", dummy[1], username, password, dummy[2];');
child.stdin.write(' }');
child.stdin.write(' }');
child.stdin.write("}'\nexit\n");
child.waitExit();
if (child.stdout.str.trim() != "")
if (child.stdout.str.trim() != '') { return (child.stdout.str.trim()); }
}
if(require('fs').existsSync('/etc/login.conf'))
{
var child = require('child_process').execFile('/bin/sh', ['sh']);
child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
child.stdin.write("cat /etc/login.conf | tr '\\n' '`' | awk -F'`' '");
child.stdin.write('{');
child.stdin.write(' printf "{";');
child.stdin.write(' group=""; first=1; firstprop=0;')
child.stdin.write(' for(i=1;i<NF;++i) ');
child.stdin.write(' {');
child.stdin.write(' a=split($i,tok,":"); ');
child.stdin.write(' if(split(tok[1],dummy,"#")==1 && split(tok[1],dummy2," ")==1)');
child.stdin.write(' { ');
child.stdin.write(' if(group != "") { printf "}"; }');
child.stdin.write(' group = tok[1]; firstprop=1;');
child.stdin.write(' printf "%s\\"%s\\": {", (first==0?",":""), tok[1];');
child.stdin.write(' first=0;');
child.stdin.write(' }');
child.stdin.write(' else ');
child.stdin.write(' {');
child.stdin.write(' if(group != "" && split($i,dummy3,"\\\\")>1 && split($i, dummy4, "#")==1)');
child.stdin.write(' {');
child.stdin.write(' if(split($i,key1,"=")==1)');
child.stdin.write(' {');
child.stdin.write(' split($i,key2,":");');
child.stdin.write(' if(key2[2]!="\\\\")');
child.stdin.write(' {');
child.stdin.write(' printf "%s\\"%s\\": null",(firstprop==0?",":""),key2[2];');
child.stdin.write(' firstprop=0;')
child.stdin.write(' }');
child.stdin.write(' }');
child.stdin.write(' else');
child.stdin.write(' {');
child.stdin.write(' tmp = substr($i,2+length(key1[1]));');
child.stdin.write(' split(tmp,dummy,"\\\\");');
child.stdin.write(' tmp=substr(tmp,0,length(tmp)-2);');
child.stdin.write(' split(key1[1],keyname,":");');
child.stdin.write(' printf "%s\\"%s\\": \\"%s\\"", (firstprop==0?",":""), keyname[2], tmp;');
child.stdin.write(' firstprop=0;');
child.stdin.write(' }');
child.stdin.write(' }');
child.stdin.write(' }');
child.stdin.write(' }');
child.stdin.write(' if(group!="") { printf "}"; }')
child.stdin.write(' printf "}";');
child.stdin.write("}'");
child.stdin.write('\nexit\n');
child.waitExit();
if (child.stdout.str.trim() != '')
{
// Enabled
child = require('child_process').execFile('/bin/sh', ['sh']);
child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
child.stderr.on('data', function (c) { console.log(c.toString()); });
child.stdin.write('cat /etc/sysconfig/proxy | grep _PROXY | ' + "tr '\\n' '`' | awk -F'`' '{");
child.stdin.write('for(i=1;i<NF;++i) { if(split($i,r,"HTTP_PROXY=")>1 || split($i,r,"HTTPS_PROXY=")>1) {');
child.stdin.write('cl=split($i,c,"#");');
child.stdin.write('split($i,px,"\\""); split(px[2],pxx,"://"); if(pxx[2]!="" && cl==1) { print pxx[2]; break; }');
child.stdin.write('} }');
child.stdin.write("}'\nexit\n");
child.waitExit();
if (child.stdout.str.trim() != '') { return (child.stdout.str.trim()); }
var config = null;
try
{
config = JSON.parse(child.stdout.str);
}
catch (e)
{
}
if(config)
{
// check root
if(config.root && config.root.setenv)
{
var i, tokens;
var items = config.root.setenv.split(',');
for(i=0;i<items.length;++i)
{
tokens = items[i].split('=');
if(tokens[0] == 'https_proxy' || tokens[0] == 'http_proxy')
{
return (tokens[1].trim());
}
}
}
// check default
if (config.default && config.default.setenv)
{
var i, tokens;
var items = config.default.setenv.split(',');
for (i = 0; i < items.length; ++i)
{
tokens = items[i].split('=');
if (tokens[0] == 'https_proxy' || tokens[0] == 'http_proxy')
{
return (tokens[1].trim());
}
}
}
}
}
}
throw ('No proxies');
}
function posix_proxyCheck(uid, checkAddr)
@@ -136,48 +338,50 @@ function posix_proxyCheck(uid, checkAddr)
return (false);
}
function windows_proxyCheck(key, checkAddr)
function windows_getUserRegistryKey()
{
if(!key)
var i;
if ((i = require('user-sessions').getProcessOwnerName(process.pid)).tsid == 0)
{
var i;
// Key wasn't specified, so lets try to figure it out
if((i=require('user-sessions').getProcessOwnerName(process.pid)).tsid == 0)
// We are a service, so we should check the user that installed the Mesh Agent
try
{
// We are a service, so we should check the user that installed the Mesh Agent
key = require('win-registry').QueryKey(require('win-registry').HKEY.LocalMachine, 'SYSTEM\\CurrentControlSet\\Services\\Mesh Agent', '_InstalledBy');
}
catch (xx)
{
// This info isn't available, so let's try to use the currently logged in user
try
{
key = require('win-registry').QueryKey(require('win-registry').HKEY.LocalMachine, 'SYSTEM\\CurrentControlSet\\Services\\Mesh Agent', '_InstalledBy');
key = require('win-registry').usernameToUserKey(require('user-sessions').getUsername(require('user-sessions').consoleUid()));
}
catch(xx)
catch (xxx)
{
// This info isn't available, so let's try to use the currently logged in user
try
// No users are logged in, so as a last resort, let's try the last logged in user.
var entries = require('win-registry').QueryKey(require('win-registry').HKEY.Users);
for (i in entries.subkeys)
{
key = require('win-registry').usernameToUserKey(require('user-sessions').getUsername(require('user-sessions').consoleUid()));
}
catch(xxx)
{
// No users are logged in, so as a last resort, let's try the last logged in user.
var entries = require('win-registry').QueryKey(require('win-registry').HKEY.Users);
for(i in entries.subkeys)
if (entries.subkeys[i].split('-').length > 5 && !entries.subkeys[i].endsWith('_Classes'))
{
if(entries.subkeys[i].split('-').length>5 && !entries.subkeys[i].endsWith('_Classes'))
{
key = entries.subkeys[i];
break;
}
key = entries.subkeys[i];
break;
}
}
}
}
else
{
// We are a logged in user
key = require('win-registry').usernameToUserKey(i.name);
}
if(!key) {throw('Could not determine which user proxy setting to query');}
}
else
{
// We are a logged in user
key = require('win-registry').usernameToUserKey(i.name);
}
if (!key) { throw ('Could not determine which user proxy setting to query'); }
return (key);
}
function windows_proxyCheck(key, checkAddr)
{
if (!key) { key = windows_getUserRegistryKey(); }
var proxyOverride = require('win-registry').QueryKey(require('win-registry').HKEY.Users, key + '\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings', 'ProxyOverride').split(';');
for(var i in proxyOverride)
{
@@ -190,6 +394,81 @@ function windows_proxyCheck(key, checkAddr)
return (false);
}
function macos_getProxy()
{
var child = require('child_process').execFile('/bin/sh', ['sh']);
child.stdout.str = ''; child.stdout.on('data', function (c) { this.str += c.toString(); });
child.stderr.str = ''; child.stderr.on('data', function (c) { this.str += c.toString(); });
child.stdin.write("scutil --proxy | tr '\\n' '`' | awk -F'`' '");
child.stdin.write('{');
child.stdin.write(' pstart=0;')
child.stdin.write(' for(i=1;i<NF;++i)');
child.stdin.write(" {");
child.stdin.write(' if(split($i,dummy,"ExceptionsList ")>1)');
child.stdin.write(" {");
child.stdin.write(' printf "{ \\"exceptions\\": [";');
child.stdin.write(' ++i;');
child.stdin.write(' fstart=1; pstart=1;');
child.stdin.write(' for(;i<NF;++i)');
child.stdin.write(' {');
child.stdin.write(' if(split($i,dummy,"}")>1) { break; } ');
child.stdin.write(' split($i, val, " : ");');
child.stdin.write(' printf "%s\\"%s\\"", (fstart==0?",":""), val[2];');
child.stdin.write(' fstart=0;');
child.stdin.write(' }');
child.stdin.write(' printf "]";');
child.stdin.write(' continue;');
child.stdin.write(" }");
child.stdin.write(' else');
child.stdin.write(' {');
child.stdin.write(' if(pstart==1 && split($i,dummy,"}")==1)');
child.stdin.write(' {');
child.stdin.write(' split($i,tok," : ");');
child.stdin.write(' split(tok[1],key," ");');
child.stdin.write(' printf ",\\"%s\\": \\"%s\\"", key[1], tok[2];');
child.stdin.write(' }');
child.stdin.write(' }')
child.stdin.write(" }");
child.stdin.write(' printf "}";');
child.stdin.write("}'\nexit\n");
child.waitExit();
if(child.stdout.str != '')
{
try
{
var p = JSON.parse(child.stdout.str);
if(p.HTTPEnable == "1")
{
return('http://' + p.HTTPProxy + ':' + p.HTTPPort);
}
}
catch(e)
{
console.log(e);
}
}
throw ('No Proxies');
}
function windows_getProxy()
{
var isroot = false;
var key, value;
key = windows_getUserRegistryKey();
try
{
if (require('win-registry').QueryKey(require('win-registry').HKEY.Users, key + '\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings', 'ProxyEnable') == 1)
{
// Proxy is enabled
return (require('win-registry').QueryKey(require('win-registry').HKEY.Users, key + '\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings', 'ProxyServer'));
}
}
catch(e)
{
throw ('No proxies');
}
}
switch (process.platform)
{
case 'linux':
@@ -197,8 +476,9 @@ switch (process.platform)
module.exports = { ignoreProxy: posix_proxyCheck, getProxy: linux_getProxy };
break;
case 'win32':
module.exports = { ignoreProxy: windows_proxyCheck };
module.exports = { ignoreProxy: windows_proxyCheck, getProxy: windows_getProxy };
break;
case 'darwin':
module.exports = { getProxy: macos_getProxy };
break;
}