public override void Activate(ProxyEntry proxy, Guid networkId)
        {
            string key1 = "HKEY_CURRENT_USER\\Software\\TortoiseSVN\\Servers\\global";
            string key2 = "HKEY_CURRENT_USER\\Software\\Tigris.org\\Subversion\\Servers\\global";

            RegistryHelper.SetStringValue(key1, "http-proxy-exceptions", proxy.Exceptions);
            RegistryHelper.SetStringValue(key2, "http-proxy-exceptions", proxy.Exceptions);

            RegistryHelper.SetStringValue(key1, "http-proxy-host", proxy.Url.FirstEntry());
            RegistryHelper.SetStringValue(key2, "http-proxy-host", proxy.Url.FirstEntry());

            RegistryHelper.SetStringValue(key1, "http-proxy-port", proxy.Port.FirstEntry());
            RegistryHelper.SetStringValue(key2, "http-proxy-port", proxy.Port.FirstEntry());

            if (proxy.RequiresAuthentication)
            {
                RegistryHelper.SetStringValue(key1, "http-proxy-username", proxy.AuthenticationUsername);
                RegistryHelper.SetStringValue(key2, "http-proxy-username", proxy.AuthenticationUsername);

                RegistryHelper.SetStringValue(key1, "http-proxy-password", proxy.AuthenticationPassword);
                RegistryHelper.SetStringValue(key2, "http-proxy-password", proxy.AuthenticationPassword);
            }
            else
            {
                RegistryHelper.SetStringValue(key1, "http-proxy-username", string.Empty);
                RegistryHelper.SetStringValue(key2, "http-proxy-username", string.Empty);

                RegistryHelper.SetStringValue(key1, "http-proxy-password", string.Empty);
                RegistryHelper.SetStringValue(key2, "http-proxy-password", string.Empty);
            }
        }
 public override void ValidateEntry(ProxyEntry proxy)
 {
     if (proxy.Exceptions.Contains("/"))
     {
         throw new ProxyValidationException(DefaultResources.ProxyExceptionsError);
     }
 }
示例#3
0
        /// <summary>
        /// Register a proxy value.  This value will be updated upon calls to Load or Refresh for an object of type
        /// T that has the same LoadContext as the passed in item.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value">The instance to register as a proxy</param>
        /// <param name="doLoad">Initiate a load for this item, which will cause it to be updated with new data if a fetch is needed.</param>
        /// <param name="update">A handler to fire when this instance is updated.</param>
        /// <param name="canUseAsInitialValue">True to have this value returned for the default value of a subsequent Load call, assuming no value currently exists for the item. Otherwise this is ignored.</param>
        public void RegisterProxy <T>(T value, bool doLoad, Action <T> update, bool canUseAsInitialValue) where T : ILoadContextItem, new()
        {
            if (value == null || value.LoadContext == null)
            {
                throw new ArgumentNullException();
            }

            ProxyEntry pe = new ProxyEntry {
                LoadContext    = value.LoadContext,
                ObjectType     = typeof(T),
                ProxyReference = new WeakReference(value),
                UpdateAction   = () =>
                {
                    if (update != null)
                    {
                        update(value);
                    }
                },
                UseAsInitialValue = canUseAsInitialValue
            };

            AddProxy(pe);

            if (doLoad)
            {
                DataManager.Current.Load <T>(value.LoadContext);
            }
        }
示例#4
0
        protected override async Task <HttpClientEntry> CreateAsync(Request request)
        {
            var        host = request.RequestUri.Host;
            string     clientName;
            ProxyEntry proxy = null;

            if (_proxyService != null)
            {
                proxy = await _proxyService.GetAsync(request.Timeout);

                if (proxy == null)
                {
                    throw new SpiderException("获取代理失败");
                }

                // todo: uri should contains user/password
                clientName = $"{Consts.ProxyPrefix}{proxy.Uri}";
            }
            else
            {
                clientName = host;
            }

            var httpClient = HttpClientFactory.CreateClient(clientName);

            return(new HttpClientEntry(httpClient, proxy));
        }
