├── .gitignore ├── LICENSE ├── Makefile ├── README.md ├── binaries ├── darwin │ └── sysproxy ├── linux_386 │ └── sysproxy ├── linux_amd64 │ └── sysproxy ├── linux_arm │ └── sysproxy └── windows │ ├── sysproxy_386.exe │ └── sysproxy_amd64.exe ├── common.h ├── linux.c ├── main.c └── windows.c /.gitignore: -------------------------------------------------------------------------------- 1 | *.o 2 | *~ 3 | *.gch 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2015 Brave New Software Project, Inc. 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # This Makefile is GNU make compatible. You can get GNU Make from 2 | # http://gnuwin32.sourceforge.net/packages/make.htm 3 | 4 | CCFLAGS = -Wall -c 5 | 6 | ifeq ($(OS),Windows_NT) 7 | os = windows 8 | CCFLAGS += -D WIN32 9 | # 32 bit `make` utility over 64 bit OS 10 | ifeq ($(PROCESSOR_ARCHITEW6432),AMD64) 11 | CCFLAGS += -D AMD64 12 | BIN = binaries/windows/sysproxy_amd64 13 | else 14 | ifeq ($(PROCESSOR_ARCHITECTURE),AMD64) 15 | CCFLAGS += -D AMD64 16 | BIN = binaries/windows/sysproxy_amd64 17 | endif 18 | ifeq ($(PROCESSOR_ARCHITECTURE),x86) 19 | CCFLAGS += -D IA32 20 | BIN = binaries/windows/sysproxy_386 21 | endif 22 | endif 23 | LDFLAGS += -l rasapi32 -l wininet -Wl,--subsystem,windows 24 | else 25 | UNAME_S := $(shell uname -s) 26 | ifeq ($(UNAME_S),Linux) 27 | os = linux 28 | CCFLAGS += -D LINUX $(shell pkg-config --cflags gio-2.0) 29 | LDFLAGS += $(shell pkg-config --libs gio-2.0) 30 | UNAME_P := $(shell uname -p) 31 | ifeq ($(UNAME_P),x86_64) 32 | CCFLAGS += -D AMD64 33 | BIN = binaries/linux_amd64/sysproxy 34 | endif 35 | ifneq ($(filter %86,$(UNAME_P)),) 36 | CCFLAGS += -D IA32 37 | BIN = binaries/linux_386/sysproxy 38 | endif 39 | ifneq ($(filter arm%,$(UNAME_P)),) 40 | CCFLAGS += -D ARM 41 | BIN = binaries/linux_arm/sysproxy 42 | endif 43 | endif 44 | endif 45 | 46 | CC=gcc 47 | 48 | all: $(BIN) 49 | main.o: main.c common.h 50 | $(CC) $(CCFLAGS) $^ 51 | $(os).o: $(os).c common.h 52 | $(CC) $(CCFLAGS) $^ 53 | $(BIN): $(os).o main.o 54 | $(CC) -o $@ $^ $(LDFLAGS) 55 | 56 | clean: 57 | rm *.o 58 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # sysproxy-cmd 2 | 3 | A command line tool to change HTTP(s) proxy settings of the operating system. 4 | 5 | Binaries included in repo. Simply `make` to build it again, with the important exception of darwin, which uses its own repository and build at https://github.com/getlantern/sysproxy-cmd-darwin. 6 | 7 | Note - you will need to run make separately on each platform. 8 | 9 | # Usage 10 | 11 | ```sh 12 | sysproxy show 13 | sysproxy on 14 | sysproxy off 15 | sysproxy wait-and-cleanup 16 | ``` 17 | 18 | `sysproxy off` and `sysproxy wait-and-cleanup` turns off proxy setting only if the 19 | existing host and port equal . 20 | 21 | `sysproxy wait-and-cleanup` differs from `sysproxy off` in that it waits for input 22 | from stdin (or close) before turning off proxy setting. Any signal or Windows 23 | system shutdown message triggers the cleanup too. 24 | 25 | 26 | # Notes 27 | 28 | * **Mac** 29 | 30 | Setting the system proxy is a privileged action on Mac OS. `sudo` or elevate it 31 | as below. 32 | 33 | There's an additional option to chown itself to root:wheel and add setuid bit. 34 | 35 | ```sh 36 | sysproxy setuid 37 | ``` 38 | 39 | * **Windows** 40 | 41 | Install [MinGW-W64](http://sourceforge.net/projects/mingw-w64) to build sysproxy 42 | as it has up to date SDK headers we require. The make command is `mingw32-make`. 43 | 44 | To avoid bringing up console window, it doesn't show anything directly to 45 | console. Piping the result to other utilities should work. 46 | 47 | ``` 48 | sysproxy show | cat 49 | ``` 50 | 51 | * **Linux** 52 | 53 | `sudo apt-get install libgtk2.0-dev` 54 | -------------------------------------------------------------------------------- /binaries/darwin/sysproxy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/getlantern/sysproxy-cmd/19cb40d0d074a67804d09de89ca1b0da822ad9dd/binaries/darwin/sysproxy -------------------------------------------------------------------------------- /binaries/linux_386/sysproxy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/getlantern/sysproxy-cmd/19cb40d0d074a67804d09de89ca1b0da822ad9dd/binaries/linux_386/sysproxy -------------------------------------------------------------------------------- /binaries/linux_amd64/sysproxy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/getlantern/sysproxy-cmd/19cb40d0d074a67804d09de89ca1b0da822ad9dd/binaries/linux_amd64/sysproxy -------------------------------------------------------------------------------- /binaries/linux_arm/sysproxy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/getlantern/sysproxy-cmd/19cb40d0d074a67804d09de89ca1b0da822ad9dd/binaries/linux_arm/sysproxy -------------------------------------------------------------------------------- /binaries/windows/sysproxy_386.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/getlantern/sysproxy-cmd/19cb40d0d074a67804d09de89ca1b0da822ad9dd/binaries/windows/sysproxy_386.exe -------------------------------------------------------------------------------- /binaries/windows/sysproxy_amd64.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/getlantern/sysproxy-cmd/19cb40d0d074a67804d09de89ca1b0da822ad9dd/binaries/windows/sysproxy_amd64.exe -------------------------------------------------------------------------------- /common.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #ifdef DARWIN 5 | int setUid(); 6 | int elevate(char *path, char *prompt, char *iconPath); 7 | #endif 8 | 9 | extern const char* proxyHost; 10 | extern const char* proxyPort; 11 | 12 | #ifdef _WIN32 13 | void setupSystemShutdownHandler(); 14 | #endif 15 | 16 | int show(); 17 | int toggleProxy(bool turnOn); 18 | 19 | enum RET_ERRORS { 20 | RET_NO_ERROR = 0, 21 | INVALID_FORMAT = 1, 22 | NO_PERMISSION = 2, 23 | SYSCALL_FAILED = 3, 24 | NO_MEMORY = 4 25 | }; 26 | -------------------------------------------------------------------------------- /linux.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include "common.h" 6 | 7 | void init() { 8 | #pragma GCC diagnostic ignored "-Wdeprecated-declarations" 9 | // deprecated since version 2.36, must leave here or prior glib will crash 10 | g_type_init(); 11 | #pragma GCC diagnostic warning "-Wdeprecated-declarations" 12 | } 13 | 14 | int show() 15 | { 16 | init(); 17 | GSettings* setting = g_settings_new("org.gnome.system.proxy"); 18 | GSettings* httpSetting = g_settings_new("org.gnome.system.proxy.http"); 19 | char* oldMode = g_settings_get_string(setting, "mode"); 20 | gboolean oldEnabled = g_settings_get_boolean(httpSetting, "enabled"); 21 | char* oldHost = g_settings_get_string(httpSetting, "host"); 22 | gint oldPort = g_settings_get_int(httpSetting, "port"); 23 | if (oldEnabled && strcmp(oldMode, "manual") == 0) { 24 | printf("%s:%d\n", oldHost, oldPort); 25 | } 26 | return RET_NO_ERROR; 27 | } 28 | 29 | int toggleProxy(bool turnOn) 30 | { 31 | long port = strtol(proxyPort, NULL, 10); 32 | if (port == 0) { 33 | fprintf(stderr, "unable to parse port '%s'\n", proxyPort); 34 | return INVALID_FORMAT; 35 | } 36 | 37 | int ret = RET_NO_ERROR; 38 | init(); 39 | GSettings* setting = g_settings_new("org.gnome.system.proxy"); 40 | GSettings* httpSetting = g_settings_new("org.gnome.system.proxy.http"); 41 | GSettings* httpsSetting = g_settings_new("org.gnome.system.proxy.https"); 42 | if (turnOn == true) { 43 | gboolean success = g_settings_set_string(httpSetting, "host", proxyHost); 44 | if (!success) { 45 | fprintf(stderr, "error setting http host to %s\n", proxyHost); 46 | ret = SYSCALL_FAILED; 47 | goto cleanup; 48 | } 49 | success = g_settings_set_int(httpSetting, "port", port); 50 | if (!success) { 51 | fprintf(stderr, "error setting http port %s\n", proxyPort); 52 | ret = SYSCALL_FAILED; 53 | goto cleanup; 54 | } 55 | success = g_settings_set_string(httpsSetting, "host", proxyHost); 56 | if (!success) { 57 | fprintf(stderr, "error setting https host to %s\n", proxyHost); 58 | ret = SYSCALL_FAILED; 59 | goto cleanup; 60 | } 61 | success = g_settings_set_int(httpsSetting, "port", port); 62 | if (!success) { 63 | fprintf(stderr, "error setting https port %s\n", proxyPort); 64 | ret = SYSCALL_FAILED; 65 | goto cleanup; 66 | } 67 | success = g_settings_set_boolean(httpSetting, "enabled", TRUE); 68 | if (!success) { 69 | fprintf(stderr, "error enabling http %s\n", proxyPort); 70 | ret = SYSCALL_FAILED; 71 | goto cleanup; 72 | } 73 | success = g_settings_set_string(setting, "mode", "manual"); 74 | if (!success) { 75 | fprintf(stderr, "error setting mode to manual\n"); 76 | ret = SYSCALL_FAILED; 77 | goto cleanup; 78 | } 79 | } 80 | else { 81 | if (strlen(proxyHost) != 0) { 82 | // clear proxy setting only if it's equal to the original setting 83 | char* oldMode = g_settings_get_string(setting, "mode"); 84 | char* oldHTTPHost = g_settings_get_string(httpSetting, "host"); 85 | long oldHTTPPort = g_settings_get_int(httpSetting, "port"); 86 | char* oldHTTPSHost = g_settings_get_string(httpsSetting, "host"); 87 | long oldHTTPSPort = g_settings_get_int(httpsSetting, "port"); 88 | if (strcmp(oldMode, "manual") != 0 || 89 | strcmp(oldHTTPHost, proxyHost) != 0 || 90 | oldHTTPPort != port || 91 | strcmp(oldHTTPSHost, proxyHost) != 0 || 92 | oldHTTPSPort != port) { 93 | fprintf(stderr, "current http or https setting is not %s:%s, skipping\n", proxyHost, proxyPort); 94 | goto cleanup; 95 | } 96 | } 97 | g_settings_reset(httpSetting, "host"); 98 | g_settings_reset(httpSetting, "port"); 99 | g_settings_reset(httpsSetting, "host"); 100 | g_settings_reset(httpsSetting, "port"); 101 | g_settings_reset(httpSetting, "enabled"); 102 | g_settings_reset(setting, "mode"); 103 | } 104 | 105 | cleanup: 106 | g_settings_sync(); 107 | g_object_unref(setting); 108 | 109 | return ret; 110 | } 111 | -------------------------------------------------------------------------------- /main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include "common.h" 6 | 7 | 8 | const char* proxyHost; 9 | const char* proxyPort; 10 | 11 | void usage(const char* binName) 12 | { 13 | printf("Usage: %s [show | on | off | wait-and-cleanup ]\n", binName); 14 | exit(INVALID_FORMAT); 15 | } 16 | 17 | void turnOffProxyOnSignal(int signal) 18 | { 19 | toggleProxy(false); 20 | exit(0); 21 | } 22 | 23 | void setupSignals() 24 | { 25 | // Register signal handlers to make sure we turn proxy off no matter what 26 | signal(SIGABRT, turnOffProxyOnSignal); 27 | signal(SIGFPE, turnOffProxyOnSignal); 28 | signal(SIGILL, turnOffProxyOnSignal); 29 | signal(SIGINT, turnOffProxyOnSignal); 30 | signal(SIGSEGV, turnOffProxyOnSignal); 31 | signal(SIGTERM, turnOffProxyOnSignal); 32 | signal(SIGSEGV, turnOffProxyOnSignal); 33 | } 34 | 35 | int main(int argc, char* argv[]) { 36 | if (argc < 2) { 37 | usage(argv[0]); 38 | } 39 | 40 | #ifdef DARWIN 41 | if (strcmp(argv[1], "setuid") == 0) { 42 | return setUid(); 43 | } 44 | #endif 45 | 46 | if (strcmp(argv[1], "show") == 0) { 47 | return show(); 48 | } else { 49 | if (argc < 4) { 50 | usage(argv[0]); 51 | } 52 | proxyHost = argv[2]; 53 | proxyPort = argv[3]; 54 | if (strcmp(argv[1], "on") == 0) { 55 | return toggleProxy(true); 56 | } else if (strcmp(argv[1], "off") == 0) { 57 | return toggleProxy(false); 58 | } else if (strcmp(argv[1], "wait-and-cleanup") == 0) { 59 | setupSignals(); 60 | #ifdef _WIN32 61 | setupSystemShutdownHandler(); 62 | #endif 63 | // wait for input from stdin (or close), then toggle off 64 | getchar(); 65 | return toggleProxy(false); 66 | } else { 67 | usage(argv[0]); 68 | } 69 | } 70 | // code never reaches here, just avoids compiler from complaining. 71 | return RET_NO_ERROR; 72 | } 73 | -------------------------------------------------------------------------------- /windows.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include "common.h" 8 | 9 | void reportWindowsError(const char* action, const char* connName) { 10 | LPTSTR pErrMsg = NULL; 11 | DWORD errCode = GetLastError(); 12 | FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER| 13 | FORMAT_MESSAGE_IGNORE_INSERTS | 14 | FORMAT_MESSAGE_FROM_HMODULE| 15 | FORMAT_MESSAGE_FROM_SYSTEM| 16 | FORMAT_MESSAGE_ARGUMENT_ARRAY, 17 | GetModuleHandle(_T("wininet.dll")), 18 | errCode, 19 | LANG_NEUTRAL, 20 | pErrMsg, 21 | 0, 22 | NULL); 23 | if (NULL != connName) { 24 | fprintf(stderr, "Error %s for connection '%s': %lu %s\n", 25 | action, connName, errCode, pErrMsg); 26 | } else { 27 | fprintf(stderr, "Error %s: %lu %s\n", action, errCode, pErrMsg); 28 | } 29 | } 30 | 31 | // Stolen from https://github.com/getlantern/winproxy Figure out which Dial-Up 32 | // or VPN connection is active; in a normal LAN connection, this should return 33 | // NULL. NOTE: For some reason this method fails when compiled in Debug mode 34 | // but works every time in Release mode. 35 | // TODO: we may want to find all active connections instead of the first one. 36 | LPTSTR findActiveConnection() { 37 | DWORD dwCb = sizeof(RASCONN); 38 | DWORD dwErr = ERROR_SUCCESS; 39 | DWORD dwRetries = 5; 40 | DWORD dwConnections = 0; 41 | RASCONN* lpRasConn = NULL; 42 | RASCONNSTATUS rasconnstatus; 43 | rasconnstatus.dwSize = sizeof(RASCONNSTATUS); 44 | 45 | // Loop through in case the information from RAS changes between calls. 46 | while (dwRetries--) { 47 | // If the memory is allocated, free it. 48 | if (NULL != lpRasConn) { 49 | HeapFree(GetProcessHeap(), 0, lpRasConn); 50 | lpRasConn = NULL; 51 | } 52 | 53 | // Allocate the size needed for the RAS structure. 54 | lpRasConn = (RASCONN*)HeapAlloc(GetProcessHeap(), 0, dwCb); 55 | if (NULL == lpRasConn) { 56 | dwErr = ERROR_NOT_ENOUGH_MEMORY; 57 | break; 58 | } 59 | 60 | // Set the structure size for version checking purposes. 61 | lpRasConn->dwSize = sizeof(RASCONN); 62 | 63 | // Call the RAS API then exit the loop if we are successful or an unknown 64 | // error occurs. 65 | dwErr = RasEnumConnections(lpRasConn, &dwCb, &dwConnections); 66 | if (ERROR_INSUFFICIENT_BUFFER != dwErr) { 67 | break; 68 | } 69 | } 70 | 71 | // In the success case, return the first active connection. 72 | if (ERROR_SUCCESS == dwErr) { 73 | DWORD i; 74 | for (i = 0; i < dwConnections; i++) { 75 | RasGetConnectStatus(lpRasConn[i].hrasconn, &rasconnstatus); 76 | if (rasconnstatus.rasconnstate == RASCS_Connected){ 77 | return lpRasConn[i].szEntryName; 78 | } 79 | 80 | } 81 | } 82 | return NULL; // Couldn't find an active dial-up/VPN connection; return NULL 83 | } 84 | 85 | int initialize(INTERNET_PER_CONN_OPTION_LIST* options) { 86 | DWORD dwBufferSize = sizeof(INTERNET_PER_CONN_OPTION_LIST); 87 | options->dwSize = dwBufferSize; 88 | // NULL for LAN, connection name otherwise. 89 | options->pszConnection = findActiveConnection(); 90 | 91 | options->dwOptionCount = 3; 92 | options->dwOptionError = 0; 93 | options->pOptions = (INTERNET_PER_CONN_OPTION*)calloc(3, sizeof(INTERNET_PER_CONN_OPTION)); 94 | if(NULL == options->pOptions) { 95 | return NO_MEMORY; 96 | } 97 | options->pOptions[0].dwOption = INTERNET_PER_CONN_FLAGS; 98 | options->pOptions[1].dwOption = INTERNET_PER_CONN_PROXY_SERVER; 99 | options->pOptions[2].dwOption = INTERNET_PER_CONN_PROXY_BYPASS; 100 | return RET_NO_ERROR; 101 | } 102 | 103 | int query(INTERNET_PER_CONN_OPTION_LIST* options) { 104 | DWORD dwBufferSize = sizeof(INTERNET_PER_CONN_OPTION_LIST); 105 | if(!InternetQueryOption(NULL, INTERNET_OPTION_PER_CONNECTION_OPTION, options, &dwBufferSize)) { 106 | reportWindowsError("querying options", options->pszConnection ? options->pszConnection : "LAN"); 107 | return SYSCALL_FAILED; 108 | } 109 | return RET_NO_ERROR; 110 | } 111 | 112 | int show() 113 | { 114 | INTERNET_PER_CONN_OPTION_LIST options; 115 | int ret = initialize(&options); 116 | if (ret != RET_NO_ERROR) { 117 | return ret; 118 | } 119 | ret = query(&options); 120 | if (ret != RET_NO_ERROR) { 121 | return ret; 122 | } 123 | if ((options.pOptions[0].Value.dwValue & PROXY_TYPE_PROXY) > 0) { 124 | if (options.pOptions[1].Value.pszValue != NULL) { 125 | printf("%s\n", options.pOptions[1].Value.pszValue); 126 | } 127 | } 128 | return ret; 129 | } 130 | 131 | int doToggleProxy(bool turnOn) 132 | { 133 | INTERNET_PER_CONN_OPTION_LIST options; 134 | int ret = initialize(&options); 135 | if (ret != RET_NO_ERROR) { 136 | return ret; 137 | } 138 | 139 | char *proxy = malloc(256); 140 | snprintf(proxy, 256, "%s:%s", proxyHost, proxyPort); 141 | 142 | if (turnOn) { 143 | options.pOptions[0].Value.dwValue = PROXY_TYPE_DIRECT | PROXY_TYPE_PROXY; 144 | options.pOptions[1].Value.pszValue = proxy; 145 | options.pOptions[2].Value.pszValue = TEXT(""); 146 | } 147 | else { 148 | if (strlen(proxyHost) == 0) { 149 | goto turnOff; 150 | } 151 | ret = query(&options); 152 | if (ret != RET_NO_ERROR) { 153 | goto cleanup; 154 | } 155 | // we turn proxy off only if the option is set and proxy address has the 156 | // provided prefix. 157 | if ((options.pOptions[0].Value.dwValue & PROXY_TYPE_PROXY) == 0 158 | || options.pOptions[1].Value.pszValue == NULL 159 | || strncmp(proxy, options.pOptions[1].Value.pszValue, strlen(proxy)) != 0) { 160 | goto cleanup; 161 | } 162 | // fall through 163 | turnOff: 164 | options.pOptions[0].Value.dwValue = PROXY_TYPE_DIRECT; 165 | options.pOptions[1].Value.pszValue = ""; 166 | options.pOptions[2].Value.pszValue = ""; 167 | } 168 | 169 | DWORD dwBufferSize = sizeof(INTERNET_PER_CONN_OPTION_LIST); 170 | BOOL result = InternetSetOption(NULL, 171 | INTERNET_OPTION_PER_CONNECTION_OPTION, 172 | &options, 173 | dwBufferSize); 174 | if (!result) { 175 | reportWindowsError("setting options", options.pszConnection ? options.pszConnection : "LAN"); 176 | ret = SYSCALL_FAILED; 177 | goto cleanup; 178 | } 179 | result = InternetSetOption(NULL, INTERNET_OPTION_SETTINGS_CHANGED, NULL, 0); 180 | if (!result) { 181 | reportWindowsError("propagating changes", NULL); 182 | ret = SYSCALL_FAILED; 183 | goto cleanup; 184 | } 185 | result = InternetSetOption(NULL, INTERNET_OPTION_REFRESH , NULL, 0); 186 | if (!result) { 187 | reportWindowsError("refreshing", NULL); 188 | ret = SYSCALL_FAILED; 189 | goto cleanup; 190 | } 191 | 192 | cleanup: 193 | free(options.pOptions); 194 | free(proxy); 195 | return ret; 196 | } 197 | 198 | HWND hWnd = NULL; 199 | HANDLE hInvisibleThread = NULL; 200 | 201 | int toggleProxy(bool turnOn) 202 | { 203 | if (hInvisibleThread == NULL) { 204 | return doToggleProxy(turnOn); 205 | } 206 | 207 | // in this case, we're running in wait-and-cleanup mode, close the Window and 208 | // let that trigger the toggling on the event loop thread. 209 | PostMessage(hWnd, WM_CLOSE, 0, 0); 210 | WaitForSingleObject(hInvisibleThread, INFINITE); 211 | DWORD exitCode = 0; 212 | GetExitCodeThread(hInvisibleThread, &exitCode); 213 | return exitCode; 214 | } 215 | 216 | LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { 217 | switch (message) { 218 | case WM_DESTROY: 219 | PostQuitMessage(doToggleProxy(false)); 220 | break; 221 | case WM_ENDSESSION: 222 | doToggleProxy(false); 223 | break; 224 | default: 225 | return DefWindowProc(hWnd, message, wParam, lParam); 226 | } 227 | return 0; 228 | } 229 | 230 | // courtesy of https://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/abf09824-4e4c-4f2c-ae1e-5981f06c9c6e/windows-7-console-application-has-no-way-of-trapping-logoffshutdown-event?forum=windowscompatibility 231 | void createInvisibleWindow() 232 | { 233 | WNDCLASS wc={0}; 234 | wc.lpfnWndProc=(WNDPROC)WndProc; 235 | wc.hInstance=GetModuleHandle(NULL); 236 | wc.hIcon=LoadIcon(GetModuleHandle(NULL), "SysproxyWindow"); 237 | wc.lpszClassName="SysproxyWindow"; 238 | RegisterClass(&wc); 239 | 240 | hWnd=CreateWindowEx(0,"SysproxyWindow","SysproxyWindow",WS_OVERLAPPEDWINDOW,CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,(HWND) NULL, (HMENU) NULL, GetModuleHandle(NULL), (LPVOID) NULL); 241 | if(!hWnd) 242 | printf("FAILED to create window!!! %Iu\n",GetLastError()); 243 | } 244 | 245 | DWORD WINAPI runInvisibleWindowThread(LPVOID lpParam) 246 | { 247 | MSG msg; 248 | createInvisibleWindow(); 249 | while (GetMessage(&msg,(HWND) NULL , 0 , 0)) 250 | { 251 | TranslateMessage(&msg); 252 | DispatchMessage(&msg); 253 | } 254 | return 0; 255 | } 256 | 257 | void setupSystemShutdownHandler() 258 | { 259 | // Create an invisible window so that we can respond to system shutdown and 260 | // make sure that we finish setting the system proxy to off. 261 | DWORD tid; 262 | hInvisibleThread=CreateThread(NULL, 0, runInvisibleWindowThread, NULL, 0, &tid); 263 | if (hInvisibleThread == NULL) 264 | { 265 | printf("FAILED to create thread for invisible window!!! %Iu\n",GetLastError()); 266 | } 267 | 268 | // Make this process shut down very early so that in system logoff case, we 269 | // successfully disable system proxy before parent process tries to do so and 270 | // fails, and also do it early enough that required system services have not 271 | // yet shut down. 272 | // 273 | // See https://stackoverflow.com/questions/8760509/graceful-application-shutdown-when-windows-shuts-down 274 | BOOL fOkay = SetProcessShutdownParameters(0x3FF, SHUTDOWN_NORETRY); 275 | if (!fOkay) { 276 | printf("Failed to prioritize sysproxy-cmd for shutdown\n"); 277 | } 278 | } 279 | --------------------------------------------------------------------------------