示例#5
0
        public override void Activate(ProxyEntry proxy, Guid networkId)
        {
            IniHelper helper = new IniHelper(GetOperaIniFile());

            if (proxy.IsAutoConf)
            {
                helper.SetValue("Proxy", "Automatic Proxy Configuration URL", proxy.Url.FirstEntry());
                helper.SetValue("Proxy", "Use Automatic Proxy Configuration", "1");
            }
            else
            {
                if (proxy.Url.IsAllSet)
                {
                    helper.SetValue("Proxy", "HTTP server", proxy.Url[ProxyScheme.All] + ":" + proxy.Port[ProxyScheme.All].ToString());
                    helper.SetValue("Proxy", "HTTPS server", proxy.Url[ProxyScheme.All] + ":" + proxy.Port[ProxyScheme.All].ToString());
                    helper.SetValue("Proxy", "Use HTTP", "1");
                    helper.SetValue("Proxy", "Use HTTPS", "1");
                }
                else
                {
                    if (proxy.Url.ContainsKey(ProxyScheme.HTTP))
                    {
                        helper.SetValue("Proxy", "HTTP server", proxy.Url[ProxyScheme.HTTP] + ":" + proxy.Port[ProxyScheme.HTTP].ToString());
                        helper.SetValue("Proxy", "Use HTTP", "1");
                    }
                    if (proxy.Url.ContainsKey(ProxyScheme.HTTPS))
                    {
                        helper.SetValue("Proxy", "HTTPS server", proxy.Url[ProxyScheme.HTTPS] + ":" + proxy.Port[ProxyScheme.HTTPS].ToString());
                        helper.SetValue("Proxy", "Use HTTPS", "1");
                    }
                    if (proxy.Url.ContainsKey(ProxyScheme.FTP))
                    {
                        helper.SetValue("Proxy", "FTP server", proxy.Url[ProxyScheme.FTP] + ":" + proxy.Port[ProxyScheme.FTP].ToString());
                        helper.SetValue("Proxy", "Use FTP", "1");
                    }
                }

                if (String.IsNullOrEmpty(proxy.Exceptions))
                {
                    helper.SetValue("Proxy", "No Proxy Servers Check", "0");
                }
                else
                {
                    helper.SetValue("Proxy", "No Proxy Servers", proxy.Exceptions);
                    helper.SetValue("Proxy", "No Proxy Servers Check", "1");
                }

                if (proxy.ByPassLocal)
                {
                    helper.SetValue("Proxy", "Use Proxy On Local Names Check", "0");
                }
                else
                {
                    helper.SetValue("Proxy", "Use Proxy On Local Names Check", "1");
                }
            }

            helper.Save();
        }
示例#6
0
        /// <summary>
        /// Shows the input etry window with the given model
        /// </summary>
        /// <param name="model">Model to bind to</param>
        private void ShowProxyEntry(ProxyEntryInformation model)
        {
            ProxyEntry dialog = new ProxyEntry(model);

            // Attach event
            dialog.OnProxyEntered += dialog_OnProxyEntered;
            // Show window
            dialog.ShowModal();
        }
示例#7
0
        private void RemoveProxy(ProxyEntry pe)
        {
            List <ProxyEntry> proxyList;

            if (_proxies.TryGetValue(pe.LoadContext, out proxyList))
            {
                proxyList.Remove(pe);
            }
        }
        protected ISourceProxy GetProxy()
        {
            ProxyEntry proxyEntry = proxies[count - 1];

            if (proxyEntry == null)
            {
                return(null);
            }

            return(proxyEntry.Proxy);
        }
        protected IModifiable GetModifiable()
        {
            ProxyEntry proxyEntry = proxies[count - 1];

            if (proxyEntry == null)
            {
                return(null);
            }

            return(proxyEntry.Proxy as IModifiable);
        }
        protected IObtainable GetObtainable()
        {
            ProxyEntry proxyEntry = proxies[count - 1];

            if (proxyEntry == null)
            {
                return(null);
            }

            return(proxyEntry.Proxy as IObtainable);
        }
        public override void Activate(ProxyEntry entry, Guid networkId)
        {
            string proxy = entry.Url.FirstEntry() + ":" + entry.Port.FirstEntry().ToString();
            string sid   = System.Security.Principal.WindowsIdentity.GetCurrent().User.Value;

            if (!entry.IsAutoConf) //only if not autoconf. autoconf is set in enable/disableProxy
            {
                RegistryHelper.SetStringValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings", "ProxyServer", proxy);
                RegistryHelper.SetStringValue(@"HKEY_USERS\" + sid + @"\Software\Microsoft\Windows\CurrentVersion\Internet Settings", "ProxyServer", proxy);

                if (entry.ByPassLocal || !String.IsNullOrEmpty(entry.Exceptions))
                {
                    string byPassString = entry.Exceptions;

                    if (entry.ByPassLocal)
                    {
                        if (byPassString.Length != 0)
                        {
                            byPassString += ";<local>";
                        }
                        else
                        {
                            byPassString = "<local>";
                        }
                    }

                    RegistryHelper.SetStringValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings", "ProxyOverride", byPassString);
                    RegistryHelper.SetStringValue(@"HKEY_USERS\" + sid + @"\Software\Microsoft\Windows\CurrentVersion\Internet Settings", "ProxyOverride", byPassString);
                }
                else
                {
                    RegistryHelper.DeleteEntry(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings", "ProxyOverride");
                    RegistryHelper.DeleteEntry(@"HKEY_USERS\" + sid + @"\Software\Microsoft\Windows\CurrentVersion\Internet Settings", "ProxyOverride");
                }
            }


            if (!entry.IsAutoConf)
            {
                RegistryHelper.SetDWordValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings", "ProxyEnable", 1);
                RegistryHelper.SetDWordValue(@"HKEY_USERS\" + sid + @"\Software\Microsoft\Windows\CurrentVersion\Internet Settings", "ProxyEnable", 1);
            }
            else
            {
                RegistryHelper.SetStringValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings", "AutoConfigURL", entry.Url.FirstEntry());
                RegistryHelper.SetStringValue(@"HKEY_USERS\" + sid + @"\Software\Microsoft\Windows\CurrentVersion\Internet Settings", "AutoConfigURL", entry.Url.FirstEntry());
            }

            RefreshIESettings();
        }
示例#12
0
        /// <summary>
        /// Recupera o indice do item na coleção.
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public int IndexOf(TProxy item)
        {
            if (_isDisposed)
            {
                return(-1);
            }
            CheckDisposed();
            var item2 = new ProxyEntry(item, 0);

            for (var i = 0; i < _proxyCollection.Count; i++)
            {
                if (ProxyEntryEqualityComparer.Instance.Equals(_proxyCollection[i], item2))
                {
                    return(i);
                }
            }
            return(-1);
        }
示例#13
0
        public override void Activate(ProxyEntry proxy, Guid networkId)
        {
            string file = GetProfileFolder(networkId);

            // all
            if (String.IsNullOrEmpty(GetProfileToSwitch(networkId)))
            {
                foreach (string profPath in GetAllProfiles(networkId))
                {
                    file = Path.Combine(file, profPath);
                    file = Path.Combine(file, "prefs.js");
                    EnableProxy(file, proxy);
                }
            }
            else
            {
                file = Path.Combine(file, GetProfileToSwitch(networkId));
                file = Path.Combine(file, "prefs.js");
                EnableProxy(file, proxy);
            }
        }
        public override ProxyEntry GetDefaultProxy()
        {
            byte[] binValue = (byte[])RegistryHelper.GetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Connections", "DefaultConnectionSettings");

            ProxyEntry proxy = new ProxyEntry();

            proxy.IsAutoConf = (binValue[8] == (byte)05);

            List <byte> proxyUrlPortBytes = new List <byte>();
            var         length            = binValue[12] + 16;

            for (int i = 16; i < length; i++)
            {
                proxyUrlPortBytes.Add(binValue[i]);
            }

            string val       = Encoding.Default.GetString(proxyUrlPortBytes.ToArray());
            int    httpIndex = val.IndexOf("http=");

            if (httpIndex > 0)
            {
                int endIndex = val.IndexOf(";", httpIndex + 1);
                val = val.Substring(httpIndex + "http=".Length, endIndex - httpIndex - "http=".Length);
            }
            string[] urlPort = val.Split(':');
            if (urlPort[0].Contains("="))
            {
                return(proxy);
            }

            proxy.Url[ProxyScheme.All] = urlPort[0];
            int port;

            if (urlPort.Length > 1 && int.TryParse(urlPort[1], out port))
            {
                proxy.Port[ProxyScheme.All] = port;
            }

            return(proxy);
        }
示例#15
0
        private void AddProxy(ProxyEntry pe)
        {
            List <ProxyEntry> proxyList;

            if (!_proxies.TryGetValue(pe.LoadContext, out proxyList))
            {
                proxyList = new List <ProxyEntry>();
                _proxies[pe.LoadContext] = proxyList;
            }

            var existingProxy = from p in proxyList
                                where p.ProxyReference.Target == pe.ProxyReference.Target
                                select p;

            if (!existingProxy.Any())
            {
                proxyList.Add(pe);
            }
            else
            {
                //  throw new ArgumentException("Proxy already added for object " + pe.ObjectType.Name);
            }
        }
示例#16
0
        public override ProxyEntry GetDefaultProxy()
        {
            ProxyEntry proxy = new ProxyEntry();

            IniHelper helper = new IniHelper(GetOperaIniFile());

            proxy.IsAutoConf = (helper.GetValue("Proxy", "Use Automatic Proxy Configuration") == "1");
            if (proxy.IsAutoConf)
            {
                proxy.Url[ProxyScheme.All] = helper.GetValue("Proxy", "Automatic Proxy Configuration URL");
            }
            else
            {
                string[] urlPort = helper.GetValue("Proxy", "HTTP server").Split(':');
                proxy.Url[ProxyScheme.All] = urlPort[0];
                int port;
                if (urlPort.Length > 1 && int.TryParse(urlPort[1], out port))
                {
                    proxy.Port[ProxyScheme.All] = port;
                }
            }

            return(proxy);
        }
示例#17
0
        /// <summary>
        /// Método acioando quando a coleção adaptada sofrer alguma alteração.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void InnerCollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            var          collection       = sender as Colosoft.Collections.IObservableCollection <T>;
            var          newStartingIndex = e.NewStartingIndex < 0 ? 0 : e.NewStartingIndex;
            var          oldStartingIndex = e.OldStartingIndex < 0 ? 0 : e.OldStartingIndex;
            ProxyMonitor monitor          = null;

            switch (e.Action)
            {
            case System.Collections.Specialized.NotifyCollectionChangedAction.Add:
                monitor = new ProxyMonitor(this);
                try
                {
                    for (int i = 0; i < e.NewItems.Count; i++)
                    {
                        _proxyCollection.Insert(newStartingIndex + i, new ProxyEntry(_proxyCreator((T)e.NewItems[i]), e.NewItems[i] != null ? e.NewItems[i].GetHashCode() : 0));
                    }
                }
                finally
                {
                    monitor.Free();
                    monitor = null;
                }
                break;

            case System.Collections.Specialized.NotifyCollectionChangedAction.Move:
                monitor = new ProxyMonitor(this);
                try
                {
                    if (e.OldItems.Count == 1)
                    {
                        _proxyCollection.Move(oldStartingIndex, newStartingIndex);
                    }
                    else
                    {
                        var items = _proxyCollection.Skip(oldStartingIndex).Take(e.OldItems.Count).ToList();
                        for (int i = 0; i < e.OldItems.Count; i++)
                        {
                            _proxyCollection.RemoveAt(oldStartingIndex + i);
                        }
                        for (int i = 0; i < items.Count; i++)
                        {
                            _proxyCollection.Insert(newStartingIndex + i, items[i]);
                        }
                    }
                }
                finally
                {
                    monitor.Free();
                    monitor = null;
                }
                break;

            case System.Collections.Specialized.NotifyCollectionChangedAction.Remove:
                monitor = new ProxyMonitor(this);
                try
                {
                    for (int i = 0; i < e.OldItems.Count; i++)
                    {
                        _proxyCollection.RemoveAt(oldStartingIndex + i);
                    }
                }
                finally
                {
                    monitor.Free();
                    monitor = null;
                }
                break;

            case System.Collections.Specialized.NotifyCollectionChangedAction.Replace:
                NotifyCollectionChangedEventArgs e2 = null;
                try
                {
                    _ignoreProxyCollectionChanged = true;
                    _ignoreProxyPropertyChanged   = true;
                    var newItems = new System.Collections.ArrayList();
                    var oldItems = new System.Collections.ArrayList();
                    monitor = new ProxyMonitor(this);
                    try
                    {
                        for (int i = 0; i < e.OldItems.Count; i++)
                        {
                            oldItems.Add(_proxyCollection[oldStartingIndex + i]);
                            _proxyCollection.RemoveAt(oldStartingIndex + i);
                        }
                        for (int i = 0; i < e.NewItems.Count; i++)
                        {
                            var entry = new ProxyEntry(_proxyCreator((T)e.NewItems[i]), e.NewItems[i] != null ? e.NewItems[i].GetHashCode() : 0);
                            newItems.Add(entry.Proxy);
                            _proxyCollection.Insert(newStartingIndex + i, entry);
                        }
                    }
                    finally
                    {
                        monitor.Free();
                        monitor = null;
                    }
                    e2 = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, oldItems[0], newItems[0], e.OldStartingIndex);
                }
                finally
                {
                    _ignoreProxyCollectionChanged = false;
                    _ignoreProxyPropertyChanged   = false;
                }
                OnCollectionChanged(e2);
                break;

            case System.Collections.Specialized.NotifyCollectionChangedAction.Reset:
                try
                {
                    _ignoreProxyCollectionChanged = true;
                    _ignoreProxyPropertyChanged   = true;
                    monitor = new ProxyMonitor(this);
                    try
                    {
                        _proxyCollection.Clear();
                        foreach (T local in collection)
                        {
                            _proxyCollection.Add(new ProxyEntry(_proxyCreator(local), local != null ? local.GetHashCode() : 0));
                        }
                    }
                    finally
                    {
                        monitor.Free();
                        monitor = null;
                    }
                }
                finally
                {
                    _ignoreProxyCollectionChanged = false;
                    _ignoreProxyPropertyChanged   = false;
                }
                OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
                break;

            default:
                break;
            }
            OnPropertyChanged("Count");
            OnPropertyChanged("Item[]");
        }
示例#18
0
    static void GenProxyBin()
    {
        List <List <ProxyEntry> > list = new List <List <ProxyEntry> >();

        for (int i = 0; i < 256; i++)
        {
            list.Add(new List <ProxyEntry>());
        }


        Console.WriteLine("Reading...");

        string       line;
        StreamReader temp = new StreamReader(PROXYFILE);

        while ((line = temp.ReadLine()) != null)   //total

        {
            string[] split = line.Split(new string[] { "\",\"" }, StringSplitOptions.None);
            for (int i = 0; i < split.Length; i++)
            {
                if (split[i].StartsWith("\""))
                {
                    split[i] = split[i].Substring(1);
                }
                if (split[i].EndsWith("\""))
                {
                    split[i] = split[i].Substring(0, split[i].Length - 1);
                }
            }

            uint   a      = UInt32.Parse(split[0]);
            uint   b      = UInt32.Parse(split[1]);
            byte[] aBytes = BitConverter.GetBytes(a);
            byte[] bBytes = BitConverter.GetBytes(b);
            Array.Reverse(aBytes);
            Array.Reverse(bBytes);

            if (aBytes[0] == bBytes[0])
            {
                ProxyEntry entry = new ProxyEntry();
                entry.from = aBytes;
                entry.to   = bBytes;
                list[aBytes[0]].Add(entry);
            }
            else
            {
                for (int i = aBytes[0]; i <= bBytes[0]; i++)
                {
                    byte[] from;
                    byte[] to;

                    if (i == aBytes[0])
                    {
                        from = new byte[] { aBytes[0], aBytes[1], aBytes[2], aBytes[3] };
                        to   = new byte[] { (byte)i, 255, 255, 255 };
                    }
                    else if (i == bBytes[0])
                    {
                        from = new byte[] { bBytes[0], 0, 0, 0 };
                        to   = new byte[] { bBytes[0], bBytes[1], bBytes[2], bBytes[3] };
                    }
                    else
                    {
                        from = new byte[] { aBytes[0], aBytes[1], aBytes[2], aBytes[3] };
                        to   = new byte[] { bBytes[0], bBytes[1], bBytes[2], bBytes[3] };
                    }

                    ProxyEntry entry = new ProxyEntry()
                    {
                        from = from,
                        to   = to
                    };

                    list[i].Add(entry);
                }
            }
        }

        DirectoryInfo dirProxy = new DirectoryInfo(PROXYDIR);

        if (!dirProxy.Exists)
        {
            dirProxy.Create();
        }

        for (int i = 0; i < list.Count; i++)
        {
            if (list[i].Count == 0)
            {
                continue;
            }

            Console.Write(i);

            FileStream   s = new FileStream($"{PROXYDIR}\\{i}.bin", FileMode.OpenOrCreate);
            BinaryWriter w = new BinaryWriter(s);

            for (int j = 0; j < list[i].Count; j++)
            {
                w.Write(list[i][j].from[3]);
                w.Write(list[i][j].from[2]);
                w.Write(list[i][j].from[1]);

                w.Write(list[i][j].to[3]);
                w.Write(list[i][j].to[2]);
                w.Write(list[i][j].to[1]);
            }

            w.Close();
            s.Close();

            Console.WriteLine(": done");
        }
    }
        public override void Activate(ProxyEntry proxy, Guid networkId)
        {
            string prx = string.Empty;

            if (proxy.Url.IsAllSet)
            {
                prx = proxy.Url[ProxyScheme.All] + ":" + proxy.Port[ProxyScheme.All].ToString();
            }
            else
            {
                foreach (var scheme in proxy.Url.Keys)
                {
                    prx += String.Format("{0}={1}:{2};", scheme.ToString().ToLower(), proxy.Url[scheme], proxy.Port[scheme]);
                }
            }

            string sid = System.Security.Principal.WindowsIdentity.GetCurrent().User.Value;

            // 01=disabled, 03=enabled, 05=auto config, 09=auto detect, 0D=auto config und auto detect
            byte enabled = (byte)03;

            if (proxy.IsAutoConf && proxy.IsAutoDetect)
            {
                enabled = (byte)13; //13=0d
            }
            else if (proxy.IsAutoConf)
            {
                enabled = (byte)05;
            }
            else if (proxy.IsAutoDetect)
            {
                enabled = (byte)09;
            }

            byte[] proxyBytes  = Encoding.Default.GetBytes(prx);
            byte   entryLength = (byte)proxyBytes.Length;

            if (proxy.IsAutoConf)
            {
                proxyBytes  = new byte[0];
                entryLength = 0;
            }

            byte[] configStart = new byte[] { 70, 00, 00, 00, 01, 00, 00, 03, enabled, 00, 00, 00, entryLength, 00, 00, 00 };

            string byPassString = string.Empty;

            if (proxy.ByPassLocal || !String.IsNullOrEmpty(proxy.Exceptions))
            {
                byPassString = proxy.Exceptions;

                if (proxy.ByPassLocal)
                {
                    if (byPassString.Length != 0)
                    {
                        byPassString += ";<local>";
                    }
                    else
                    {
                        byPassString = "<local>";
                    }
                }
            }

            byte[] exceptions = Encoding.Default.GetBytes(byPassString);

            int autoConfigUrlArrayLength = 0;

            byte[] autoConfigUrl = new byte[0];
            if (proxy.IsAutoConf)
            {
                autoConfigUrl            = Encoding.Default.GetBytes(proxy.Url.FirstEntry());
                autoConfigUrlArrayLength = autoConfigUrl.Length;
            }

            int lastPosition = 0;

            byte[] merged = new byte[configStart.Length + proxyBytes.Length + 4 + exceptions.Length + 4 + autoConfigUrlArrayLength + 31];

            configStart.CopyTo(merged, lastPosition);
            lastPosition = configStart.Length;

            proxyBytes.CopyTo(merged, lastPosition);
            lastPosition += proxyBytes.Length;

            if (exceptions.Length > 255)
            {
                //length is 379. in hex: 17B. muss in der reg als 17 und 0B eingetragen werden
                //int l1 = exceptions.Length - 356;
                //int l2 = 11;
                //new byte[] { (byte)l1, (byte)l2, 0, 0 }.CopyTo(merged, lastPosition);
            }
            else
            {
                new byte[] { (byte)exceptions.Length, 0, 0, 0 }.CopyTo(merged, lastPosition);
            }
            lastPosition += 4;

            exceptions.CopyTo(merged, lastPosition);
            lastPosition += exceptions.Length;

            new byte[] { (byte)autoConfigUrl.Length, 0, 0, 0 }.CopyTo(merged, lastPosition);
            lastPosition += 4;

            if (proxy.IsAutoConf)
            {
                autoConfigUrl.CopyTo(merged, lastPosition);
                lastPosition += autoConfigUrl.Length;
            }

            new byte[31].CopyTo(merged, lastPosition);


            if (UseDialUp(networkId))
            {
                string connectionName = GetDialUpName(networkId);
                RegistryHelper.SetBinaryValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Connections", connectionName, merged);
            }
            else
            {
                RegistryHelper.SetBinaryValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Connections", "DefaultConnectionSettings", merged);
            }

            RefreshIESettings();
        }
        public override void Activate(ProxyEntry proxy, Guid networkId)
        {
            string prx = string.Empty;

            if (proxy.Url.IsAllSet)
            {
                prx = proxy.Url[ProxyScheme.All] + ":" + proxy.Port[ProxyScheme.All].ToString();
            }
            else
            {
                foreach (var scheme in proxy.Url.Keys)
                {
                    prx += String.Format("{0}={1}:{2};", scheme.ToString().ToLower(), proxy.Url[scheme], proxy.Port[scheme]);
                }
            }

            string sid = System.Security.Principal.WindowsIdentity.GetCurrent().User.Value;

            // 01=disabled, 03=enabled, 05=auto config, 09=auto detect, 0b=auto detect and manual proxy, 0D=auto config und auto detect
            byte enabled = (byte)03;

            if (proxy.IsAutoDetect && !String.IsNullOrEmpty(prx))
            {
                enabled = (byte)11; //11=0b
            }
            else if (proxy.IsAutoConf && proxy.IsAutoDetect)
            {
                enabled = (byte)13; //13=0d
            }
            else if (proxy.IsAutoConf)
            {
                enabled = (byte)05;
            }
            else if (proxy.IsAutoDetect)
            {
                enabled = (byte)09;
            }
            //Convert Proxy Addresses to Bytes
            byte[] proxyBytes  = Encoding.Default.GetBytes(prx);
            byte   entryLength = (byte)proxyBytes.Length;

            if (proxy.IsAutoConf)
            {
                proxyBytes  = new byte[0];
                entryLength = 0;
            }

            byte[] configStart = new byte[] { 70, 00, 00, 00, 01, 00, 00, 03, enabled, 00, 00, 00, entryLength, 00, 00, 00 };

            string byPassString = string.Empty;

            if (proxy.ByPassLocal || !String.IsNullOrEmpty(proxy.Exceptions))
            {
                byPassString = proxy.Exceptions;

                if (proxy.ByPassLocal)
                {
                    if (byPassString.Length != 0)
                    {
                        byPassString += ";<local>";
                    }
                    else
                    {
                        byPassString = "<local>";
                    }
                }
            }
            //Convert Exceptions to Bytes
            byte[] exceptions = Encoding.Default.GetBytes(byPassString);

            int autoConfigUrlArrayLength = 0;

            byte[] autoConfigUrl = new byte[0];
            if (proxy.IsAutoConf)
            {
                autoConfigUrl            = Encoding.Default.GetBytes(proxy.Url.FirstEntry());
                autoConfigUrlArrayLength = autoConfigUrl.Length;
            }

            int lastPosition = 0;

            //Set Merged
            byte[] merged = new byte[configStart.Length + proxyBytes.Length + 4 + exceptions.Length + 4 + autoConfigUrlArrayLength + 31];

            //Add ConfigStart to Merged
            configStart.CopyTo(merged, lastPosition);
            lastPosition = configStart.Length;

            //Add ProxyServers to Merged
            proxyBytes.CopyTo(merged, lastPosition);
            lastPosition += proxyBytes.Length;
            //Convert exceptions string length to Hex Values
            string hexString = exceptions.Length.ToString("x");

            //first character should be 0 if string is not even length
            hexString = (hexString.Length % 2 == 0 ? "" : "0") + hexString;
            //Convert Hex String to Byte Array
            int NumberChars = hexString.Length;

            byte[] bytes = new byte[NumberChars / 2];
            for (int i = 0; i < NumberChars; i += 2)
            {
                bytes[i / 2] = Convert.ToByte(hexString.Substring(i, 2), 16);
            }
            //Reverse Byte Array
            Array.Reverse(bytes);
            Array.Resize(ref bytes, 4);

            bytes.CopyTo(merged, lastPosition);
            lastPosition += 4;

            //Add Exceptions to Merged
            exceptions.CopyTo(merged, lastPosition);
            lastPosition += exceptions.Length;


            //Add AutoConfigURL to Merged
            new byte[] { (byte)autoConfigUrl.Length, 0, 0, 0 }.CopyTo(merged, lastPosition);
            lastPosition += 4;

            if (proxy.IsAutoConf)
            {
                autoConfigUrl.CopyTo(merged, lastPosition);
                lastPosition += autoConfigUrl.Length;
            }

            new byte[31].CopyTo(merged, lastPosition);


            if (UseDialUp(networkId))
            {
                string connectionName = GetDialUpName(networkId);
                RegistryHelper.SetBinaryValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Connections", connectionName, merged);
            }
            else
            {
                RegistryHelper.SetBinaryValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Connections", "DefaultConnectionSettings", merged);
            }

            RefreshIESettings();
        }
        void Bind(object source, PathToken token)
        {
            int          index = token.Index;
            ISourceProxy proxy = factory.Create(source, token);

            if (proxy == null)
            {
                var node = token.Current;
                if (node is MemberNode)
                {
                    var    memberNode = node as MemberNode;
                    string typeName   = source != null?source.GetType().Name : memberNode.Type.Name;

                    throw new Exception(string.Format("Not found the member named '{0}' in the '{1}' type", memberNode.Name, typeName));
                }
                throw new Exception("proxy is null.");
            }

            ProxyEntry entry = new ProxyEntry(proxy, token);

            proxies[index] = entry;

            if (token.HasNext())
            {
                if (proxy is INotifiable)
                {
                    entry.Handler = (sender, args) =>
                    {
                        lock (_lock)
                        {
                            try
                            {
                                var proxyEntry = proxies[index];
                                if (proxyEntry == null || sender != proxyEntry.Proxy)
                                {
                                    return;
                                }

                                Rebind(index);
                            }
                            catch (Exception e)
                            {
                                if (log.IsErrorEnabled)
                                {
                                    log.ErrorFormat("{0}", e);
                                }
                            }
                        }
                    };
                }

                var child = (proxy as IObtainable).GetValue();
                if (child != null)
                {
                    Bind(child, token.NextToken());
                }
                else
                {
                    this.RaiseValueChanged();
                }
            }
            else
            {
                if (proxy is INotifiable)
                {
                    entry.Handler = (sender, args) => { this.RaiseValueChanged(); }
                }
                ;
                this.RaiseValueChanged();
            }
        }

        void Rebind(int index)
        {
            for (int i = proxies.Length - 1; i > index; i--)
            {
                ProxyEntry proxyEntry = proxies[i];
                if (proxyEntry == null)
                {
                    continue;
                }

                var proxy = proxyEntry.Proxy;
                proxyEntry.Proxy = null;
                if (proxy != null)
                {
                    proxy.Dispose();
                }
            }

            ProxyEntry entry      = proxies[index];
            var        obtainable = entry.Proxy as IObtainable;

            if (obtainable == null)
            {
                this.RaiseValueChanged();
                return;
            }

            var source = obtainable.GetValue();

            if (source == null)
            {
                this.RaiseValueChanged();
                return;
            }

            Bind(source, entry.Token.NextToken());
        }

        void Unbind()
        {
            for (int i = proxies.Length - 1; i <= 0; i--)
            {
                ProxyEntry proxyEntry = proxies[i];
                if (proxyEntry == null)
                {
                    continue;
                }

                proxyEntry.Dispose();
                proxies[i] = null;
            }
        }
示例#22
0
        private void EnableProxy(string file, ProxyEntry proxy)
        {
            string content = "";

            using (StreamReader sr = new StreamReader(file))
            {
                content = sr.ReadToEnd();
            }

            StringBuilder sb = new StringBuilder();

            using (StringWriter sw = new StringWriter(sb))
            {
                using (StringReader sr = new StringReader(content))
                {
                    while (true)
                    {
                        string line = sr.ReadLine();
                        if (line == null)
                        {
                            break;
                        }
                        if (line.StartsWith("user_pref(\"network.proxy.type"))
                        {
                            continue;
                        }
                        if (line.StartsWith("user_pref(\"network.proxy.autoconfig_url"))
                        {
                            continue;
                        }
                        if (line.StartsWith("user_pref(\"network.proxy.http"))
                        {
                            continue;
                        }
                        if (line.StartsWith("user_pref(\"network.proxy.http_port"))
                        {
                            continue;
                        }
                        if (line.StartsWith("user_pref(\"network.proxy.ssl"))
                        {
                            continue;
                        }
                        if (line.StartsWith("user_pref(\"network.proxy.ssl_port"))
                        {
                            continue;
                        }
                        if (line.StartsWith("user_pref(\"network.proxy.ftp"))
                        {
                            continue;
                        }
                        if (line.StartsWith("user_pref(\"network.proxy.ftp_port"))
                        {
                            continue;
                        }
                        if (line.StartsWith("user_pref(\"network.proxy.socks"))
                        {
                            continue;
                        }
                        if (line.StartsWith("user_pref(\"network.proxy.socks_port"))
                        {
                            continue;
                        }
                        if (line.StartsWith("user_pref(\"network.proxy.no_proxies_on"))
                        {
                            continue;
                        }
                        if (line.StartsWith("user_pref(\"network.proxy.share_proxy_settings"))
                        {
                            continue;
                        }

                        sw.WriteLine(line);
                    }
                }

                if (proxy.IsAutoConf)
                {
                    sw.WriteLine("user_pref(\"network.proxy.autoconfig_url\", \"" + proxy.Url.FirstEntry() + "\");");
                    sw.WriteLine("user_pref(\"network.proxy.type\", 2);");
                }
                else if (proxy.IsAutoDetect)
                {
                    sw.WriteLine("user_pref(\"network.proxy.type\", 4);");
                }
                else
                {
                    if (proxy.Url.IsAllSet)
                    {
                        sw.WriteLine("user_pref(\"network.proxy.http\", \"" + proxy.Url[ProxyScheme.All] + "\");");
                        sw.WriteLine("user_pref(\"network.proxy.http_port\", " + proxy.Port[ProxyScheme.All].ToString() + ");");
                        sw.WriteLine("user_pref(\"network.proxy.ssl\", \"" + proxy.Url[ProxyScheme.All] + "\");");
                        sw.WriteLine("user_pref(\"network.proxy.ssl_port\", " + proxy.Port[ProxyScheme.All].ToString() + ");");
                        sw.WriteLine("user_pref(\"network.proxy.ftp\", \"" + proxy.Url[ProxyScheme.All] + "\");");
                        sw.WriteLine("user_pref(\"network.proxy.ftp_port\", " + proxy.Port[ProxyScheme.All].ToString() + ");");
                        sw.WriteLine("user_pref(\"network.proxy.socks\", \"" + proxy.Url[ProxyScheme.All] + "\");");
                        sw.WriteLine("user_pref(\"network.proxy.socks_port\", " + proxy.Port[ProxyScheme.All].ToString() + ");");
                    }
                    else
                    {
                        if (proxy.Url.ContainsKey(ProxyScheme.HTTP))
                        {
                            sw.WriteLine("user_pref(\"network.proxy.http\", \"" + proxy.Url[ProxyScheme.HTTP] + "\");");
                            sw.WriteLine("user_pref(\"network.proxy.http_port\", " + proxy.Port[ProxyScheme.HTTP].ToString() + ");");
                        }
                        if (proxy.Url.ContainsKey(ProxyScheme.HTTPS))
                        {
                            sw.WriteLine("user_pref(\"network.proxy.ssl\", \"" + proxy.Url[ProxyScheme.HTTPS] + "\");");
                            sw.WriteLine("user_pref(\"network.proxy.ssl_port\", " + proxy.Port[ProxyScheme.HTTPS].ToString() + ");");
                        }
                        if (proxy.Url.ContainsKey(ProxyScheme.FTP))
                        {
                            sw.WriteLine("user_pref(\"network.proxy.ftp\", \"" + proxy.Url[ProxyScheme.FTP] + "\");");
                            sw.WriteLine("user_pref(\"network.proxy.ftp_port\", " + proxy.Port[ProxyScheme.FTP].ToString() + ");");
                        }
                        if (proxy.Url.ContainsKey(ProxyScheme.SOCKS))
                        {
                            sw.WriteLine("user_pref(\"network.proxy.socks\", \"" + proxy.Url[ProxyScheme.SOCKS] + "\");");
                            sw.WriteLine("user_pref(\"network.proxy.socks_port\", " + proxy.Port[ProxyScheme.SOCKS].ToString() + ");");
                        }
                    }
                    string noProxies = proxy.Exceptions;
                    if (proxy.ByPassLocal)
                    {
                        noProxies = "localhost, 127.0.0.1, " + noProxies;
                    }
                    sw.WriteLine("user_pref(\"network.proxy.no_proxies_on\", \"" + noProxies + "\");");
                    sw.WriteLine("user_pref(\"network.proxy.share_proxy_settings\", true);");
                    sw.WriteLine("user_pref(\"network.proxy.type\", 1);");
                }
            }

            using (StreamWriter sw = new StreamWriter(file))
            {
                sw.Write(sb.ToString());
            }
        }