Repository: Cenmrev/V2RayX Branch: master Commit: 3551c3eb496d Files: 48 Total size: 560.5 KB Directory structure: gitextract_wbr1cdk7/ ├── .github/ │ └── ISSUE_TEMPLATE.md ├── .gitignore ├── .gitmodules ├── .travis.yml ├── LICENSE ├── README.md ├── V2RayX/ │ ├── AdvancedWindow.xib │ ├── AdvancedWindowController.h │ ├── AdvancedWindowController.m │ ├── AppDelegate.h │ ├── AppDelegate.m │ ├── Assets.xcassets/ │ │ ├── AppIcon.appiconset/ │ │ │ └── Contents.json │ │ ├── Contents.json │ │ ├── config_duplicate.imageset/ │ │ │ └── Contents.json │ │ ├── statusBarIcon.imageset/ │ │ │ └── Contents.json │ │ └── statusBarIcon_disabled.imageset/ │ │ └── Contents.json │ ├── Base.lproj/ │ │ └── MainMenu.xib │ ├── ConfigImporter.h │ ├── ConfigImporter.m │ ├── ConfigWindow.xib │ ├── ConfigWindowController.h │ ├── ConfigWindowController.m │ ├── Credits.rtf │ ├── Info.plist │ ├── MutableDeepCopying.h │ ├── NSData+AES256Encryption.h │ ├── NSData+AES256Encryption.m │ ├── ServerProfile.h │ ├── ServerProfile.m │ ├── TransportWindow.xib │ ├── TransportWindowController.h │ ├── TransportWindowController.m │ ├── config-sample.plist │ ├── config-sample_new.plist │ ├── dlcore.sh │ ├── install_helper.sh │ ├── main.m │ ├── simple.pac │ ├── tcp_http_header_example.txt │ ├── utilities.h │ └── utilities.m ├── V2RayX.xcodeproj/ │ └── project.pbxproj ├── compilefromsource.sh ├── jsonplist/ │ └── main.m ├── prepare_zip.sh ├── v2rayx_sysconf/ │ ├── main.m │ └── sysconf_version.h └── vx.ggb ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/ISSUE_TEMPLATE.md ================================================ --- name: V2RayX issue 模版 --- 请回答下列问题。不按模板发的 issue 将直接被关闭。 0) 如果你没有遇到任何错误和不正常,请在此处回答你想发表的内容: 1) 你正在使用哪个版本的 V2RayX,你的 macOS 系统版本? 2) 如果你在操作 V2RayX 的时候遇到程序崩溃/无反应,请描述你的操作,之后在命令行(终端.app)里运行`/Applications/V2RayX.app/Contents/MacOS/V2RayX`,重复上述操作直至软件崩溃,把终端里的输出贴到下面指定的地方。 ``` 在这里贴上终端的输出 ``` 3) 如果 V2RayX 没有发生崩溃,但是有一些不正常行为,比如上次勾选了 mux,再次打开,mux 的钩没有了。请描述你遇到的不正常行为。 4) 如果 V2RayX 一切正常,但网络依然不如你所预料,请首先把 log level 切换到 debug,再次访问你想访问的网站。然后点击 V2RayX 的 `view current config.json`,将弹出的浏览器内的配置文件粘贴到下面指定的地方,但是隐藏掉ip/端口/id等信息。 ```javascript 在这里粘贴配置文件内容 ``` 然后点击 V2RayX 的`view log`,把 error.log 中的输出贴到下方: ``` 在这里贴上 error.log ``` 5) 其他你认为可以帮助开发者和你一起解决问题的信息: ================================================ FILE: .gitignore ================================================ DerivedData/ .DS_Store V2RayX.xcodeproj/project.xcworkspace V2RayX.xcodeproj/xcuserdata/ build/ v2ray-core-bin/ ================================================ FILE: .gitmodules ================================================ [submodule "GCDWebServer"] path = GCDWebServer url = https://github.com/swisspol/GCDWebServer.git ================================================ FILE: .travis.yml ================================================ os: osx language: objective-c sudo: false install: true script: xcodebuild -project V2RayX.xcodeproj -target V2RayX -configuration Release after_success: - isbeta=$(git describe --abbrev=0 --tags | grep beta) before_deploy: - sh ./prepare_zip.sh deploy: - provider: releases prerelease: true api_key: secure: HjwZ8C70qYeozvaEUvKqDX42T26pRYiQBrTvzbqy8Q+BDWJZ7vNZhSwgt+oYGBywgpk0bM/Ao3al6YDlTE86bMiRUEGSFjRWo2Oquo4N5ydp5cmzT6sVigrLiviufAMrCrCljh0OEt/hEN7wf7zJ8SZKFCLOi8AhTkJu8yEuFdx/2Zd/VSOs6AFp0s1uGrfd3UmwxWfGcKatpYb4GcCwZk2PrECc0qkAP9UzGjemU1cYzcICi+cXl/NoMeLRftHSZaGl+zg95bvddSlNvyqvPwH/00hnh6kpjdyKMDQ071eFE+9NIShglm5yS9TcR3+fE6WfWU9SjTOnT2IfggvXfogcJWd7k4/AwFoAkezNiV0IMKXl2163T17pfFxVQo56oy9HtMts3bw5TapL2YiJa1PKzluSc5ijNcGdDh/7GIejne9lyTeHNhnE/Acmlt8Mu9N+gSj04R4sqN/GfTGzmlPC4kXB08RLg5ycHksGyf4YOLYe9wOEBN4UaSqepFsWqrrufj16l4dqTdacLdt2dJtkPsqCCiUu+nfVVZP9uibIMqWjBi+Fp2Rz+RIvaqtoQrMy+b1y/YwcVz9cJ29OMwU5hY6MehN5pqknwMhsDk1vH5m93swpL6wfM6CT7NjambVfPGffX8zYp/1l/CbBelzjaxZ/CbV4GHXkYHJ923s= file: build/Debug/V2RayX.app.zip skip_cleanup: true on: repo: Cenmrev/V2RayX tags: true condition: "\"$isbeta\" != \"\"" - provider: releases api_key: secure: HjwZ8C70qYeozvaEUvKqDX42T26pRYiQBrTvzbqy8Q+BDWJZ7vNZhSwgt+oYGBywgpk0bM/Ao3al6YDlTE86bMiRUEGSFjRWo2Oquo4N5ydp5cmzT6sVigrLiviufAMrCrCljh0OEt/hEN7wf7zJ8SZKFCLOi8AhTkJu8yEuFdx/2Zd/VSOs6AFp0s1uGrfd3UmwxWfGcKatpYb4GcCwZk2PrECc0qkAP9UzGjemU1cYzcICi+cXl/NoMeLRftHSZaGl+zg95bvddSlNvyqvPwH/00hnh6kpjdyKMDQ071eFE+9NIShglm5yS9TcR3+fE6WfWU9SjTOnT2IfggvXfogcJWd7k4/AwFoAkezNiV0IMKXl2163T17pfFxVQo56oy9HtMts3bw5TapL2YiJa1PKzluSc5ijNcGdDh/7GIejne9lyTeHNhnE/Acmlt8Mu9N+gSj04R4sqN/GfTGzmlPC4kXB08RLg5ycHksGyf4YOLYe9wOEBN4UaSqepFsWqrrufj16l4dqTdacLdt2dJtkPsqCCiUu+nfVVZP9uibIMqWjBi+Fp2Rz+RIvaqtoQrMy+b1y/YwcVz9cJ29OMwU5hY6MehN5pqknwMhsDk1vH5m93swpL6wfM6CT7NjambVfPGffX8zYp/1l/CbBelzjaxZ/CbV4GHXkYHJ923s= file: build/Release/V2RayX.app.zip skip_cleanup: true on: repo: Cenmrev/V2RayX tags: true condition: "\"$isbeta\" = \"\"" ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: README.md ================================================ # V2RayX: A simple GUI for V2Ray on macOS [![Build Status](https://travis-ci.org/Cenmrev/V2RayX.svg?branch=master)](https://travis-ci.org/Cenmrev/V2RayX) ## What is V2Ray? __READ THIS__: [Project V2Ray](http://www.v2ray.com). __YOU SHOULD READ V2RAY'S OFFICIAL INSTRUCTION BEFORE USING V2RAYX!__ Other V2Ray clients on macOS: [V2RayU](https://github.com/yanue/v2rayu). (Not related to or endorsed by authors of this repo. USE AT YOUR OWN RISK.) ## Download V2RayX Download from [Releases](https://github.com/Cenmrev/V2RayX/releases). (compiled by [travis-ci.org](https://travis-ci.org/Cenmrev/V2RayX)). By [Homebrew-Cask](https://caskroom.github.io/). ```sh brew cask install v2rayx ``` ## How to build V2RayX.app is built by running one of the following commands in your terminal. You can install this via the command-line with curl. `sh -c "$(curl -fsSL https://raw.githubusercontent.com/Cenmrev/V2RayX/master/compilefromsource.sh)"` or step by step: `git clone --recursive https://github.com/Cenmrev/V2RayX.git` open V2RayX.xcodeproj and use Xcode to build V2RayX. ## How does V2RayX work V2RayX provides a GUI to generate the config file for V2Ray. It includes V2Ray's binary executable in the app bundle. V2RayX starts and stops V2Ray with `launchd` of macOS. V2RayX also allows users to change system proxy settings and switch proxy servers on the macOS menu bar. As default, V2RayX will open a socks5 proxy at port `1081` as the main inbound, as well as a http proxy at port `8001` as an inboundDetour. V2RayX provide three modes: * Global Mode: V2RayX asks macOS to route all internet traffic to v2ray core if the network traffic obeys operating system's network rules. * PAC Mode: macOS will determine the routing based on a pac file and some traffic may be routed to v2ray core. * Manual Mode: V2RayX will not modify any macOS network settings, but only start or stop v2ray core. Options in menu list `Routing Rule` determine how v2ray core deals with incoming traffic. Core routing rules apply to all three modes above. ### auto-run on login Open macOS System Preferences -> Users & Group -> Login Items, add V2RayX.app to the list. ### manually update v2ray-core replace `V2RayX.app/Contents/Resources/v2ray` with the newest v2ray version from [v2ray-core repo](https://github.com/v2ray/v2ray-core/releases). However, compatibility is not guaranteed. ### Uninstall V2RayX will create the following files and folders: * `/Library/Application Support/V2RayX` * `~/Library/Application Support/V2RayX` * `~/Library/Preferences/cenmrev.V2RayX.plist` So, to totally uninstall V2RayX, just delete V2RayX.app and the files above. :) ## Acknowledge V2RayX uses [GCDWebServer](https://github.com/swisspol/GCDWebServer) to provide a local pac server. V2RayX also uses many ideas and codes from [ShadowsocksX](https://github.com/shadowsocks/shadowsocks-iOS/tree/master), especially, the codes of [v2rays_sysconfig](https://github.com/Cenmrev/V2RayX/blob/master/v2rayx_sysconf/main.m) are simply copied from [shadowsocks_sysconf](https://github.com/shadowsocks/shadowsocks-iOS/blob/master/shadowsocks_sysconf/main.m) with some modifications. ## Donation If Project V2Ray or V2RayX helped you, you can also help us by donation __in your will__. To donate to Project V2Ray, you may refer to [this page](https://www.v2ray.com/chapter_00/02_donate.html). ## Disclaimer This tool is mainly for personal usage. For professional users and technique support, commercial software like proxifier is recommended. Please refer to [#60](https://github.com/Cenmrev/V2RayX/issues/60#issuecomment-369531443). The developer does not major in CS nor Software Engineer and currently is busy with grad school courses. So V2rayX will not be updated frequently. Users can replace V2RayX.app/Contents/Resources/v2ray with the newest v2ray-core downloaded from [https://github.com/v2ray/v2ray-core/releases](https://github.com/v2ray/v2ray-core/releases). The developer currently does not have enough time to add more features to V2RayX, nor to merge PRs. However, forking and releasing your own version are always welcome. ================================================ FILE: V2RayX/AdvancedWindow.xib ================================================ To use outbounds of other protocols apart from vmess, directly provide the corresponding OutboundObject below. Click Help to see instructions. Item 1 Item 2 Item 3 Item 1 Item 2 Item 3 V2RayX is shipped with a v2ray binary file in the app bundle. If anyone wants to use a different v2ray core binary, put the binary file in the following directory: v2ray-core/v2ray v2ray-core/v2ctl v2ray-core/geoip.dat v2ray-core/geosite.dat Otherwise V2RayX will still use default v2ray core binaries. Compatibility is not guaranteed. All the configuration information are stored in ~/Library/Preferences/cenmrev.V2RayX.plist. In case the information is leaked to other unauthorized programs or individuals, set a password and V2RayX will use AES-256-ECB to encrypt the information. NSAllRomanInputSourcesLocaleIdentifier NSAllRomanInputSourcesLocaleIdentifier When an incoming connection matches ALL the criterions (domain/ip/port/network), it will be routed to the provided outbound tag. Four preset tags: main: the outbound users choose from the menu list "Server" decline: the connection will be closed. direct: incoming traffic will be send to its real destination. balance: v2ray will randomly pickup an outbound from all provided outbounds. To provide domain and IP rules, follow this format: separate domains and ips with a line `---`. Examples: 1. v2ray.com ---- 10.0.0.0/8 geoip:private will match traffic with (a destination domain includes "v2ray.com") AND (a destination IP in range of 10.0.0.0/8 OR a private destination IP) 2. domain:v2ray.com ---- will match traffic with a destination domain of v2ray.com and *.v2ray.com. 3. ---- geoip:private will match all private IPs. ================================================ FILE: V2RayX/AdvancedWindowController.h ================================================ // // AdvancedWindowController.h // V2RayX // // #import #import "ConfigWindowController.h" NS_ASSUME_NONNULL_BEGIN @interface AdvancedWindowController : NSWindowController - (instancetype)initWithWindowNibName:(NSNibName)windowNibName parentController:(ConfigWindowController*)parent; @property (weak) IBOutlet NSTextField *checkLabel; @property (weak) IBOutlet NSTabView *mainTabView; //outbounds @property (weak) IBOutlet NSTableView *outboundTable; @property (unsafe_unretained) IBOutlet NSTextView *outboundJsonView; @property (weak) IBOutlet NSSegmentedControl *outboundAddControl; @property NSMutableArray* outbounds; // subscription @property (weak) IBOutlet NSTableView *subscriptionTable; @property (weak) IBOutlet NSSegmentedControl *subscriptionAddControl; @property NSMutableArray* subscriptions; //rules @property (strong) IBOutlet NSView *domainListEditView; @property (strong) IBOutlet NSView *ipListEditView; @property (strong) IBOutlet NSView *routingTagHelpView; @property (strong) IBOutlet NSView *domainIpHelpView; @property (weak) IBOutlet NSTableView *ruleSetTable; @property (weak) IBOutlet NSSegmentedControl *ruleSetAddControl; @property (weak) IBOutlet NSTextField *ruleSetNameField; @property (weak) IBOutlet NSPopUpButton *domainStrategyButton; @property (weak) IBOutlet NSTableView *ruleTable; @property (weak) IBOutlet NSSegmentedControl *ruleAddControl; @property (weak) IBOutlet NSButton *domainIpHelpButton; // enbale buttons @property (weak) IBOutlet NSButton *domainEnableButton; @property (weak) IBOutlet NSButton *ipEnableButton; @property (weak) IBOutlet NSButton *inboundEnableButton; @property (weak) IBOutlet NSButton *protocolEnableButton; @property (weak) IBOutlet NSButton *portEnableButton; @property (weak) IBOutlet NSButton *networkEnableButton; // fields @property (weak) IBOutlet NSButton *editDomainButton; @property (unsafe_unretained) IBOutlet NSTextView *domainTextView; @property (weak) IBOutlet NSButton *editIpButton; @property (unsafe_unretained) IBOutlet NSTextView *ipTextView; @property (weak) IBOutlet NSComboBox *inboundTagBox; @property (weak) IBOutlet NSPopUpButton *protocolButton; @property (weak) IBOutlet NSTextField *portField; @property (weak) IBOutlet NSPopUpButton *networkListButton; @property (weak) IBOutlet NSButton *saveIPListButton; @property (weak) IBOutlet NSButton *saveDomainListButton; @property (weak) IBOutlet NSButton *routeToHelpButton; @property (weak) IBOutlet NSComboBox *routeToBox; @property NSMutableArray* routingRuleSets; //config @property (weak) IBOutlet NSTableView *configTable; @property (weak) IBOutlet NSSegmentedControl *configAddControl; @property NSMutableArray* configs; // v2ray core @property (weak) IBOutlet NSTextField *corePathField; @property (weak) IBOutlet NSTextField *coreFileListField; @property (weak) IBOutlet NSPopUpButton *enableRestoreButton; @property BOOL enableRestore; // encryption @property (weak) IBOutlet NSButton *enableEncryptionButton; @property (weak) IBOutlet NSSecureTextField *encryptionKeyField; @property (weak) IBOutlet NSSecureTextField *encryptionKeyConfirmField; @property BOOL enableEncryption; @property NSString* encryptionKey; @property (weak) IBOutlet NSTextField *changeIndicatorField; @end NS_ASSUME_NONNULL_END ================================================ FILE: V2RayX/AdvancedWindowController.m ================================================ // // AdvancedWindowController.m // V2RayX // // #import "AdvancedWindowController.h" #import "MutableDeepCopying.h" #include @interface AdvancedWindowController () { ConfigWindowController* configWindowController; //outbound } @property (strong) NSPopover* popover; @property NSInteger selectedOutbound; @property (atomic) NSInteger selectedRuleSet; @property (atomic) NSInteger selectedRule; @end @implementation AdvancedWindowController - (instancetype)initWithWindowNibName:(NSNibName)windowNibName parentController:(ConfigWindowController*)parent { self = [super initWithWindowNibName:windowNibName]; if (self) { configWindowController = parent; } return self; } - (void)removeObservers { [self removeObserver:self forKeyPath:@"selectedOutbound"]; [self removeObserver:self forKeyPath:@"selectedRuleSet"]; [self removeObserver:self forKeyPath:@"selectedRule"]; } - (void)windowDidLoad { [super windowDidLoad]; // initialize UI [_outboundTable setFocusRingType:NSFocusRingTypeNone]; [_ruleTable setFocusRingType:NSFocusRingTypeNone]; [_ruleSetTable setFocusRingType:NSFocusRingTypeNone]; [_configTable setFocusRingType:NSFocusRingTypeNone]; [_subscriptionTable setFocusRingType:NSFocusRingTypeNone]; [[self domainStrategyButton] removeAllItems]; for(NSString* strategy in DOMAIN_STRATEGY_LIST) { [[self domainStrategyButton] addItemWithTitle:strategy]; } [[self networkListButton] removeAllItems]; for(NSString* network in ROUTING_NETWORK_LIST) { [[self networkListButton] addItemWithTitle:network]; } [_protocolButton removeAllItems]; for (NSString* p in SNIFFING_PROTOCOL) { [_protocolButton addItemWithTitle:p]; } _outboundJsonView.automaticQuoteSubstitutionEnabled = false; _domainTextView.automaticQuoteSubstitutionEnabled = false; [_routeToBox removeAllItems]; [_routeToBox addItemsWithObjectValues:RESERVED_TAGS]; [_inboundTagBox removeAllItems]; [_inboundTagBox addItemsWithObjectValues:@[@"socksinbound", @"httpinbound"]]; // outbound [_outboundJsonView setFont:[NSFont fontWithName:@"Menlo" size:13]]; [self addObserver:self forKeyPath:@"selectedOutbound" options:NSKeyValueObservingOptionNew context:nil]; // rule [self addObserver:self forKeyPath:@"selectedRuleSet" options:NSKeyValueObservingOptionNew context:nil]; [self addObserver:self forKeyPath:@"selectedRule" options:NSKeyValueObservingOptionNew context:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidChange:) name:NSControlTextDidChangeNotification object:_ruleSetNameField]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidChange:) name:NSControlTextDidChangeNotification object:_routeToBox]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidChange:) name:NSControlTextDidChangeNotification object:_portField]; // core path self.corePathField.stringValue = [NSString stringWithFormat:@"%@/Library/Application Support/V2RayX/v2ray-core/",NSHomeDirectory()]; self.enableRestore = configWindowController.enableRestore; self.enableEncryption = configWindowController.enableEncryption; self.encryptionKey = [[NSString alloc] initWithString:configWindowController.encryptionKey]; // encryption _changeIndicatorField.stringValue = @""; [self fillData]; } - (void)fillData { // outbound self.outbounds = [configWindowController.outbounds mutableCopy]; _outboundJsonView.editable = self.outbounds.count > 0; if (self.outbounds.count > 0) { self.selectedOutbound = 0; } else { self.selectedOutbound = -1; } [_outboundTable reloadData]; // subscriptions self.subscriptions = [configWindowController.subscriptions mutableCopy]; [_subscriptionTable reloadData]; // rules self.selectedRuleSet = 0; self.selectedRule = 0; self.routingRuleSets = [configWindowController.routingRuleSets mutableDeepCopy]; // configs self.configs = [configWindowController.cusProfiles mutableDeepCopy]; [_configTable reloadData]; // core [_enableRestoreButton selectItemAtIndex:_enableRestore?1:0]; } - (IBAction)ok:(id)sender { if (![self checkOutbound]) { return; } if (![self checkConfig]) { return; } [self removeObservers]; [self.window.sheetParent endSheet:self.window returnCode:NSModalResponseOK]; } - (IBAction)cancel:(id)sender { [self removeObservers]; [self.window.sheetParent endSheet:self.window returnCode:NSModalResponseCancel]; } // table data - (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView { if (tableView == _outboundTable) { return [self.outbounds count]; } if (tableView == _configTable) { return [self.configs count]; } if (tableView == _ruleSetTable) { return self.routingRuleSets.count; } if (tableView == _ruleTable) { return [self.routingRuleSets[_selectedRuleSet][@"rules"] count]; } if (tableView == _subscriptionTable) { return [self.subscriptions count]; } return 0; } - (id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row { if (tableView == _outboundTable) { return self.outbounds[row][@"tag"]; } if (tableView == _configTable) { return self.configs[row]; } if (tableView == _ruleSetTable) { return self.routingRuleSets[row][@"name"]; } if(tableView == _ruleTable) { NSUInteger ruleCount = [self.routingRuleSets[_selectedRuleSet][@"rules"] count]; NSDictionary* rule = self.routingRuleSets[_selectedRuleSet][@"rules"][row]; NSString* routeTo = rule[@"outboundTag"] ? rule[@"outboundTag"] : rule[@"balancerTag"]; return row + 1 == ruleCount ? [NSString stringWithFormat:@"final:%@", routeTo] : [NSString stringWithFormat:@"%lu:%@", row, routeTo] ; } if (tableView == _subscriptionTable) { return self.subscriptions[row]; } return @""; } // table delegate - (void)tableViewSelectionDidChange:(NSNotification *)notification { if (notification.object == _outboundTable) { if (_outboundTable.selectedRow != _selectedOutbound) { [self checkOutbound]; } else { NSLog(@"do nothing"); } } if (notification.object == _ruleSetTable) { self.selectedRuleSet = [_ruleSetTable selectedRow]; [_ruleTable reloadData]; } if (notification.object == _ruleTable) { self.selectedRule = [_ruleTable selectedRow]; } } - (void)tableView:(NSTableView *)tableView setObjectValue:(id)object forTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row { if (tableView == _configTable) { self.configs[row] = object; } else if (tableView == _subscriptionTable) { self.subscriptions[row] = object; } } // bound - (BOOL)checkOutbound { if (_outbounds.count == 0) { return YES; } NSError *e; NSDictionary* newOutboud = [NSJSONSerialization JSONObjectWithData:[_outboundJsonView.string dataUsingEncoding:NSUTF8StringEncoding] options:0 error:&e]; if (e) { [self showAlert:@"NOT a valid json"]; [_outboundTable selectRowIndexes:[NSIndexSet indexSetWithIndex:_selectedOutbound] byExtendingSelection:NO]; return NO; } else { self.outbounds[_selectedOutbound] = newOutboud; self.selectedOutbound = _outboundTable.selectedRow; [_outboundTable reloadData]; return YES; } } - (IBAction)addRemoveOutbound:(id)sender { if ([sender selectedSegment] == 0) { NSString* tagName = [NSString stringWithFormat:@"tag%lu", self.outbounds.count]; [self.outbounds addObject:@{ @"sendThrough": @"0.0.0.0", @"protocol": @"protocol name", @"settings": @{}, @"tag": tagName, @"streamSettings": @{}, @"mux": @{} }]; if (_selectedOutbound == -1) { _selectedOutbound = 0; self.selectedOutbound = 0; } } else { if (_selectedOutbound >= 0 && _selectedOutbound < _outbounds.count) { [_outbounds removeObjectAtIndex:_selectedOutbound]; self.selectedOutbound = MIN((NSInteger)_outbounds.count - 1, _selectedOutbound); } } [_outboundTable reloadData]; _outboundJsonView.editable = _outbounds.count > 0; } // rules -(void)textFieldDidChange:(NSNotification *)notification { if (notification.object == _ruleSetNameField) { self.routingRuleSets[_selectedRuleSet][@"name"] = _ruleSetNameField.stringValue; } if (notification.object == _routeToBox) { NSMutableDictionary* rule = self.routingRuleSets[_selectedRuleSet][@"rules"][_selectedRule]; if ([@"balance" isEqualToString:_routeToBox.stringValue]) { rule[@"balancerTag"] = @"balance"; [rule removeObjectForKey:@"outboundTag"]; } else { rule[@"outboundTag"] = _routeToBox.stringValue; [rule removeObjectForKey:@"balancerTag"]; } } if (notification.object == _portField) { NSMutableDictionary* rule = self.routingRuleSets[_selectedRuleSet][@"rules"][_selectedRule]; NSString* trimedInput = [_portField.stringValue stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; NSNumberFormatter* f = [[NSNumberFormatter alloc] init]; f.numberStyle = NSNumberFormatterDecimalStyle; NSNumber *port = [f numberFromString:trimedInput]; rule[@"port"] = nilCoalescing(port, trimedInput); } if (notification.object == _inboundTagBox) { self.routingRuleSets[_selectedRuleSet][@"rules"][_selectedRule][@"inboundTag"] = _inboundTagBox.stringValue; } } - (IBAction)addRemoveRuleSet:(id)sender { [[self window] makeFirstResponder:_ruleSetTable]; if ([sender selectedSegment] == 0) { NSMutableDictionary* newRuleSet = [ROUTING_DIRECT mutableDeepCopy]; newRuleSet[@"name"] = @"new_rule_set"; [_routingRuleSets addObject:newRuleSet]; [_ruleSetTable reloadData]; [_ruleSetTable selectRowIndexes:[NSIndexSet indexSetWithIndex:_routingRuleSets.count - 1] byExtendingSelection:NO]; // toggle } else if([sender selectedSegment] == 1 && _selectedRuleSet > 0 && _selectedRuleSet < _routingRuleSets.count){ [_routingRuleSets removeObjectAtIndex:_selectedRuleSet]; NSUInteger originalIndex = _ruleSetTable.selectedRow; [_ruleSetTable selectRowIndexes:[NSIndexSet indexSetWithIndex:MIN(_selectedRuleSet, _routingRuleSets.count - 1)] byExtendingSelection:NO]; // toggle if (originalIndex == _ruleSetTable.selectedRow) { [self tableViewSelectionDidChange:[NSNotification notificationWithName:NSTableViewSelectionDidChangeNotification object:_ruleSetTable]]; } [_ruleSetTable reloadData]; } else if ([sender selectedSegment] == 2) { NSAlert* alert = [[NSAlert alloc] init]; alert.messageText = @"Do you want to reset rule sets to original three ones?"; [alert addButtonWithTitle:@"OK"]; [alert addButtonWithTitle:@"Cancel"]; [alert beginSheetModalForWindow:self.window completionHandler:^(NSModalResponse returnCode) { if (returnCode == NSAlertFirstButtonReturn) { NSLog(@"will rest"); self->_routingRuleSets = [@[ROUTING_GLOBAL, ROUTING_BYPASSCN_PRIVATE_APPLE, ROUTING_DIRECT] mutableDeepCopy]; NSUInteger originalIndex = self->_ruleSetTable.selectedRow; [self->_ruleSetTable selectRowIndexes:[NSIndexSet indexSetWithIndex:0] byExtendingSelection:NO]; // toggle if (originalIndex == self->_ruleSetTable.selectedRow) { [self tableViewSelectionDidChange:[NSNotification notificationWithName:NSTableViewSelectionDidChangeNotification object:self->_ruleSetTable]]; } [self->_ruleSetTable reloadData]; } }]; } else if ([sender selectedSegment] == 3 && _selectedRuleSet >= 0 && _selectedRuleSet < _routingRuleSets.count) { [_routingRuleSets addObject:[[_routingRuleSets objectAtIndex:_selectedRuleSet] mutableDeepCopy]]; [_ruleSetTable reloadData]; [_ruleSetTable selectRowIndexes:[NSIndexSet indexSetWithIndex:_routingRuleSets.count - 1] byExtendingSelection:NO]; // toggle } } - (IBAction)didSelectStrategy:(id)sender { if (_selectedRuleSet < _routingRuleSets.count) { _routingRuleSets[_selectedRuleSet][@"domainStrategy"] = _domainStrategyButton.selectedItem.title; } } - (IBAction)addRemoveRule:(id)sender { [[self window] makeFirstResponder:_ruleTable]; NSMutableArray* rules = _routingRuleSets[_selectedRuleSet][@"rules"]; if ([sender selectedSegment] == 0) { [rules insertObject:[@{ @"type": @"field", @"outboundTag": @"direct"} mutableDeepCopy] atIndex:rules.count-1]; } else { if (_selectedRule + 1 == [rules count]) { return; } [rules removeObjectAtIndex:_selectedRule]; } [_ruleTable reloadData]; self.selectedRule = _selectedRule; // toggle } - (IBAction)didClickEnable:(id)sender { #define enableFilter(enableButton, field, key) \ field.enabled = enableButton.state; \ if (!enableButton.state) { \ [self.routingRuleSets[_selectedRuleSet][@"rules"][_selectedRule] removeObjectForKey:key];\ } if (sender == _domainEnableButton) { enableFilter(_domainEnableButton, _editDomainButton, @"domain") if (_domainEnableButton.state) { [self showEditView:_editDomainButton]; } else if (self.popover.shown) { [self.popover close]; } } else if (sender == _ipEnableButton) { enableFilter(_ipEnableButton, _editIpButton, @"ip") if (_ipEnableButton.state) { [self showEditView:_editIpButton]; } else if (self.popover.shown) { [self.popover close]; } } else if (sender == _inboundEnableButton) { enableFilter(_inboundEnableButton, _inboundTagBox, @"inboundTag") if (_inboundEnableButton.state) { [self.routingRuleSets[_selectedRuleSet][@"rules"][_selectedRule] setObject:_inboundTagBox.stringValue forKey:@"inboundTag"]; } } else if (sender == _protocolEnableButton) { enableFilter(_protocolEnableButton, _protocolButton, @"protocol") if (_protocolEnableButton.state) { [self didSelectRuleItem:_protocolButton]; } } else if (sender == _networkEnableButton) { enableFilter(_networkEnableButton, _networkListButton, @"network") if (_networkEnableButton.state) { [self didSelectRuleItem:_networkListButton]; } } else if (sender == _portEnableButton) { enableFilter(_portEnableButton, _portField, @"port") if (_portEnableButton.state) { [self textFieldDidChange:[[NSNotification alloc] initWithName:NSTextDidChangeNotification object:_portField userInfo:nil]]; } } } - (IBAction)didSelectRuleItem:(id)sender { if (sender == _networkListButton && _networkEnableButton.state) { [self.routingRuleSets[_selectedRuleSet][@"rules"][_selectedRule] setObject:_networkListButton.selectedItem.title forKey:@"network"]; } else if (sender == _protocolButton && _protocolEnableButton.state) { [self.routingRuleSets[_selectedRuleSet][@"rules"][_selectedRule] setObject:_protocolButton.selectedItem.title forKey:@"protocol"]; } else if ((sender == _inboundTagBox && _inboundEnableButton.state) || sender == _routeToBox) { [self textFieldDidChange:[[NSNotification alloc] initWithName:NSTextDidChangeNotification object:sender userInfo:nil]]; } } - (IBAction)showEditView:(id)sender { if (self.popover.shown) { [self.popover close]; } self.popover = [[NSPopover alloc] init]; self.popover.behavior = NSPopoverBehaviorApplicationDefined; self.popover.contentViewController = [[NSViewController alloc] init]; if (sender == _editDomainButton) { self.popover.contentViewController.view = _domainListEditView; } else if (sender == _editIpButton) { self.popover.contentViewController.view = _ipListEditView; } [self.popover showRelativeToRect:[sender bounds] ofView:sender preferredEdge:NSMaxYEdge]; } - (IBAction)saveDomainOrIPList:(id)sender { [self.popover close]; if (sender == _saveIPListButton) { self.routingRuleSets[_selectedRuleSet][@"rules"][_selectedRule][@"ip"] = [[_ipTextView string] componentsSeparatedByString:@"\n"]; NSLog(@"%@", self.routingRuleSets[_selectedRuleSet][@"rules"][_selectedRule][@"ip"]); } else { self.routingRuleSets[_selectedRuleSet][@"rules"][_selectedRule][@"domain"] = [[_ipTextView string] componentsSeparatedByString:@"\n"]; } } - (IBAction)closeDomainOrIPList:(id)sender { [self.popover close]; } // - (IBAction)addRemoveSubscription:(id)sender { NSLog(@"%@", sender); if ([sender selectedSegment] == 0) { [_subscriptions addObject:@"enter your subscription link here"]; [_subscriptionTable reloadData]; } else if ([sender selectedSegment] == 1 && [_subscriptionTable selectedRow] >= 0 && [_subscriptionTable selectedRow] < _subscriptions.count) { [_subscriptions removeObjectAtIndex:[_subscriptionTable selectedRow]]; [_subscriptionTable reloadData]; } NSLog(@"%@", _subscriptions); } // configs - (IBAction)addRemoveConfig:(id)sender { if ([sender selectedSegment] == 0) { [_configs addObject:@"/path/to/your/config.json"]; [_configTable reloadData]; // [_configTable selectRowIndexes:[NSIndexSet indexSetWithIndex:[_configs count] -1] byExtendingSelection:NO]; // [_configTable setFocusedColumn:[_configs count] - 1]; } else if ([sender selectedSegment] == 1 && [_configTable selectedRow] >= 0 && [_configTable selectedRow] < _configs.count) { [_configs removeObjectAtIndex:[_configTable selectedRow]]; [_configTable reloadData]; } } - (BOOL)checkConfig { [_checkLabel setHidden:NO]; NSString* v2rayBinPath = [configWindowController.appDelegate getV2rayPath]; for (NSString* filePath in _configs) { int returnCode = runCommandLine(v2rayBinPath, @[@"-test", @"-config", filePath]); if (returnCode != 0) { [_checkLabel setHidden:YES]; NSAlert *alert = [[NSAlert alloc] init]; [alert setMessageText:[NSString stringWithFormat:@"%@ is not a valid v2ray config file", filePath]]; [alert beginSheetModalForWindow:self.window completionHandler:^(NSModalResponse returnCode) { return; }]; return NO; } } return YES; } // core - (IBAction)showCorePath:(id)sender { if (![[NSFileManager defaultManager] fileExistsAtPath:self.corePathField.stringValue]) { [[NSFileManager defaultManager] createDirectoryAtPath:self.corePathField.stringValue withIntermediateDirectories:YES attributes:nil error:nil]; } [[NSWorkspace sharedWorkspace] activateFileViewerSelectingURLs:@[[NSURL fileURLWithPath:self.corePathField.stringValue]]]; } - (IBAction)changeEnableRestore:(NSPopUpButton*)sender { _enableRestore = [sender indexOfSelectedItem]; } - (IBAction)showInformation:(id)sender { self.popover = [[NSPopover alloc] init]; self.popover.behavior = NSPopoverBehaviorTransient; self.popover.contentViewController = [[NSViewController alloc] init]; if (sender == _domainIpHelpButton) { self.popover.contentViewController.view = _domainIpHelpView; } else if (sender == _routeToHelpButton) { self.popover.contentViewController.view = _routingTagHelpView; } [self.popover showRelativeToRect:[sender bounds] ofView:sender preferredEdge:NSMaxYEdge]; } - (IBAction)showHelp:(id)sender { NSString* tabTitle = _mainTabView.selectedTabViewItem.label; // NSLog(@"%@", _mainTabView.selectedTabViewItem.label); if ([@"Rules" isEqualToString:tabTitle]) { [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"https://www.v2ray.com/chapter_02/03_routing.html"]]; } else if ([@"Outbounds" isEqualToString:tabTitle]) { [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"https://www.v2ray.com/chapter_02/01_overview.html#outboundobject"]]; } else if ([@"Configs" isEqualToString:tabTitle]) { [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"https://www.v2ray.com/chapter_02/01_overview.html"]]; } else if ([@"V2Ray Core" isEqualToString:tabTitle]) { [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"https://www.v2ray.com/chapter_00/install.html#download"]]; } } - (void)showAlert:(NSString*)text { NSAlert* alert = [[NSAlert alloc] init]; [alert setInformativeText:text]; [alert beginSheetModalForWindow:self.window completionHandler:nil]; } - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { // NSLog(@"keypath=%@", keyPath); // outboud if ([@"selectedOutbound" isEqualToString:keyPath]) { if (_selectedOutbound > -1) { [_outboundTable selectRowIndexes:[NSIndexSet indexSetWithIndex:_selectedOutbound] byExtendingSelection:NO]; _outboundJsonView.string = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:_outbounds[_selectedOutbound] options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding]; } else { _outboundJsonView.string = @""; } } // rule if ([@"selectedRuleSet" isEqualToString:keyPath] && _selectedRuleSet < _routingRuleSets.count) { _ruleSetNameField.stringValue = _routingRuleSets[_selectedRuleSet][@"name"]; [_domainStrategyButton selectItemAtIndex:searchInArray(_routingRuleSets[_selectedRuleSet][@"domainStrategy"], DOMAIN_STRATEGY_LIST)]; self.selectedRule = _selectedRule; //toggle } if ([@"selectedRule" isEqualToString:keyPath] && _selectedRuleSet < _routingRuleSets.count && _selectedRule < [_routingRuleSets[_selectedRuleSet][@"rules"] count] ) { if (self.popover.shown) { [self.popover close]; } NSDictionary* rules = _routingRuleSets[_selectedRuleSet][@"rules"][_selectedRule]; BOOL selectedLastRule = _selectedRule + 1 == [_routingRuleSets[_selectedRuleSet][@"rules"] count]; _domainEnableButton.enabled = !selectedLastRule; _domainEnableButton.state = rules[@"domain"] != NULL; _editDomainButton.enabled = _domainEnableButton.state; if (rules[@"domain"]) { _domainTextView.string = [rules[@"domain"] componentsJoinedByString:@"\n"]; } else { _domainTextView.string = @""; } _ipEnableButton.enabled = !selectedLastRule; _ipEnableButton.state = rules[@"ip"] != NULL; _editIpButton.enabled = _ipEnableButton.state; if (rules[@"ip"]) { _ipTextView.string = [rules[@"ip"] componentsJoinedByString:@"\n"]; } else { _ipTextView.string = @""; } _inboundEnableButton.enabled = !selectedLastRule; _inboundEnableButton.state = rules[@"inboundTag"] != NULL; _inboundTagBox.enabled = _inboundEnableButton.state; _inboundTagBox.stringValue = nilCoalescing(rules[@"inboundTag"], @""); _protocolEnableButton.enabled = !selectedLastRule; _protocolEnableButton.state = rules[@"protocol"] != NULL; _protocolButton.enabled = _protocolEnableButton.state; [_protocolButton selectItemAtIndex:searchInArray(rules[@"protocol"], SNIFFING_PROTOCOL)]; _portEnableButton.enabled = !selectedLastRule; _portEnableButton.state = rules[@"port"] != NULL; _portField.enabled = _portEnableButton.state && !selectedLastRule; _portField.objectValue = nilCoalescing(rules[@"port"], @"0-65535"); _networkEnableButton.enabled = !selectedLastRule; _networkEnableButton.state = rules[@"network"] != NULL; _networkListButton.enabled = _networkEnableButton.state; [_networkListButton selectItemAtIndex:searchInArray(rules[@"network"], ROUTING_NETWORK_LIST)]; _routeToBox.stringValue = rules[@"outboundTag"] ? rules[@"outboundTag"] : rules[@"balancerTag"]; } } - (IBAction)changePassword:(id)sender { if ([[_encryptionKeyField stringValue] isEqualToString:[_encryptionKeyConfirmField stringValue]]) { if ([[_encryptionKeyField stringValue] length] > 32) { self.encryptionKey = [_encryptionKeyField.stringValue substringToIndex:32]; } else { self.encryptionKey = [_encryptionKeyConfirmField.stringValue stringByPaddingToLength:32 withString:@"-" startingAtIndex:0]; } [_changeIndicatorField setStringValue:@"success"]; } else { [_changeIndicatorField setStringValue:@"two password do not match each other."]; } } @end ================================================ FILE: V2RayX/AppDelegate.h ================================================ // // AppDelegate.h // V2RayX // // Copyright © 2016年 Cenmrev. All rights reserved. // #import #import "sysconf_version.h" #import "utilities.h" #define kV2RayXHelper @"/Library/Application Support/V2RayX/v2rayx_sysconf" #define kV2RayXSettingVersion 4 #define webServerPort 8070 typedef enum ProxyMode : NSInteger{ pacMode, globalMode, manualMode } ProxyMode; int runCommandLine(NSString* launchPath, NSArray* arguments); @interface AppDelegate : NSObject { BOOL proxyState; ProxyMode proxyMode; NSInteger localPort; NSInteger httpPort; BOOL udpSupport; BOOL shareOverLan; BOOL useCusProfile; BOOL useMultipleServer; NSInteger selectedServerIndex; NSInteger selectedCusServerIndex; NSString* selectedPacFileName; NSString* dnsString; NSMutableArray *profiles; NSMutableArray *cusProfiles; NSString* logLevel; NSString* logDirPath; } @property NSString* logDirPath; @property BOOL proxyState; @property ProxyMode proxyMode; @property NSInteger localPort; @property NSInteger httpPort; @property BOOL udpSupport; @property BOOL shareOverLan; @property BOOL useCusProfile; @property NSInteger selectedServerIndex; @property NSInteger selectedCusServerIndex; @property NSInteger selectedRoutingSet; @property NSString* dnsString; @property NSMutableArray *profiles; @property NSMutableArray *cusProfiles; @property (atomic) NSMutableArray *subsOutbounds; @property NSMutableArray *routingRuleSets; @property NSString* logLevel; @property BOOL useMultipleServer; @property NSString* selectedPacFileName; @property BOOL enableRestore; @property NSMutableArray *subscriptions; @property BOOL enableEncryption; @property NSString* encryptionKey; - (IBAction)didChangeStatus:(id)sender; - (IBAction)updateSubscriptions:(id)sender; - (IBAction)showHelp:(id)sender; - (IBAction)showConfigWindow:(id)sender; - (IBAction)editPac:(id)sender; - (IBAction)resetPac:(id)sender; - (IBAction)viewLog:(id)sender; - (void)saveConfigInfo; -(NSString*)getV2rayPath; - (NSString*)logDirPath; @property (weak) IBOutlet NSMenuItem *updateServerItem; @property (strong, nonatomic) NSStatusItem *statusBarItem; @property (weak) IBOutlet NSMenuItem *upgradeMenuItem; @property (weak, nonatomic) IBOutlet NSMenu *statusBarMenu; @property (weak, nonatomic) IBOutlet NSMenuItem *v2rayStatusItem; @property (weak, nonatomic) IBOutlet NSMenuItem *enableV2rayItem; @property (weak, nonatomic) IBOutlet NSMenuItem *pacModeItem; @property (weak, nonatomic) IBOutlet NSMenuItem *v2rayRulesItem; @property (weak) IBOutlet NSMenu *ruleSetMenuList; @property (weak, nonatomic) IBOutlet NSMenuItem *globalModeItem; @property (weak) IBOutlet NSMenuItem *manualModeItem; @property (weak, nonatomic) IBOutlet NSMenuItem *serversItem; @property (weak, nonatomic) IBOutlet NSMenu *serverListMenu; @property (weak, nonatomic) IBOutlet NSMenu *pacListMenu; @property (weak) IBOutlet NSMenuItem *editPacMenuItem; @property (weak) IBOutlet NSMenu *authMenu; @end ================================================ FILE: V2RayX/AppDelegate.m ================================================ // // AppDelegate.m // V2RayX // // Copyright © 2016年 Cenmrev. All rights reserved. // #import "AppDelegate.h" #import "GCDWebServer.h" #import "GCDWebServerDataResponse.h" #import "ConfigWindowController.h" #import #import "ServerProfile.h" #import "MutableDeepCopying.h" #import "ConfigImporter.h" #import "NSData+AES256Encryption.h" #define kUseAllServer -10 @interface AppDelegate () { GCDWebServer *webServer; ConfigWindowController *configWindowController; dispatch_queue_t taskQueue; dispatch_queue_t coreLoopQueue; dispatch_semaphore_t coreLoopSemaphore; NSTask* coreProcess; dispatch_source_t dispatchPacSource; FSEventStreamRef fsEventStream; NSData* v2rayJSONconfig; } @end @implementation AppDelegate static AppDelegate *appDelegate; - (NSData*)v2rayJSONconfig { return v2rayJSONconfig; } // a good reference: https://blog.gaelfoppolo.com/user-notifications-in-macos-66c25ed5c692 - (BOOL)userNotificationCenter:(NSUserNotificationCenter *)center shouldPresentNotification:(NSUserNotification *)notification { return YES; } - (void)userNotificationCenter:(NSUserNotificationCenter *)center didActivateNotification:(NSUserNotification *)notification { switch (notification.activationType) { case NSUserNotificationActivationTypeActionButtonClicked: [self inputPassword:self]; break; default: break; } } - (void)applicationDidFinishLaunching:(NSNotification *)aNotification { [[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate:self]; // check helper if (![self installHelper:false]) { [[NSApplication sharedApplication] terminate:nil];// installation failed or stopped by user, }; // prepare directory NSFileManager* fileManager = [NSFileManager defaultManager]; NSString *pacDir = [NSString stringWithFormat:@"%@/Library/Application Support/V2RayX/pac", NSHomeDirectory()]; //create application support directory and pac directory if (![fileManager fileExistsAtPath:pacDir]) { [fileManager createDirectoryAtPath:pacDir withIntermediateDirectories:YES attributes:nil error:nil]; } // Create Log Dir NSString* logDirName = @"cenmrev.v2rayx.log"; logDirPath = [NSString stringWithFormat:@"%@%@", NSTemporaryDirectory(), logDirName]; [fileManager createDirectoryAtPath:logDirPath withIntermediateDirectories:YES attributes:nil error:nil]; [fileManager createFileAtPath:[NSString stringWithFormat:@"%@/access.log", logDirPath] contents:nil attributes:nil]; [fileManager createFileAtPath:[NSString stringWithFormat:@"%@/error.log", logDirPath] contents:nil attributes:nil]; // initialize variables NSNumber* setingVersion = [[NSUserDefaults standardUserDefaults] objectForKey:@"setingVersion"]; if(setingVersion == nil || [setingVersion integerValue] != kV2RayXSettingVersion) { NSAlert *noServerAlert = [[NSAlert alloc] init]; [noServerAlert setMessageText:@"If you are running V2RayX for the first time, ignore this message. \nSorry, unknown settings!\nAll V2RayX settings will be reset."]; [noServerAlert runModal]; [self writeDefaultSettings]; //explicitly write default settings to user defaults file } v2rayJSONconfig = [[NSData alloc] init]; [self addObserver:self forKeyPath:@"selectedPacFileName" options:NSKeyValueObservingOptionNew context:nil]; // create a serial queue used for NSTask operations taskQueue = dispatch_queue_create("cenmrev.v2rayx.nstask", DISPATCH_QUEUE_SERIAL); // create a loop to run core coreLoopSemaphore = dispatch_semaphore_create(0); coreLoopQueue = dispatch_queue_create("cenmrev.v2rayx.coreloop", DISPATCH_QUEUE_SERIAL); dispatch_async(coreLoopQueue, ^{ while (true) { dispatch_semaphore_wait(self->coreLoopSemaphore, DISPATCH_TIME_FOREVER); self->coreProcess = [[NSTask alloc] init]; if (@available(macOS 10.13, *)) { [self->coreProcess setExecutableURL:[NSURL fileURLWithPath:[self getV2rayPath]]]; } else { [self->coreProcess setLaunchPath:[self getV2rayPath]]; } [self->coreProcess setArguments:@[@"-config", @"stdin:"]]; NSPipe* stdinpipe = [NSPipe pipe]; [self->coreProcess setStandardInput:stdinpipe]; NSData* configData = [NSJSONSerialization dataWithJSONObject:[self generateConfigFile] options:0 error:nil]; [[stdinpipe fileHandleForWriting] writeData:configData]; [self->coreProcess launch]; [[stdinpipe fileHandleForWriting] closeFile]; [self->coreProcess waitUntilExit]; NSLog(@"core exit with code %d", [self->coreProcess terminationStatus]); } }); // set up pac server __weak typeof(self) weakSelf = self; //http://stackoverflow.com/questions/14556605/capturing-self-strongly-in-this-block-is-likely-to-lead-to-a-retain-cycle webServer = [[GCDWebServer alloc] init]; [webServer addHandlerForMethod:@"GET" path:@"/proxy.pac" requestClass:[GCDWebServerRequest class] processBlock:^GCDWebServerResponse *(GCDWebServerRequest* request) { return [GCDWebServerDataResponse responseWithData:[weakSelf pacData] contentType:@"application/x-ns-proxy-autoconfig"]; }]; [webServer addHandlerForMethod:@"GET" path:@"/config.json" requestClass:[GCDWebServerRequest class] processBlock:^GCDWebServerResponse * _Nullable(__kindof GCDWebServerRequest * _Nonnull request) { return [GCDWebServerDataResponse responseWithData:[weakSelf v2rayJSONconfig] contentType:@"application/json"]; }]; [webServer startWithPort:webServerPort bonjourName:nil]; [self checkUpgrade:self]; appDelegate = self; // resume the service when mac wakes up [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(didChangeStatus:) name:NSWorkspaceDidWakeNotification object:NULL]; // initialize UI _statusBarItem = [[NSStatusBar systemStatusBar] statusItemWithLength:NSVariableStatusItemLength]; [_statusBarItem setHighlightMode:YES]; _pacModeItem.tag = pacMode; _globalModeItem.tag = globalMode; _manualModeItem.tag = manualMode; // read defaults [self readDefaults]; self.encryptionKey = @""; if (_enableEncryption && ([profiles count] > 0 || [_subscriptions count] > 0)) { NSUserNotification* notification = [[NSUserNotification alloc] init]; notification.identifier = [NSString stringWithFormat:@"cenmrev.v2rayx.passwork.%@", [NSUUID UUID]]; notification.title = @"Input Password"; notification.informativeText = @"input your password to continue"; notification.soundName = NSUserNotificationDefaultSoundName; notification.actionButtonTitle = @"Continue"; notification.hasActionButton = true; [[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification:notification]; [_statusBarItem setMenu:_authMenu]; [_statusBarItem setImage:[NSImage imageNamed:@"statusBarIcon_disabled"]]; } else { [self continueInitialization]; } } - (IBAction)inputPassword:(id)sender { NSAlert* alert = [[NSAlert alloc] init]; alert.messageText = @"input password to decrypt configurations"; [alert addButtonWithTitle:@"Decrypt"]; [alert addButtonWithTitle:@"Cancel"]; NSTextField *input = [[NSSecureTextField alloc] initWithFrame:NSMakeRect(0, 0, 200, 24)]; [input setStringValue:@""]; [alert setAccessoryView:input]; [input becomeFirstResponder]; [alert layout]; //important https://openmcl-devel.clozure.narkive.com/76HRbj5O/how-to-make-an-alert-accessory-view-be-first-responder [alert.window makeFirstResponder:input]; while (true) { NSModalResponse response = [alert runModal]; if (response == NSAlertSecondButtonReturn) { return; } else { BOOL result = [self decryptConfigurationsWithKey:[[input stringValue] stringByPaddingToLength:32 withString:@"-" startingAtIndex:0]]; if (result) { break; } } } [self continueInitialization]; } -(BOOL)decryptConfigurationsWithKey:(NSString*)key { NSMutableArray* decryptedLinks = [[NSMutableArray alloc] init]; for (NSString* encryptedLink in _subscriptions) { NSData* encryptedData = [[NSData alloc] initWithBase64EncodedString:encryptedLink options:NSDataBase64DecodingIgnoreUnknownCharacters]; NSData* decryptedData = [encryptedData decryptedDataWithKey:key]; if (decryptedData) { NSString* decryptedLink = [[NSString alloc] initWithData:decryptedData encoding:NSUTF8StringEncoding]; if (decryptedLink) { [decryptedLinks addObject:decryptedLink]; } else { return false; } } else { return false; } } NSMutableArray* decryptedProfiles = [[NSMutableArray alloc] init]; for (NSString* encryptedJSON in profiles) { NSData* encryptedData = [[NSData alloc] initWithBase64EncodedString:encryptedJSON options:NSDataBase64DecodingIgnoreUnknownCharacters]; NSData* decryptedData = [encryptedData decryptedDataWithKey:key]; if (decryptedData) { NSDictionary* decryptedProfile = [NSJSONSerialization JSONObjectWithData:decryptedData options:0 error:nil]; if (decryptedProfile) { [decryptedProfiles addObject:decryptedProfile]; } else { return false; } } else { return false; } } _subscriptions = decryptedLinks; profiles = decryptedProfiles; return true; } - (void)continueInitialization { [_statusBarItem setMenu:_statusBarMenu]; // start proxy [self updateSubscriptions:self]; // also includes [self didChangeStatus:self]; } - (BOOL)installHelper:(BOOL)force { NSFileManager *fileManager = [NSFileManager defaultManager]; if (!force && [fileManager fileExistsAtPath:kV2RayXHelper] && [self isSysconfVersionOK]) { // helper already installed return YES; } NSAlert *installAlert = [[NSAlert alloc] init]; [installAlert addButtonWithTitle:@"Install"]; [installAlert addButtonWithTitle:@"Quit"]; [installAlert setMessageText:@"V2RayX needs to install a small tool to /Library/Application Support/V2RayX/ with administrator privileges to set system proxy quickly.\nOtherwise you need to type in the administrator password every time you change system proxy through V2RayX."]; if ([installAlert runModal] == NSAlertFirstButtonReturn) { NSLog(@"start install"); NSString *helperPath = [NSString stringWithFormat:@"%@/%@", [[NSBundle mainBundle] resourcePath], @"install_helper.sh"]; NSLog(@"run install script: %@", helperPath); NSDictionary *error; NSString *script = [NSString stringWithFormat:@"do shell script \"bash %@\" with administrator privileges", helperPath]; NSAppleScript *appleScript = [[NSAppleScript new] initWithSource:script]; if ([appleScript executeAndReturnError:&error]) { NSLog(@"installation success"); return YES; } else { NSLog(@"installation failure"); //unknown failure return NO; } } else { // stopped by user return NO; } } - (BOOL)isSysconfVersionOK { NSTask *task; task = [[NSTask alloc] init]; if (@available(macOS 10.13, *)) { [task setExecutableURL:[NSURL fileURLWithPath:kV2RayXHelper]]; } else { [task setLaunchPath:kV2RayXHelper]; } NSArray *args; args = [NSArray arrayWithObjects:@"-v", nil]; [task setArguments: args]; NSPipe *pipe; pipe = [NSPipe pipe]; [task setStandardOutput:pipe]; NSFileHandle *fd; fd = [pipe fileHandleForReading]; [task launch]; NSData *data; data = [fd readDataToEndOfFile]; NSString *str; str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; if (![str isEqualToString:VERSION]) { return NO; } return YES; } - (IBAction)openReleasePage:(id)sender { [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"https://github.com/Cenmrev/V2RayX/releases/latest"]]; } - (IBAction)checkUpgrade:(id)sender { NSURL* url =[NSURL URLWithString:@"https://api.github.com/repos/cenmrev/v2rayx/releases/latest"]; NSURLSessionDataTask* task = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { @try { NSDictionary* d = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; if ([d[@"prerelease"] isEqualToNumber:@NO]) { NSNumberFormatter* f = [[NSNumberFormatter alloc] init]; f.numberStyle = NSNumberFormatterDecimalStyle; NSArray* newVersion = [[d[@"tag_name"] substringFromIndex:1] componentsSeparatedByString:@"."]; NSArray* currentVersion = [[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] componentsSeparatedByString:@"."]; for (int i = 0; i < 3; i += 1) { NSInteger newv = [[f numberFromString:newVersion[i]] integerValue]; NSInteger currentv = [[f numberFromString:currentVersion[i]] integerValue]; if (newv > currentv) { self.upgradeMenuItem.hidden = false; return; } } } } @catch (NSException *exception) { } @finally { ; } self.upgradeMenuItem.hidden = true; }]; [task resume]; } - (void)readDefaults { // just read defaults, didChangeStatus will handle invalid parameters. // return encrypted or not NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; NSDictionary* appStatus = nilCoalescing([defaults objectForKey:@"appStatus"], @{}); proxyState = [nilCoalescing(appStatus[@"proxyState"], @(NO)) boolValue]; //turn off proxy as default proxyMode = [nilCoalescing(appStatus[@"proxyMode"], @(manualMode)) integerValue]; selectedServerIndex = [nilCoalescing(appStatus[@"selectedServerIndex"], @0) integerValue]; selectedCusServerIndex = [nilCoalescing(appStatus[@"selectedCusServerIndex"], @0) integerValue]; _selectedRoutingSet = [nilCoalescing(appStatus[@"selectedRoutingSet"], @0) integerValue]; useMultipleServer = [nilCoalescing(appStatus[@"useMultipleServer"], @(NO)) boolValue]; useCusProfile = [nilCoalescing(appStatus[@"useCusProfile"], @(NO)) boolValue]; self.selectedPacFileName = nilCoalescing(appStatus[@"selectedPacFileName"], @"pac.js"); _enableEncryption = [nilCoalescing([defaults objectForKey:@"enableEncryption"], @(NO)) boolValue]; logLevel = nilCoalescing([defaults objectForKey:@"logLevel"], @"none"); localPort = [nilCoalescing([defaults objectForKey:@"localPort"], @1081) integerValue]; //use 1081 as default local port httpPort = [nilCoalescing([defaults objectForKey:@"httpPort"], @8001) integerValue]; //use 8001 as default local http port udpSupport = [nilCoalescing([defaults objectForKey:@"udpSupport"], @(NO)) boolValue];// do not support udp as default shareOverLan = [nilCoalescing([defaults objectForKey:@"shareOverLan"],@(NO)) boolValue]; dnsString = nilCoalescing([defaults objectForKey:@"dnsString"], @"localhost"); _enableRestore = [nilCoalescing([defaults objectForKey:@"enableRestore"],@(NO)) boolValue]; profiles = [[NSMutableArray alloc] init]; if ([defaults objectForKey:@"profiles"] && [[defaults objectForKey:@"profiles"] isKindOfClass:[NSArray class]]) { if (!_enableEncryption) { for (NSDictionary* aProfile in [defaults objectForKey:@"profiles"]) { if ([aProfile isKindOfClass:[NSDictionary class]] && aProfile[@"tag"] && [aProfile[@"tag"] length] && [RESERVED_TAGS indexOfObject:aProfile[@"tag"]] == NSNotFound) { [profiles addObject:aProfile]; } } } else { for (NSString* encrypted in [defaults objectForKey:@"profiles"]) { if ([encrypted isKindOfClass:[NSString class]]) { [profiles addObject:encrypted]; } } } } cusProfiles = [[NSMutableArray alloc] init]; if ([[defaults objectForKey:@"cusProfiles"] isKindOfClass:[NSArray class]] && [[defaults objectForKey:@"cusProfiles"] count] > 0) { for (id cusPorfile in [defaults objectForKey:@"cusProfiles"]) { if ([cusPorfile isKindOfClass:[NSString class]]) { [cusProfiles addObject:cusPorfile]; } } } _subscriptions = [[NSMutableArray alloc] init]; if ([defaults objectForKey:@"subscriptions"] && [[defaults objectForKey:@"subscriptions"] isKindOfClass:[NSArray class]]) { for (NSString* link in [defaults objectForKey:@"subscriptions"]) { if ([link isKindOfClass:[NSString class]]) { [_subscriptions addObject:link]; } } } _routingRuleSets = [@[ROUTING_GLOBAL, ROUTING_BYPASSCN_PRIVATE_APPLE, ROUTING_DIRECT] mutableDeepCopy]; if ([[defaults objectForKey:@"routingRuleSets"] isKindOfClass:[NSArray class]] && [[defaults objectForKey:@"routingRuleSets"] count] > 0) { _routingRuleSets = [[defaults objectForKey:@"routingRuleSets"] mutableDeepCopy]; } } - (void) writeDefaultSettings { NSDictionary *defaultSettings = @{ @"setingVersion": [NSNumber numberWithInteger:kV2RayXSettingVersion], @"appStatus": @{ @"proxyState": [NSNumber numberWithBool:NO], @"proxyMode": @(manualMode), @"selectedServerIndex": [NSNumber numberWithInteger:0], @"selectedCusServerIndex": [NSNumber numberWithInteger:-1], @"useCusProfile": @NO, @"selectedRoutingSet":@0, @"useMultipleServer": @NO, @"selectedPacFileName": @"pac.js" }, @"enableEncryption":@(NO), @"logLevel": @"none", @"localPort": [NSNumber numberWithInteger:1081], @"httpPort": [NSNumber numberWithInteger:8001], @"udpSupport": [NSNumber numberWithBool:NO], @"shareOverLan": [NSNumber numberWithBool:NO], @"dnsString": @"localhost", @"profiles":@[ [[[ServerProfile alloc] init] outboundProfile] ], @"cusProfiles": @[], @"enableRestore": @NO, @"routingRuleSets": @[ROUTING_GLOBAL, ROUTING_BYPASSCN_PRIVATE_APPLE, ROUTING_DIRECT], }; for (NSString* key in [defaultSettings allKeys]) { [[NSUserDefaults standardUserDefaults] setObject:defaultSettings[key] forKey:key]; } } - (NSData*) pacData { return [NSData dataWithContentsOfFile:[NSString stringWithFormat:@"%@/Library/Application Support/V2RayX/pac/%@",NSHomeDirectory(), selectedPacFileName]]; } - (void)saveAppStatus { NSDictionary* status = @{ @"proxyState": @(proxyState), @"proxyMode": @(proxyMode), @"selectedServerIndex": @(selectedServerIndex), @"selectedCusServerIndex": @(selectedCusServerIndex), @"useCusProfile": @(useCusProfile), @"selectedRoutingSet":@(_selectedRoutingSet), @"useMultipleServer": @(useMultipleServer), @"selectedPacFileName": selectedPacFileName }; [[NSUserDefaults standardUserDefaults] setObject:status forKey:@"appStatus"]; } - (void)saveConfigInfo { dispatch_async(taskQueue, ^{ NSMutableArray* subscriptionToSave; NSMutableArray* profilesToSave; if (self->_enableEncryption) { subscriptionToSave = [[NSMutableArray alloc] init]; for (NSString* link in self->_subscriptions) { [subscriptionToSave addObject:[[[link dataUsingEncoding:NSUTF8StringEncoding] encryptedDataWithKey:self->_encryptionKey] base64EncodedStringWithOptions:0]]; } profilesToSave = [[NSMutableArray alloc] init]; for (NSDictionary* profile in self->profiles) { NSData* jsonData = [NSJSONSerialization dataWithJSONObject:profile options:0 error:nil]; [profilesToSave addObject:[[jsonData encryptedDataWithKey:self->_encryptionKey] base64EncodedStringWithOptions:0]]; } } else { subscriptionToSave = self->_subscriptions; profilesToSave = self->profiles; } NSDictionary *settings = @{ @"enableEncryption":@(self->_enableEncryption), @"setingVersion": [NSNumber numberWithInteger:kV2RayXSettingVersion], @"logLevel": self.logLevel, @"localPort": @(self.localPort), @"httpPort": @(self.httpPort), @"udpSupport": @(self.udpSupport), @"shareOverLan": @(self.shareOverLan), @"dnsString": self.dnsString, @"profiles":profilesToSave, @"cusProfiles": self.cusProfiles, @"subscriptions": subscriptionToSave, @"routingRuleSets": self.routingRuleSets, @"enableRestore": @(self.enableRestore) }; for (NSString* key in [settings allKeys]) { [[NSUserDefaults standardUserDefaults] setObject:settings[key] forKey:key]; } NSLog(@"Settings saved."); }); } - (void)applicationWillTerminate:(NSNotification *)aNotification { //stop monitor pac if (dispatchPacSource) { dispatch_source_cancel(dispatchPacSource); } //unload v2ray //runCommandLine(@"/bin/launchctl", @[@"unload", plistPath]); [self unloadV2ray]; NSLog(@"V2RayX quiting, V2Ray core unloaded."); //remove log file [[NSFileManager defaultManager] removeItemAtPath:logDirPath error:nil]; //save application status [self saveAppStatus]; //turn off proxy if (proxyState && proxyMode != manualMode) { _enableRestore ? [self restoreSystemProxy] : [self cancelSystemProxy]; //restore system proxy } } - (IBAction)showHelp:(id)sender { [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"https://www.v2ray.com"]]; } // v2rayx status part // back up system proxy state when V2RayX starts to take control of // macOS's proxy settings, which means: // 1. proxy status is On and not changed, but proxy mode changes from manual to non-manual => happens when didChangeMode // or 2. proxy status was off and now is turned on, and the proxy mode is non-manual => happens when didChangeStatus // restore system proxy state when V2RayX stops taking control of macOS's proxy settings, which means: // 1. proxy state is On and not changed, but proxy mode changes from non-manual mode to manual mode => happens when didChangeMode // or 2. proxy state was on and now is turned off, and the proxy mode is non-manual => happens when didChangeStatus -(void)backupSystemProxy { SCPreferencesRef prefRef = SCPreferencesCreate(nil, CFSTR("V2RayX"), nil); NSDictionary* sets = (__bridge NSDictionary *)SCPreferencesGetValue(prefRef, kSCPrefNetworkServices); [sets writeToURL:[NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/Library/Application Support/V2RayX/system_proxy_backup.plist",NSHomeDirectory()]] atomically:NO]; } -(void)restoreSystemProxy { dispatch_async(taskQueue, ^{ runCommandLine(kV2RayXHelper,@[@"restore"]); }); } -(void)cancelSystemProxy { dispatch_async(taskQueue, ^{ runCommandLine(kV2RayXHelper,@[@"off"]); }); } - (IBAction)didChangeStatus:(id)sender { NSInteger previousStatus = proxyState; if (sender == self) { previousStatus = false; } // sender can be // 1. self, when app is launched // 2. menuitem, when a user click on a server or a routing or updateSeverMenuItem // 3. configwindow controller if (sender == _enableV2rayItem) { proxyState = !proxyState; } // make sure current status parameter is valid selectedServerIndex = MIN((NSInteger)profiles.count + (NSInteger)_subsOutbounds.count - 1, selectedServerIndex); if (profiles.count + _subsOutbounds.count > 0) { selectedServerIndex = MAX(selectedServerIndex, 0); } selectedCusServerIndex = MIN((NSInteger)cusProfiles.count - 1, selectedCusServerIndex ); _selectedRoutingSet = MIN((NSInteger)_routingRuleSets.count - 1, _selectedRoutingSet); NSLog(@"%ld, %ld", selectedServerIndex, selectedCusServerIndex); if ((!useMultipleServer && selectedServerIndex == -1 && selectedCusServerIndex == -1) || (useMultipleServer && profiles.count + _subsOutbounds.count < 1)) { proxyState = false; } else if (!useMultipleServer && selectedCusServerIndex == -1) { useCusProfile = false; } else if (!useMultipleServer && selectedServerIndex == -1) { useCusProfile = true; } if (proxyMode != manualMode) { if (previousStatus == false && proxyState == true) { [self backupSystemProxy]; } else if (previousStatus == true && proxyState == false ) { _enableRestore ? [self restoreSystemProxy] : [self cancelSystemProxy]; } } [self coreConfigDidChange:self]; if (proxyState == true) { [self updateSystemProxy]; } else { [self unloadV2ray]; } [self updateMenus]; [self updatePacMenuList]; } - (IBAction)didChangeMode:(id)sender { if (proxyState == true && proxyMode == manualMode && [sender tag] != manualMode) { [self backupSystemProxy]; } if (proxyState == true && proxyMode != manualMode && [sender tag] == manualMode) { _enableRestore ? [self restoreSystemProxy] : [self cancelSystemProxy]; } proxyMode = [sender tag]; [self updateMenus]; if (sender == _pacModeItem) { [self updatePacMenuList]; } if (proxyState == true) { [self updateSystemProxy]; } } - (void)updateMenus { if (proxyState) { [_v2rayStatusItem setTitle:@"v2ray-core: loaded"]; [_enableV2rayItem setTitle:@"Unload core"]; NSImage *icon = [NSImage imageNamed:@"statusBarIcon"]; [icon setTemplate:YES]; [_statusBarItem setImage:icon]; } else { [_v2rayStatusItem setTitle:@"v2ray-core: unloaded"]; [_enableV2rayItem setTitle:@"Load core"]; [_statusBarItem setImage:[NSImage imageNamed:@"statusBarIcon_disabled"]]; } [_pacModeItem setState:proxyMode == pacMode]; [_manualModeItem setState:proxyMode == manualMode]; [_globalModeItem setState:proxyMode == globalMode]; } - (void)updatePacMenuList { NSLog(@"updatePacMenuList"); [_pacListMenu removeAllItems]; NSString *pacDir = [NSString stringWithFormat:@"%@/Library/Application Support/V2RayX/pac", NSHomeDirectory()]; NSFileManager *manager = [NSFileManager defaultManager]; NSArray *allPath =[manager subpathsAtPath:pacDir]; int i = 0; for (NSString *subPath in allPath) { NSString *extString = [subPath pathExtension]; if (![extString isEqual: @"js"]){ continue; } NSString *itemTitle = subPath; NSMenuItem *newItem = [[NSMenuItem alloc] initWithTitle:itemTitle action:@selector(switchPac:) keyEquivalent:@""]; newItem.state = [itemTitle isEqualToString:selectedPacFileName]; [newItem setTag:i]; [_pacListMenu addItem:newItem]; i++; } [_pacListMenu addItem:[NSMenuItem separatorItem]]; [_pacListMenu addItem:_editPacMenuItem]; } - (IBAction)editPac:(id)sender { [[NSWorkspace sharedWorkspace] activateFileViewerSelectingURLs:@[[NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/Library/Application Support/V2RayX/pac/%@",NSHomeDirectory(), selectedPacFileName]]]]; } - (IBAction)resetPac:(id)sender { NSAlert *resetAlert = [[NSAlert alloc] init]; [resetAlert setMessageText:@"The pac file will be reset to the original one coming with V2RayX. Are you sure to proceed?"]; [resetAlert addButtonWithTitle:@"Yes"]; [resetAlert addButtonWithTitle:@"Cancel"]; NSModalResponse response = [resetAlert runModal]; if(response == NSAlertFirstButtonReturn) { NSString* simplePac = [[NSBundle mainBundle] pathForResource:@"simple" ofType:@"pac"]; NSString* pacPath = [NSString stringWithFormat:@"%@/Library/Application Support/V2RayX/pac/%@",NSHomeDirectory(), selectedPacFileName]; if ([[NSFileManager defaultManager] isWritableFileAtPath:pacPath]) { [[NSData dataWithContentsOfFile:simplePac] writeToFile:pacPath atomically:YES]; } else { NSAlert* writePacAlert = [[NSAlert alloc] init]; [writePacAlert setMessageText:[NSString stringWithFormat:@"%@ is not writable!", pacPath]]; [writePacAlert runModal]; } } } - (void)switchPac:(id)sender { [self setSelectedPacFileName:[sender title]]; [self didChangeMode:_pacModeItem]; } -(void)updateSystemProxy { NSArray *arguments; if (proxyState) { if (proxyMode == pacMode) { // pac mode // close system proxy first to refresh pac file dispatch_async(taskQueue, ^{ runCommandLine(kV2RayXHelper, @[@"off"]); }); arguments = @[@"auto"]; } else { if (proxyMode == manualMode) { // manualMode mode arguments = @[@"-v"]; // do nothing } else { // global mode if(useMultipleServer || !useCusProfile) { arguments = @[@"global", [NSString stringWithFormat:@"%ld", localPort], [NSString stringWithFormat:@"%ld", httpPort]]; } else { NSInteger cusHttpPort = 0; NSInteger cusSocksPort = 0; NSDictionary* cusJson = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:cusProfiles[selectedCusServerIndex]] options:0 error:nil]; if (cusJson[@"inboundDetour"] != nil && [cusJson[@"inboundDetour"] isKindOfClass:[NSArray class]]) { for (NSDictionary *inboundDetour in cusJson[@"inboundDetour"]) { if ([inboundDetour[@"protocol"] isEqualToString:@"http"]) { cusHttpPort = [inboundDetour[@"port"] integerValue]; } if ([inboundDetour[@"protocol"] isEqualToString:@"socks"]) { cusSocksPort = [inboundDetour[@"port"] integerValue]; } } } if ([cusJson[@"inbound"][@"protocol"] isEqualToString:@"http"]) { cusHttpPort = [cusJson[@"inbound"][@"port"] integerValue]; } if ([cusJson[@"inbound"][@"protocol"] isEqualToString:@"socks"]) { cusSocksPort = [cusJson[@"inbound"][@"port"] integerValue]; } NSLog(@"socks: %ld, http: %ld", cusSocksPort, cusHttpPort); arguments = @[@"global", [NSString stringWithFormat:@"%ld", cusSocksPort], [NSString stringWithFormat:@"%ld", cusHttpPort]]; } } } dispatch_async(taskQueue, ^{ runCommandLine(kV2RayXHelper,arguments); }); } else { ; // do nothing } NSLog(@"system proxy state:%@,%ld",proxyState?@"on":@"off", (long)proxyMode); } // core part - (IBAction)updateSubscriptions:(id)sender { // sender can be self -> called when app is started // or menuItem -> called by user _subsOutbounds = [[NSMutableArray alloc] init]; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ for (NSString* link in self.subscriptions) { NSDictionary* r = [ConfigImporter importFromHTTPSubscription:link]; if (r) { for (ServerProfile* p in r[@"vmess"]) { [self.subsOutbounds addObject:[p outboundProfile]]; } [self.subsOutbounds addObjectsFromArray:r[@"other"]]; } } // not safe, need to make sure every tag is unique dispatch_async(dispatch_get_main_queue(), ^{ [self didChangeStatus:sender]; }); }); } - (void)updateRuleSetMenuList { [_ruleSetMenuList removeAllItems]; NSInteger i = 0; for (NSDictionary* rule in _routingRuleSets) { NSMenuItem* item = [[NSMenuItem alloc] initWithTitle:rule[@"name"] action:@selector(switchRoutingSet:) keyEquivalent:@""]; item.tag = i; item.state = i == _selectedRoutingSet; [_ruleSetMenuList addItem:item]; i += 1; } } - (void)updateServerMenuList { [_serverListMenu removeAllItems]; if ([profiles count] == 0 && [cusProfiles count] == 0 && [_subsOutbounds count] == 0) { [_serverListMenu addItem:[[NSMenuItem alloc] initWithTitle:@"no available servers, please add server profiles through config window." action:nil keyEquivalent:@""]]; if (_subscriptions.count > 0) { [_serverListMenu addItem:[NSMenuItem separatorItem]]; [_serverListMenu addItem:_updateServerItem]; } } else { int i = 0; for (NSDictionary *p in profiles) { NSString *itemTitle = nilCoalescing(p[@"tag"], @""); NSMenuItem *newItem = [[NSMenuItem alloc] initWithTitle:itemTitle action:@selector(switchServer:) keyEquivalent:@""]; [newItem setTag:i]; if (useMultipleServer){ newItem.state = 0; } else { newItem.state = (!useCusProfile && i == selectedServerIndex); } [_serverListMenu addItem:newItem]; i += 1; } for (NSDictionary* p in _subsOutbounds) { NSString *itemTitle = nilCoalescing(p[@"tag"], @"from subscription"); NSMenuItem *newItem = [[NSMenuItem alloc] initWithTitle:itemTitle action:@selector(switchServer:) keyEquivalent:@""]; [newItem setTag:i]; if (useMultipleServer){ newItem.state = 0; } else { newItem.state = (!useCusProfile && i == selectedServerIndex); } [_serverListMenu addItem:newItem]; i += 1; } if([profiles count] + [_subsOutbounds count]> 0) { NSMenuItem *newItem = [[NSMenuItem alloc] initWithTitle:@"Use All" action:@selector(switchServer:) keyEquivalent:@""]; [newItem setTag:kUseAllServer]; newItem.state = useMultipleServer & !useCusProfile; [_serverListMenu addItem:newItem]; } if (_subscriptions.count > 0) { [_serverListMenu addItem:[NSMenuItem separatorItem]]; [_serverListMenu addItem:_updateServerItem]; } if (cusProfiles.count > 0) { [_serverListMenu addItem:[NSMenuItem separatorItem]]; } for (NSString* cusProfilePath in cusProfiles) { NSString *itemTitle = [[cusProfilePath componentsSeparatedByString:@"/"] lastObject]; NSMenuItem *newItem = [[NSMenuItem alloc] initWithTitle:itemTitle action:@selector(switchServer:) keyEquivalent:@""]; [newItem setTag:i]; if (useMultipleServer){ newItem.state = 0; } else { newItem.state = (useCusProfile && i - [profiles count] - [_subsOutbounds count] == selectedCusServerIndex)? 1 : 0; } [_serverListMenu addItem:newItem]; i += 1; } } } - (IBAction)coreConfigDidChange:(id)sender { if (proxyState == true) { if (!useMultipleServer && useCusProfile) { v2rayJSONconfig = [NSData dataWithContentsOfFile:cusProfiles[selectedCusServerIndex]]; } else { NSDictionary *fullConfig = [self generateConfigFile]; v2rayJSONconfig = [NSJSONSerialization dataWithJSONObject:fullConfig options:NSJSONWritingPrettyPrinted error:nil]; } //[self generateLaunchdPlist:plistPath]; [self toggleCore]; } [self updateServerMenuList]; [self updateRuleSetMenuList]; } -(void)toggleCore { [self unloadV2ray]; dispatch_semaphore_signal(coreLoopSemaphore); // dispatch_async(taskQueue, ^{ // runCommandLine(@"/bin/launchctl", @[@"unload", self->plistPath]); // runCommandLine(@"/bin/cp", @[@"/dev/null", [NSString stringWithFormat:@"%@/access.log", self->logDirPath]]); // runCommandLine(@"/bin/cp", @[@"/dev/null", [NSString stringWithFormat:@"%@/error.log", self->logDirPath]]); // runCommandLine(@"/bin/launchctl", @[@"load", self->plistPath]); // }); } - (IBAction)showConfigWindow:(id)sender { if (configWindowController) { [configWindowController close]; } configWindowController =[[ConfigWindowController alloc] initWithWindowNibName:@"ConfigWindow"]; configWindowController.appDelegate = self; [configWindowController showWindow:self]; [NSApp activateIgnoringOtherApps:YES]; [configWindowController.window makeKeyAndOrderFront:nil]; } - (IBAction)backupConfigs:(id)sender { NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"dd-MM-yyyy HH:mm"]; NSDate *currentDate = [NSDate date]; NSString *dateString = [formatter stringFromDate:currentDate]; NSMutableDictionary *backup = [[NSMutableDictionary alloc] init]; backup[@"outbounds"] = self.profiles; backup[@"routings"] = self.routingRuleSets; NSData* backupData = [NSJSONSerialization dataWithJSONObject:backup options:NSJSONWritingPrettyPrinted error:nil]; NSString* backupPath = [NSString stringWithFormat:@"%@/v2rayx_backup_%@.json", NSHomeDirectory(), dateString]; [backupData writeToFile:backupPath atomically:YES]; [[NSWorkspace sharedWorkspace] activateFileViewerSelectingURLs:@[[NSURL fileURLWithPath:backupPath]]]; } -(IBAction)switchRoutingSet:(id)sender { _selectedRoutingSet = [sender tag]; [self coreConfigDidChange:self]; } - (void)switchServer:(id)sender { NSInteger outboundCount = [profiles count] + [_subsOutbounds count]; if ([sender tag] >= 0 && [sender tag] < outboundCount) { [self setUseMultipleServer:NO]; [self setUseCusProfile:NO]; [self setSelectedServerIndex:[sender tag]]; } else if ([sender tag] >= outboundCount && [sender tag] < outboundCount + [cusProfiles count]) { [self setUseMultipleServer:NO]; [self setUseCusProfile:YES]; [self setSelectedCusServerIndex:[sender tag] - outboundCount]; } else if ([sender tag] == kUseAllServer) { [self setUseMultipleServer:YES]; [self setUseCusProfile:NO]; } NSLog(@"use cus pro:%hhd, select %ld, select cus %ld", useCusProfile, (long)selectedServerIndex, selectedCusServerIndex); [self coreConfigDidChange:self]; } -(void)unloadV2ray { if (coreProcess && [coreProcess isRunning]) { [coreProcess terminate]; } // dispatch_async(taskQueue, ^{ // runCommandLine(@"/bin/launchctl", @[@"unload", self->plistPath]); // NSLog(@"V2Ray core unloaded."); // }); } - (NSDictionary*)generateConfigFile { NSMutableDictionary* fullConfig = [NSMutableDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"config-sample_new" ofType:@"plist"]]; fullConfig[@"log"] = @{ @"access": [NSString stringWithFormat:@"%@/access.log", logDirPath], @"error": [NSString stringWithFormat:@"%@/error.log", logDirPath], @"loglevel": logLevel }; fullConfig[@"inbounds"][0][@"port"] = @(localPort); fullConfig[@"inbounds"][0][@"listen"] = shareOverLan ? @"0.0.0.0" : @"127.0.0.1"; fullConfig[@"inbounds"][0][@"settings"][@"udp"] = [NSNumber numberWithBool:udpSupport]; fullConfig[@"inbounds"][1][@"port"] = @(httpPort); fullConfig[@"inbounds"][1][@"listen"] = shareOverLan ? @"0.0.0.0" : @"127.0.0.1"; NSArray* dnsArray = [dnsString componentsSeparatedByString:@","]; if ([dnsArray count] > 0) { fullConfig[@"dns"][@"servers"] = dnsArray; } else { fullConfig[@"dns"][@"servers"] = @[@"localhost"]; } // deal with outbound NSMutableDictionary* configOutboundDict = [[NSMutableDictionary alloc] init]; NSMutableDictionary* allUniqueTagOutboundDict = [[NSMutableDictionary alloc] init]; // make sure tag is unique NSMutableArray* allOutbounds = [profiles mutableCopy]; [allOutbounds addObjectsFromArray:_subsOutbounds]; for (NSDictionary* outbound in profiles) { allUniqueTagOutboundDict[outbound[@"tag"]] = [outbound mutableDeepCopy]; } for (NSDictionary* outbound in _subsOutbounds) { allUniqueTagOutboundDict[outbound[@"tag"]] = [outbound mutableDeepCopy]; } NSArray* allProxyTags = allUniqueTagOutboundDict.allKeys; allUniqueTagOutboundDict[@"direct"] = OUTBOUND_DIRECT; allUniqueTagOutboundDict[@"decline"] = OUTBOUND_DECLINE; fullConfig[@"routing"] = [_routingRuleSets[_selectedRoutingSet] mutableDeepCopy]; if (!useMultipleServer) { // replace tag main with current selected outbound tag NSString* currentMainTag = allOutbounds[selectedServerIndex][@"tag"]; for (NSMutableDictionary* aRule in fullConfig[@"routing"][@"rules"]) { if ([@"main" isEqualToString:aRule[@"outboundTag"]]) { aRule[@"outboundTag"] = currentMainTag; } } } else { // replace outbound tag main with balancetag for (NSMutableDictionary* aRule in fullConfig[@"routing"][@"rules"]) { if ([@"main" isEqualToString:aRule[@"outboundTag"]]) { [aRule removeObjectForKey:@"outboundTag"]; [aRule setObject:@"balance" forKey:@"balancerTag"]; } } } // NSLog(@"%@", allOutbounds); BOOL usebalance = false; for (NSDictionary* rule in fullConfig[@"routing"][@"rules"]) { if (rule[@"balancerTag"] && !rule[@"outboundTag"]) { // if any rule uses balancer, stop the loop and add a balancer to the routing part usebalance = true; break; } else { // pick up all mentioned outbounds in the routing rule set if (allUniqueTagOutboundDict[rule[@"outboundTag"]]) { configOutboundDict[rule[@"outboundTag"]] = allUniqueTagOutboundDict[rule[@"outboundTag"]]; } } } if (usebalance) { // if balancer is used, add all outbounds into config file, and add all tags to the balancer selector fullConfig[@"routing"][@"balancers"] = @[@{ @"tag":@"balance", @"selector": allProxyTags }]; fullConfig[@"outbounds"] = allUniqueTagOutboundDict.allValues; } else { // otherwise, we convert all collected outbounds into an array fullConfig[@"outbounds"] = configOutboundDict.allValues; } return fullConfig; } //-(void)generateLaunchdPlist:(NSString*)path { // NSString* v2rayPath = [self getV2rayPath]; // NSLog(@"use core: %@", v2rayPath); // NSString *configPath = [NSString stringWithFormat:@"http://127.0.0.1:%d/config.json", webServerPort]; // NSDictionary *runPlistDic = [[NSDictionary alloc] initWithObjects:@[@"v2rayproject.v2rayx.v2ray-core", @[v2rayPath, @"-config", configPath], [NSNumber numberWithBool:YES]] forKeys:@[@"Label", @"ProgramArguments", @"RunAtLoad"]]; // [runPlistDic writeToFile:path atomically:NO]; //} -(NSString*)getV2rayPath { NSString* defaultV2ray = [NSString stringWithFormat:@"%@/v2ray", [[NSBundle mainBundle] resourcePath]]; NSFileManager* fileManager = [NSFileManager defaultManager]; NSString* cusV2ray = [NSString stringWithFormat:@"%@/Library/Application Support/V2RayX/v2ray-core/v2ray",NSHomeDirectory()]; for (NSString* binary in @[@"v2ray", @"v2ctl"]) { NSString* fullpath = [NSString stringWithFormat:@"%@/Library/Application Support/V2RayX/v2ray-core/%@",NSHomeDirectory(), binary]; BOOL isDir = YES; if (![fileManager fileExistsAtPath:fullpath isDirectory:&isDir] || isDir || ![fileManager setAttributes:@{NSFilePosixPermissions: [NSNumber numberWithShort:0777]} ofItemAtPath:fullpath error:nil]) { return defaultV2ray; } } for (NSString* data in @[@"geoip.dat", @"geosite.dat"]) { NSString* fullpath = [NSString stringWithFormat:@"%@/Library/Application Support/V2RayX/v2ray-core/%@",NSHomeDirectory(), data]; BOOL isDir = YES; if (![fileManager fileExistsAtPath:fullpath isDirectory:&isDir] || isDir ) { return defaultV2ray; } } return cusV2ray; } - (IBAction)authorizeV2sys:(id)sender { [self installHelper:true]; } - (IBAction)viewLog:(id)sender { if (!useCusProfile) { [[NSWorkspace sharedWorkspace] openFile:logDirPath]; } else { NSAlert *alert = [[NSAlert alloc] init]; [alert setMessageText:[NSString stringWithFormat:@"Check %@.", cusProfiles[selectedCusServerIndex]]]; [alert runModal]; } } - (IBAction)copyExportCmd:(id)sender { if (!useCusProfile) { [[NSPasteboard generalPasteboard] clearContents]; NSString* command = [NSString stringWithFormat:@"export http_proxy=\"http://127.0.0.1:%ld\"; export HTTP_PROXY=\"http://127.0.0.1:%ld\"; export https_proxy=\"http://127.0.0.1:%ld\"; export HTTPS_PROXY=\"http://127.0.0.1:%ld\"", httpPort, httpPort, httpPort, httpPort]; [[NSPasteboard generalPasteboard] setString:command forType:NSStringPboardType]; } else { NSAlert *alert = [[NSAlert alloc] init]; [alert setMessageText:[NSString stringWithFormat:@"Check %@.", cusProfiles[selectedCusServerIndex]]]; [alert runModal]; } } - (IBAction)viewConfigJson:(NSMenuItem *)sender { [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://127.0.0.1:%d/config.json", webServerPort]]]; } int runCommandLine(NSString* launchPath, NSArray* arguments) { NSTask *task = [[NSTask alloc] init]; [task setLaunchPath:launchPath]; [task setArguments:arguments]; NSPipe *stdoutpipe = [NSPipe pipe]; [task setStandardOutput:stdoutpipe]; NSPipe *stderrpipe = [NSPipe pipe]; [task setStandardError:stderrpipe]; NSFileHandle *file; file = [stdoutpipe fileHandleForReading]; [task launch]; NSData *data; data = [file readDataToEndOfFile]; NSString *string; string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; if (string.length > 0) { NSLog(@"%@", string); } file = [stderrpipe fileHandleForReading]; data = [file readDataToEndOfFile]; string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; if (string.length > 0) { NSLog(@"%@", string); } [task waitUntilExit]; return task.terminationStatus; } - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if ([@"selectedPacFileName" isEqualToString:keyPath]) { NSLog(@"pac file is switched to %@", selectedPacFileName); if (dispatchPacSource) { //stop monitor previous pac dispatch_source_cancel(dispatchPacSource); } if (selectedPacFileName == nil || selectedPacFileName.length == 0) { return; } NSString* pacFullPath = [NSString stringWithFormat:@"%@/Library/Application Support/V2RayX/pac/%@",NSHomeDirectory(), selectedPacFileName]; if (![[NSFileManager defaultManager] fileExistsAtPath:pacFullPath]) { NSString* simplePac = [[NSBundle mainBundle] pathForResource:@"simple" ofType:@"pac"]; [[NSFileManager defaultManager] copyItemAtPath:simplePac toPath:pacFullPath error:nil]; } //https://randexdev.com/2012/03/how-to-detect-directory-changes-using-gcd/ int fildes = open([pacFullPath cStringUsingEncoding:NSUTF8StringEncoding], O_RDONLY); dispatchPacSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_VNODE, fildes, DISPATCH_VNODE_WRITE | DISPATCH_VNODE_EXTEND, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)); dispatch_source_set_event_handler(dispatchPacSource, ^{ NSLog(@"pac file changed"); if (self.proxyMode == pacMode && self.proxyState == true) { [appDelegate updateSystemProxy]; NSLog(@"refreshed system pacfile."); } }); dispatch_resume(dispatchPacSource); } } @synthesize logDirPath; @synthesize proxyState; @synthesize proxyMode; @synthesize localPort; @synthesize httpPort; @synthesize udpSupport; @synthesize shareOverLan; @synthesize selectedServerIndex; @synthesize selectedPacFileName; @synthesize dnsString; @synthesize profiles; @synthesize logLevel; @synthesize cusProfiles; @synthesize useCusProfile; @synthesize selectedCusServerIndex; @synthesize useMultipleServer; @end ================================================ FILE: V2RayX/Assets.xcassets/AppIcon.appiconset/Contents.json ================================================ { "images" : [ { "size" : "16x16", "idiom" : "mac", "filename" : "vx16.png", "scale" : "1x" }, { "size" : "16x16", "idiom" : "mac", "filename" : "vx32.png", "scale" : "2x" }, { "size" : "32x32", "idiom" : "mac", "filename" : "vx32.png", "scale" : "1x" }, { "size" : "32x32", "idiom" : "mac", "filename" : "vx64.png", "scale" : "2x" }, { "size" : "128x128", "idiom" : "mac", "filename" : "vx128.png", "scale" : "1x" }, { "size" : "128x128", "idiom" : "mac", "filename" : "vx256.png", "scale" : "2x" }, { "size" : "256x256", "idiom" : "mac", "filename" : "vx256.png", "scale" : "1x" }, { "size" : "256x256", "idiom" : "mac", "filename" : "vx 512.png", "scale" : "2x" }, { "size" : "512x512", "idiom" : "mac", "filename" : "vx 512.png", "scale" : "1x" }, { "idiom" : "mac", "size" : "512x512", "scale" : "2x" } ], "info" : { "version" : 1, "author" : "xcode" } } ================================================ FILE: V2RayX/Assets.xcassets/Contents.json ================================================ { "info" : { "version" : 1, "author" : "xcode" } } ================================================ FILE: V2RayX/Assets.xcassets/config_duplicate.imageset/Contents.json ================================================ { "images" : [ { "idiom" : "universal", "filename" : "duplicate-document16.png", "scale" : "1x" }, { "idiom" : "universal", "filename" : "duplicate-document.png", "scale" : "2x" }, { "idiom" : "universal", "scale" : "3x" } ], "info" : { "version" : 1, "author" : "xcode" } } ================================================ FILE: V2RayX/Assets.xcassets/statusBarIcon.imageset/Contents.json ================================================ { "images" : [ { "idiom" : "universal", "filename" : "b16.png", "scale" : "1x" }, { "idiom" : "universal", "filename" : "b32.png", "scale" : "2x" }, { "idiom" : "universal", "scale" : "3x" } ], "info" : { "version" : 1, "author" : "xcode" } } ================================================ FILE: V2RayX/Assets.xcassets/statusBarIcon_disabled.imageset/Contents.json ================================================ { "images" : [ { "idiom" : "universal", "filename" : "g16.png", "scale" : "1x" }, { "idiom" : "universal", "filename" : "g32.png", "scale" : "2x" }, { "idiom" : "universal", "scale" : "3x" } ], "info" : { "version" : 1, "author" : "xcode" } } ================================================ FILE: V2RayX/Base.lproj/MainMenu.xib ================================================ Default Left to Right Right to Left Default Left to Right Right to Left ================================================ FILE: V2RayX/ConfigImporter.h ================================================ // // ConfigImporter.h // V2RayX // // #import #import "ServerProfile.h" NS_ASSUME_NONNULL_BEGIN @interface ConfigImporter : NSObject + (NSDictionary*)parseStandardSSLink:(NSString*)link; + (NSMutableDictionary*)ssOutboundFromSSLink:(NSString*)link; + (NSMutableDictionary*)ssOutboundFromSSConfig:(NSDictionary*)jsonObject; + (ServerProfile*)importFromVmessOfV2RayN:(NSString*)vmessStr; + (NSMutableDictionary*)importFromHTTPSubscription:(NSString*)httpLink; + (NSMutableDictionary*)importFromStandardConfigFiles:(NSArray*)files; + (NSMutableDictionary*)validateRuleSet:(NSMutableDictionary*)set; + (NSMutableDictionary* _Nonnull)importFromSubscriptionOfSSD: (NSString* _Nonnull)ssdLink; @end NS_ASSUME_NONNULL_END ================================================ FILE: V2RayX/ConfigImporter.m ================================================ // // ConfigImporter.m // V2RayX // // #import "ConfigImporter.h" #import "utilities.h" @implementation ConfigImporter + (NSString* _Nonnull)decodeBase64String:(NSString*)encoded { if (!encoded || ![encoded isKindOfClass:[NSString class]] || encoded.length == 0) { return @""; } NSMutableString* fixed = [encoded mutableCopy]; NSInteger numAdd = (4 - encoded.length % 4) % 4; for (int i = 0; i < numAdd; i += 1) { [fixed appendString:@"="]; } @try { NSData* decodedData = [[NSData alloc] initWithBase64EncodedString:fixed options:NSDataBase64DecodingIgnoreUnknownCharacters]; NSString* decodedString = [[NSString alloc] initWithData:decodedData encoding:NSUTF8StringEncoding]; assert(decodedString != nil); return decodedString; } @catch (NSException *exception) { return @""; } } + (NSDictionary*)parseLegacySSLink:(NSString*)link { //http://shadowsocks.org/en/config/quick-guide.html @try { NSString* encoded = [[link stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] substringFromIndex:5]; NSArray* hashTagSeperatedParts = [encoded componentsSeparatedByString:@"#"]; NSString* encodedRemoveTag = hashTagSeperatedParts[0]; NSString* decoded = [ConfigImporter decodeBase64String:encodedRemoveTag]; NSArray* parts = [decoded componentsSeparatedByString:@"@"]; NSArray* addressAndPort = [parts[1] componentsSeparatedByString:@":"]; NSMutableArray* methodAndPassword = [[parts[0] componentsSeparatedByString:@":"] mutableCopy]; NSString* method = methodAndPassword[0]; [methodAndPassword removeObjectAtIndex:0]; NSNumberFormatter* f = [[NSNumberFormatter alloc] init]; f.numberStyle = NSNumberFormatterDecimalStyle; NSNumber *port = [f numberFromString:addressAndPort[1]]; if (hashTagSeperatedParts.count == 1) { return @{ @"server":addressAndPort[0], @"server_port":port, @"password": [methodAndPassword componentsJoinedByString:@":"], @"method":method}; } else { return @{ @"server":addressAndPort[0], @"server_port":port, @"password": [methodAndPassword componentsJoinedByString:@":"], @"method":method, @"tag":hashTagSeperatedParts[1] }; } } @catch (NSException *exception) { return nil; } } + (NSDictionary*)parseStandardSSLink:(NSString*)link { //https://shadowsocks.org/en/spec/SIP002-URI-Scheme.html if (![@"ss://" isEqualToString: [link substringToIndex:5]]) { return nil; } @try { NSURL* ssurl = [[NSURL alloc] initWithString:link]; NSNumber* enableOTA; if ([@"ota=false" isEqualToString:[ssurl.query lowercaseString]]) { enableOTA = @(NO); } else if ([@"ota=true" isEqualToString:[ssurl.query lowercaseString]]) { enableOTA = @(YES); } else if (ssurl.query.length > 0) { return nil; // only support ota } NSString* userinfoDecoded = [ConfigImporter decodeBase64String:ssurl.user]; NSArray* userinfo = [userinfoDecoded componentsSeparatedByString:@":"]; if(enableOTA == nil) { return @{ @"server":ssurl.host, @"server_port":ssurl.port, @"password": userinfo[1], @"method":userinfo[0], @"tag":ssurl.fragment }; } else { return @{ @"server":ssurl.host, @"server_port":ssurl.port, @"password": userinfo[1], @"method":userinfo[0], @"tag":ssurl.fragment, @"ota":enableOTA }; } } @catch (NSException *exception) { NSLog(@"%@", exception); return nil; } } + (NSMutableDictionary* )ssOutboundFromSSLink:(NSString*)link { NSDictionary* parsed = [ConfigImporter parseStandardSSLink:link]; if (parsed) { return [ConfigImporter ssOutboundFromSSConfig:parsed]; } else { parsed = [ConfigImporter parseLegacySSLink:link]; if (parsed) { return [ConfigImporter ssOutboundFromSSConfig:parsed]; } } return nil; } + (NSMutableDictionary*)ssOutboundFromSSConfig:(NSDictionary*)jsonObject { if (jsonObject && jsonObject[@"server"] && jsonObject[@"server_port"] && jsonObject[@"password"] && jsonObject[@"method"] && [SUPPORTED_SS_SECURITY indexOfObject:jsonObject[@"method"]] != NSNotFound) { NSMutableDictionary* ssOutbound = [@{ @"sendThrough": @"0.0.0.0", @"protocol": @"shadowsocks", @"settings": @{ @"servers": @[ @{ @"address": jsonObject[@"server"], @"port": jsonObject[@"server_port"], @"method": jsonObject[@"method"], @"password": jsonObject[@"password"], } ] }, @"tag": [NSString stringWithFormat:@"%@:%@",jsonObject[@"server"],jsonObject[@"server_port"]], @"streamSettings": @{}, @"mux": @{} } mutableDeepCopy]; if (jsonObject[@"ota"]) { ssOutbound[@"settings"][@"servers"][0][@"ota"] = jsonObject[@"ota"]; } if (jsonObject[@"tag"] && [jsonObject[@"tag"] isKindOfClass:[NSString class]] && [jsonObject[@"tag"] length] ) { ssOutbound[@"tag"] = jsonObject[@"tag"]; } if ([jsonObject[@"fast_open"] isKindOfClass:[NSNumber class]]) { ssOutbound[@"streamSettings"] =[@{ @"sockopt": @{ @"tcpFastOpen": jsonObject[@"fast_open"] }} mutableDeepCopy]; } return ssOutbound; } return nil; } + (NSMutableDictionary*)validateRuleSet:(NSMutableDictionary*)set { if (![set isKindOfClass:[NSMutableDictionary class]]) { NSLog(@"not a mutable dictionary class, %@", [set className]); return nil; } if (!set[@"rules"] || ![set[@"rules"] isKindOfClass:[NSMutableArray class]] || ![set count] ) { NSLog(@"no rules"); return nil; } if (![@"0-65535" isEqualToString: [set[@"rules"] lastObject][@"port"]]) { NSMutableDictionary *lastRule = [@{ @"type" : @"field", @"outboundTag" : @"main", @"port" : @"0-65535" } mutableDeepCopy]; [set[@"rules"] addObject:lastRule]; } NSMutableArray* ruleToRemove = [[NSMutableArray alloc] init]; NSArray* notSupported = NOT_SUPPORTED_ROUTING; NSArray* supported = SUPPORTED_ROUTING; // currently, source/user/inboundTag/protocol are not supported for (NSMutableDictionary* aRule in set[@"rules"]) { [aRule removeObjectsForKeys:notSupported]; BOOL shouldRemove = true; for (NSString* supportedKey in supported) { if (aRule[supportedKey]) { shouldRemove = false; break; } } if (shouldRemove) { [ruleToRemove addObject:aRule]; continue; } aRule[@"type"] = @"field"; if (!aRule[@"outboundTag"] && !aRule[@"balancerTag"]) { aRule[@"outboundTag"] = @"main"; } if (aRule[@"outboundTag"] && aRule[@"balancerTag"]) { [aRule removeObjectForKey:@"balancerTag"]; } } for (NSMutableDictionary* aRule in ruleToRemove) { [set[@"rules"] removeObject:aRule]; } if (!set[@"name"]) { set[@"name"] = @"some rule set"; } return set; } + (NSMutableDictionary*)importFromStandardConfigFiles:(NSArray*)files { NSMutableDictionary* result = [@{@"vmess": @[], @"other": @[], @"rules":@[]} mutableDeepCopy]; for (NSURL* file in files) { NSError* error; id jsonObject = [NSJSONSerialization JSONObjectWithData: [NSData dataWithContentsOfURL:file] options:0 error:&error]; if (error) continue; if (![jsonObject isKindOfClass:[NSDictionary class]]) continue; NSMutableArray* outboundJSONs = [[NSMutableArray alloc] init]; NSMutableArray* routingJSONs = [[NSMutableArray alloc] init]; if ([[jsonObject objectForKey:@"outbound"] isKindOfClass:[NSDictionary class]]) { [outboundJSONs addObject:jsonObject[@"outbound"]]; } if ([[jsonObject objectForKey:@"outboundDetour"] isKindOfClass:[NSArray class]]) { [outboundJSONs addObjectsFromArray:jsonObject[@"outboundDetour"]]; } if ([[jsonObject objectForKey:@"outbounds"] isKindOfClass:[NSArray class]]) { [outboundJSONs addObjectsFromArray:jsonObject[@"outbounds"]]; } for (NSDictionary* outboundJSON in outboundJSONs) { NSString* protocol = outboundJSON[@"protocol"]; if (!protocol) { continue; } if ([@"vmess" isEqualToString:outboundJSON[@"protocol"]]) { [result[@"vmess"] addObject:[ServerProfile profilesFromJson:outboundJSON][0]]; } else { [result[@"other"] addObject:outboundJSON]; } } if ([[jsonObject objectForKey:@"routing"] isKindOfClass:[NSDictionary class]]) { [routingJSONs addObject:[jsonObject objectForKey:@"routing"]]; } if ([[jsonObject objectForKey:@"routings"] isKindOfClass:[NSArray class]]) { [routingJSONs addObjectsFromArray:[jsonObject objectForKey:@"routings"]]; } for (NSDictionary* routingSet in routingJSONs) { NSMutableDictionary* set = [routingSet mutableDeepCopy]; if (set[@"settings"]) { // compatibal with previous config file format set = set[@"settings"]; } NSMutableDictionary* validatedSet = [ConfigImporter validateRuleSet:set]; if (validatedSet) { [result[@"rules"] addObject:validatedSet]; } } if (jsonObject[@"server"] && jsonObject[@"server_port"] && jsonObject[@"password"] && jsonObject[@"method"] && [SUPPORTED_SS_SECURITY indexOfObject:jsonObject[@"method"]] != NSNotFound) { NSMutableDictionary* ssOutbound = [@{ @"sendThrough": @"0.0.0.0", @"protocol": @"shadowsocks", @"settings": @{ @"servers": @[ @{ @"address": jsonObject[@"server"], @"port": jsonObject[@"server_port"], @"method": jsonObject[@"method"], @"password": jsonObject[@"password"], } ] }, @"tag": [NSString stringWithFormat:@"%@:%@",jsonObject[@"server"],jsonObject[@"server_port"]], @"streamSettings": @{}, @"mux": @{} } mutableDeepCopy]; if ([jsonObject[@"fast_open"] isKindOfClass:[NSNumber class]]) { ssOutbound[@"streamSettings"] =[@{ @"sockopt": @{ @"tcpFastOpen": jsonObject[@"fast_open"] }} mutableDeepCopy]; } [result[@"other"] addObject:ssOutbound]; } } return result; } + (NSMutableDictionary*)importFromHTTPSubscription: (NSString*)httpLink { // https://blog.csdn.net/yi_zz32/article/details/48769487 NSMutableDictionary* result = [@{@"vmess": @[], @"other": @[]} mutableDeepCopy]; if ([httpLink length] < 4) { return nil; } if (![@"http" isEqualToString:[httpLink substringToIndex:4]]) { return nil; } NSURL *url = [NSURL URLWithString:httpLink]; NSError *urlError = nil; NSString *urlStr = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&urlError]; if (!urlError) { NSString *decodedDataStr = [ConfigImporter decodeBase64String:urlStr]; if ([decodedDataStr length] == 0) { return nil; } decodedDataStr = [decodedDataStr stringByReplacingOccurrencesOfString:@"\r" withString:@""]; NSArray *decodedDataArray = [decodedDataStr componentsSeparatedByString:@"\n"]; for (id linkStr in decodedDataArray) { if ([linkStr length] != 0) { ServerProfile* p = [ConfigImporter importFromVmessOfV2RayN:linkStr]; if (p) { [result[@"vmess"] addObject:p]; continue; } NSMutableDictionary* outbound = [ConfigImporter ssOutboundFromSSLink:linkStr]; if (outbound) { [result[@"other"] addObject:outbound]; continue; } NSMutableDictionary* ssdResults = [ConfigImporter importFromSubscriptionOfSSD:linkStr]; [result[@"other"] addObjectsFromArray:ssdResults[@"other"]]; } } return result; } return nil; } + (ServerProfile*)importFromVmessOfV2RayN:(NSString*)vmessStr { if ([vmessStr length] < 9 || ![[[vmessStr substringToIndex:8] lowercaseString] isEqualToString:@"vmess://"]) { return nil; } NSString* decodedJsonString = [[ConfigImporter decodeBase64String:[vmessStr substringFromIndex:8]] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; NSData* decodedData = [decodedJsonString dataUsingEncoding:NSUTF8StringEncoding]; NSError* jsonParseError; NSDictionary *sharedServer = [NSJSONSerialization JSONObjectWithData: decodedData options:0 error:&jsonParseError]; if (jsonParseError) { return nil; } ServerProfile* newProfile = [[ServerProfile alloc] init]; newProfile.outboundTag = nilCoalescing([sharedServer objectForKey:@"ps"], @"imported From QR"); newProfile.address = nilCoalescing([sharedServer objectForKey:@"add"], @""); newProfile.port = [nilCoalescing([sharedServer objectForKey:@"port"], @0) intValue]; newProfile.userId = nilCoalescing([sharedServer objectForKey:@"id"], newProfile.userId); newProfile.alterId = [nilCoalescing([sharedServer objectForKey:@"aid"], @0) intValue]; NSDictionary *netWorkDict = @{@"tcp": @0, @"kcp": @1, @"ws":@2, @"h2":@3 }; if ([sharedServer objectForKey:@"net"] && [netWorkDict objectForKey:[sharedServer objectForKey:@"net"]]) { newProfile.network = [netWorkDict[sharedServer[@"net"]] intValue]; } NSMutableDictionary* streamSettings = [newProfile.streamSettings mutableDeepCopy]; switch (newProfile.network) { case tcp: if (![sharedServer objectForKey:@"type"] || !([sharedServer[@"type"] isEqualToString:@"none"] || [sharedServer[@"type"] isEqualToString:@"http"])) { break; } streamSettings[@"tcpSettings"][@"header"][@"type"] = sharedServer[@"type"]; if ([streamSettings[@"tcpSettings"][@"header"][@"type"] isEqualToString:@"http"]) { if ([sharedServer objectForKey:@"host"]) { streamSettings[@"tcpSettings"][@"header"][@"host"] = [sharedServer[@"host"] componentsSeparatedByString:@","]; } } break; case kcp: if (![sharedServer objectForKey:@"type"]) { break; } if (![@{@"none": @0, @"srtp": @1, @"utp": @2, @"wechat-video":@3, @"dtls":@4, @"wireguard":@5} objectForKey:sharedServer[@"type"]]) { break; } streamSettings[@"kcpSettings"][@"header"][@"type"] = sharedServer[@"type"]; break; case ws: if ([[sharedServer objectForKey:@"host"] containsString:@";"]) { NSArray *tempPathHostArray = [[sharedServer objectForKey:@"host"] componentsSeparatedByString:@";"]; streamSettings[@"wsSettings"][@"path"] = tempPathHostArray[0]; streamSettings[@"wsSettings"][@"headers"][@"Host"] = tempPathHostArray[1]; } else { streamSettings[@"wsSettings"][@"path"] = nilCoalescing([sharedServer objectForKey:@"path"], @""); streamSettings[@"wsSettings"][@"headers"][@"Host"] = nilCoalescing([sharedServer objectForKey:@"host"], @""); } break; case http: if ([[sharedServer objectForKey:@"host"] containsString:@";"]) { NSArray *tempPathHostArray = [[sharedServer objectForKey:@"host"] componentsSeparatedByString:@";"]; streamSettings[@"wsSettings"][@"path"] = tempPathHostArray[0]; streamSettings[@"wsSettings"][@"headers"][@"Host"] = [tempPathHostArray[1] componentsSeparatedByString:@","]; } else { streamSettings[@"httpSettings"][@"path"] = nilCoalescing([sharedServer objectForKey:@"path"], @""); if (![sharedServer objectForKey:@"host"]) { break; }; if ([[sharedServer objectForKey:@"host"] length] > 0) { streamSettings[@"httpSettings"][@"host"] = [[sharedServer objectForKey:@"host"] componentsSeparatedByString:@","]; } } break; default: break; } if ([sharedServer objectForKey:@"tls"] && [sharedServer[@"tls"] isEqualToString:@"tls"]) { streamSettings[@"security"] = @"tls"; streamSettings[@"tlsSettings"][@"serverName"] = newProfile.address; } newProfile.streamSettings = streamSettings; return newProfile; } // https://github.com/CGDF-Github/SSD-Windows/wiki/订阅链接协定 + (NSMutableDictionary* _Nonnull)importFromSubscriptionOfSSD: (NSString* _Nonnull)ssdLink { NSMutableDictionary* result = EMPTY_IMPORT_RESULT; @try { NSString* encodedPart; if (![[ssdLink substringToIndex:6] isEqualToString:@"ssd://"]) { return EMPTY_IMPORT_RESULT; } encodedPart = [ssdLink substringFromIndex:6]; NSString* decodedJSONStr = [ConfigImporter decodeBase64String:encodedPart]; NSDictionary* decodedObject = [NSJSONSerialization JSONObjectWithData:[decodedJSONStr dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil]; NSString* airportName = decodedObject[@"airport"]; NSNumber* defaultPort = decodedObject[@"port"]; NSString* defaultEncryption = decodedObject[@"encryption"]; NSString* defaultPassword = decodedObject[@"password"]; NSString* defaultPlutgin = decodedObject[@"plugin"]; NSInteger count = 0; for (NSDictionary* server in decodedObject[@"servers"]) { NSString* address = server[@"server"]; NSNumber* port = nilCoalescing(server[@"port"], defaultPort) ; NSString* method = nilCoalescing(server[@"encryption"], defaultEncryption); NSString* password = nilCoalescing(server[@"password"], defaultPassword); NSString* plugIn = nilCoalescing(server[@"plugin"], defaultPlutgin); if (plugIn && plugIn.length > 0) { continue; // do not support plug-in yet } NSString* defaultServerName = [NSString stringWithFormat:@"%lu", count]; NSString* serverName = nilCoalescing(server[@"remarks"], defaultServerName); NSString* tag = [NSString stringWithFormat:@"%@-%@", airportName, serverName]; NSMutableDictionary* ssOutbound = [ConfigImporter ssOutboundFromSSConfig:@{ @"server":address, @"server_port":port, @"password":password, @"method":method, @"tag": tag }]; if (ssOutbound) { [result[@"other"] addObject:ssOutbound]; count += 1; } } NSLog(@"%@", result); return result; } @catch (NSException *exception) { return EMPTY_IMPORT_RESULT; } } @end ================================================ FILE: V2RayX/ConfigWindow.xib ================================================ NSAllRomanInputSourcesLocaleIdentifier NSAllRomanInputSourcesLocaleIdentifier NSAllRomanInputSourcesLocaleIdentifier NSAllRomanInputSourcesLocaleIdentifier NSAllRomanInputSourcesLocaleIdentifier ================================================ FILE: V2RayX/ConfigWindowController.h ================================================ // // ConfigWindowController.h // V2RayX // // Copyright © 2016年 Cenmrev. All rights reserved. // #import #import "ServerProfile.h" @interface ConfigWindowController : NSWindowController - (IBAction)chooseNetwork:(NSPopUpButton *)sender; @property (weak) IBOutlet NSPopUpButton *networkButton; @property (weak) IBOutlet NSPopUpButton *vmessSecurityButton; - (IBAction)addRemoveServer:(id)sender; - (IBAction)cancel:(id)sender; - (IBAction)okSave:(id)sender; @property (weak) IBOutlet NSButton *importButton; @property (weak) IBOutlet NSTableView *profileTable; @property (weak) IBOutlet NSSegmentedControl *addRemoveButton; @property (weak) IBOutlet NSView *importResultView; @property (weak) IBOutlet NSTextField *importMessageField; @property (weak) IBOutlet NSTextField *localPortField; @property (weak) IBOutlet NSTextField *httpPortField; @property (weak) IBOutlet NSTextField *portField; @property (weak) IBOutlet NSTextField *alterIdField; @property (weak) IBOutlet NSTextField *dnsField; @property (weak) IBOutlet NSButton *globalTransportButton; @property (weak) IBOutlet NSPopUpButton *logLevelButton; @property (weak) IBOutlet NSMenu *importFromJsonMenu; @property (weak) IBOutlet NSButton *transportSettingsButton; @property (weak) AppDelegate* appDelegate; @property (nonatomic) ServerProfile* selectedProfile; @property (nonatomic) NSInteger logLevel; @property (nonatomic) NSInteger selectedServerIndex; @property (nonatomic) NSInteger selectedCusServerIndex; @property (nonatomic) NSInteger localPort; @property (nonatomic) NSInteger httpPort; @property (nonatomic) BOOL udpSupport; @property (nonatomic) BOOL shareOverLan; @property (nonatomic) NSString* dnsString; @property (nonatomic) NSMutableArray *profiles; @property (nonatomic) NSMutableArray *outbounds; // except than vmess @property (nonatomic) NSMutableArray *subscriptions; @property NSMutableArray* routingRuleSets; @property (nonatomic) NSMutableArray *cusProfiles; @property BOOL enableRestore; @property BOOL enableEncryption; @property NSString* encryptionKey; @property (weak) IBOutlet NSTextField *versionField; @end ================================================ FILE: V2RayX/ConfigWindowController.m ================================================ // // ConfigWindowController.m // V2RayX // // Copyright © 2016年 Cenmrev. All rights reserved. // #import "ConfigWindowController.h" #import "AppDelegate.h" #import "MutableDeepCopying.h" #import "TransportWindowController.h" #import "AdvancedWindowController.h" #import "ConfigImporter.h" @interface ConfigWindowController () @property (strong) TransportWindowController* transportWindowController; @property (strong) AdvancedWindowController* advancedWindowController; @property (strong) NSPopover* popover; @end @implementation ConfigWindowController - (void)windowDidLoad { [super windowDidLoad]; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSString* v2rayPath = [self.appDelegate getV2rayPath]; NSTask *task = [[NSTask alloc] init]; if (@available(macOS 10.13, *)) { [task setExecutableURL:[NSURL fileURLWithPath:v2rayPath]]; } else { [task setLaunchPath:v2rayPath]; } [task setArguments:@[@"-version"]]; NSPipe *stdoutpipe = [NSPipe pipe]; [task setStandardOutput:stdoutpipe]; [task launch]; [task waitUntilExit]; NSFileHandle *file = [stdoutpipe fileHandleForReading]; NSData *data = [file readDataToEndOfFile]; NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; dispatch_async(dispatch_get_main_queue(), ^{ [self->_versionField setStringValue:[string componentsSeparatedByString:@"\n"][0]]; }); }); [_networkButton removeAllItems]; for(NSString* network in NETWORK_LIST) { [_networkButton addItemWithTitle:network]; } [_vmessSecurityButton removeAllItems]; for(NSString* security in VMESS_SECURITY_LIST) { [_vmessSecurityButton addItemWithTitle:security]; } //set textField Display [_profileTable setFocusRingType:NSFocusRingTypeNone]; NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; [formatter setNumberStyle:NSNumberFormatterNoStyle]; [_portField setFormatter:formatter]; [_alterIdField setFormatter:formatter]; [_localPortField setFormatter:formatter]; [_httpPortField setFormatter:formatter]; // [_addRemoveButton setMenu:_importFromJsonMenu forSegment:2]; // copy data _profiles = [[NSMutableArray alloc] init]; _outbounds = [[NSMutableArray alloc] init]; for (NSDictionary *p in _appDelegate.profiles) { if ([@"vmess" isEqualToString:p[@"protocol"]] && [p[@"settings"][@"vnext"] count] == 1) { [_profiles addObject:[ServerProfile profilesFromJson:p][0]]; } else { [_outbounds addObject:p]; } } _cusProfiles = [_appDelegate.cusProfiles mutableDeepCopy]; _subscriptions = [_appDelegate.subscriptions mutableCopy]; _routingRuleSets = [_appDelegate.routingRuleSets mutableCopy]; // [_profileTable reloadData]; self.selectedServerIndex = 0; self.selectedCusServerIndex = 0; self.httpPort = _appDelegate.httpPort; self.localPort = _appDelegate.localPort; self.udpSupport = _appDelegate.udpSupport; self.shareOverLan = _appDelegate.shareOverLan; self.dnsString = _appDelegate.dnsString; self.enableRestore = _appDelegate.enableRestore; self.enableEncryption = _appDelegate.enableEncryption; self.encryptionKey = [NSString stringWithString:_appDelegate.encryptionKey]; NSDictionary *logLevelDic = @{ @"debug": @4, @"info": @3, @"warning": @2, @"error":@1, @"none":@0 }; self.logLevel = [logLevelDic[_appDelegate.logLevel] integerValue]; [_profileTable selectRowIndexes:[NSIndexSet indexSetWithIndex:self.selectedServerIndex] byExtendingSelection:NO]; [[self window] makeFirstResponder:_profileTable]; } // set controller as profilesTable's datasource - (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView { if (tableView == _profileTable) { return [_profiles count]; } return 0; } - (id) tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row { if (tableView == _profileTable) { if ([_profiles count] > 0) { ServerProfile* p = [_profiles objectAtIndex:row]; return [[p outboundTag] length] > 0 ? [p outboundTag] : [NSString stringWithFormat:@"%@:%ld", [p address], [p port]]; } else { return nil; } } return nil; } -(void)tableViewSelectionDidChange:(NSNotification *)notification{ if ([notification object] == _profileTable) { if ([_profiles count] > 0) { [self setSelectedServerIndex:[_profileTable selectedRow]]; // NSLog(@"selectef p = %@", _profiles[_selectedServerIndex]); [self setSelectedProfile:_profiles[_selectedServerIndex]]; } } } - (IBAction)chooseNetwork:(NSPopUpButton *)sender { if (_selectedServerIndex >= 0 && _selectedServerIndex < [_profiles count]) { [self checkTLSforHttp2]; } } - (BOOL)checkTLSforHttp2 { if ([_networkButton indexOfSelectedItem] == 3) { // selected http/2 BOOL tlsEnabled = [self.selectedProfile.streamSettings[@"security"] isEqual: @"tls"]; if (!tlsEnabled) { NSAlert *httpTlsAlerm = [[NSAlert alloc] init]; [httpTlsAlerm addButtonWithTitle:@"Close"]; [httpTlsAlerm addButtonWithTitle:@"Help"]; [httpTlsAlerm setMessageText:@"Both client and server must enable TLS to use HTTP/2 network! Enbale TLS in transport settings. Click \"Help\" if you need more information"]; [httpTlsAlerm beginSheetModalForWindow:self.window completionHandler:^(NSModalResponse returnCode) { if (returnCode == NSAlertSecondButtonReturn) { [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"https://www.v2ray.com/chapter_02/transport/h2.html#tips"]]; } }]; [_networkButton selectItemAtIndex:0]; return NO; // does not pass checking } } return true; // pass checking } - (IBAction)addRemoveServer:(id)sender { [[self window] makeFirstResponder:_profileTable]; if ([sender selectedSegment] == 0) { ServerProfile* newProfile = [[ServerProfile alloc] init]; [_profiles addObject:newProfile]; [_profileTable reloadData]; [_profileTable selectRowIndexes:[NSIndexSet indexSetWithIndex:([_profiles count] - 1)] byExtendingSelection:NO]; } else if ([sender selectedSegment] == 1 && [_profiles count] > 0) { NSInteger originalSelectedServerIndex = [_profileTable selectedRow]; [_profiles removeObjectAtIndex:originalSelectedServerIndex]; if ([_profiles count] > 0) { if (originalSelectedServerIndex == [_profiles count]) {//deleted the last server //select the last server of the remains [self setSelectedServerIndex:[_profiles count] - 1]; } [_profileTable selectRowIndexes:[NSIndexSet indexSetWithIndex:_selectedServerIndex] byExtendingSelection:NO]; [self setSelectedProfile:_profiles[_selectedServerIndex]]; } else { // all the profiles are deleted; [self setSelectedServerIndex:-1]; [self setSelectedProfile:nil]; } [_profileTable reloadData]; } else if ([sender selectedSegment] == 2) { // share server } else if ([sender selectedSegment] == 3) { // duplicate if (_selectedServerIndex >= 0 && _selectedServerIndex < [_profiles count]) { [_profiles addObject:[_profiles[_selectedServerIndex] deepCopy]]; [_profileTable reloadData]; } } } - (IBAction)importConfigs:(id)sender { [NSMenu popUpContextMenu:_importFromJsonMenu withEvent:[NSApp currentEvent] forView:sender]; } - (IBAction)cancel:(id)sender { [[self window] close]; } - (NSString*)firstFewLines:(NSDictionary*)dict { NSInteger limit = 13; NSString* str = [dict description]; NSArray* lines = [str componentsSeparatedByString:@"\n"]; if (lines.count < limit) { return str; } else { NSString* r = [[lines subarrayWithRange:NSMakeRange(0, limit)] componentsJoinedByString:@"\n"]; return [NSString stringWithFormat:@"%@\n...", r]; } } - (IBAction)okSave:(id)sender { if (![self checkTLSforHttp2]) { return; } NSMutableArray *allOutbounds = [[NSMutableArray alloc] init]; for (ServerProfile* p in _profiles) { [allOutbounds addObject:[p outboundProfile]]; } for (NSMutableDictionary* p in _outbounds) { [allOutbounds addObject:p]; } NSMutableDictionary *allOutboundDict =[[NSMutableDictionary alloc] init]; for (NSMutableDictionary* outbound in allOutbounds) { if (!outbound[@"tag"] || ![outbound[@"tag"] isKindOfClass:[NSString class]] || [outbound[@"tag"] length] == 0) { [self showAlert: [NSString stringWithFormat:@"%@\ntag is not valid!", [self firstFewLines:outbound]]]; return; } if ([RESERVED_TAGS indexOfObject:outbound[@"tag"]] != NSNotFound) { [self showAlert: [NSString stringWithFormat:@"tag %@ is reserved, please use another one!", outbound[@"tag"]]]; return; } if (allOutboundDict[outbound[@"tag"]]) { [self showAlert: [NSString stringWithFormat:@"The two outbounds share the same tag: %@\n%@\nAND\n%@",outbound[@"tag"], [self firstFewLines:outbound], [self firstFewLines:allOutboundDict[outbound[@"tag"]]]]]; return; } allOutboundDict[outbound[@"tag"]] = outbound; } _appDelegate.profiles = allOutbounds; NSString* dnsStr = [[_dnsField stringValue] stringByReplacingOccurrencesOfString:@" " withString:@""]; if ([dnsStr length] == 0) { dnsStr = @"localhost"; } _appDelegate.logLevel = _logLevelButton.selectedItem.title; _appDelegate.localPort = [_localPortField integerValue]; _appDelegate.httpPort = [_httpPortField integerValue]; _appDelegate.udpSupport = self.udpSupport; _appDelegate.shareOverLan = self.shareOverLan; _appDelegate.dnsString = dnsStr; _appDelegate.cusProfiles = self.cusProfiles; _appDelegate.subscriptions = self.subscriptions; _appDelegate.enableRestore = self.enableRestore; [_appDelegate.routingRuleSets removeAllObjects]; for (NSMutableDictionary* set in self.routingRuleSets) { NSMutableDictionary* validatedSet = [ConfigImporter validateRuleSet:set]; if (validatedSet) { [_appDelegate.routingRuleSets addObject:validatedSet]; } } if (_appDelegate.routingRuleSets.count == 0) { [_appDelegate.routingRuleSets addObject:[ROUTING_DIRECT mutableDeepCopy]]; } _appDelegate.enableEncryption = self.enableEncryption; _appDelegate.encryptionKey = self.encryptionKey; [_appDelegate saveConfigInfo]; [_appDelegate updateSubscriptions:self]; [[self window] close]; } - (IBAction)showAdvancedWindow:(NSButton *)sender { self.advancedWindowController = [[AdvancedWindowController alloc] initWithWindowNibName:@"AdvancedWindow" parentController:self]; [[self window] beginSheet:self.advancedWindowController.window completionHandler:^(NSModalResponse returnCode) { if (returnCode == NSModalResponseOK) { self.outbounds = self.advancedWindowController.outbounds; self.cusProfiles = self.advancedWindowController.configs; self.routingRuleSets = self.advancedWindowController.routingRuleSets; self.subscriptions = self.advancedWindowController.subscriptions; self.enableRestore = self.advancedWindowController.enableRestore; self.enableEncryption = self.advancedWindowController.enableEncryption; self.encryptionKey = self.advancedWindowController.encryptionKey; } self.advancedWindowController = nil; }]; } - (IBAction)showTransportSettings:(id)sender { if ([_profiles count] == 0) { return; } self.transportWindowController = [[TransportWindowController alloc] initWithWindowNibName:@"TransportWindow" parentController:self]; [[self window] beginSheet:self.transportWindowController.window completionHandler:^(NSModalResponse returnCode) { if (returnCode == NSModalResponseOK) { NSArray* a = [self->_transportWindowController generateSettings]; self.selectedProfile.streamSettings = a[0]; self.selectedProfile.muxSettings = a[1]; } self.transportWindowController = nil; }]; } // https://stackoverflow.com/questions/7387341/how-to-create-and-get-return-value-from-cocoa-dialog/7387395#7387395 - (void)askInputWithPrompt: (NSString*)prompt handler:(void (^ __nullable)(NSString* inputStr))handler { NSAlert *alert = [[NSAlert alloc] init]; alert.messageText = prompt; [alert addButtonWithTitle:@"OK"]; [alert addButtonWithTitle:@"Cancel"]; NSTextField *inputField = [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 400, 24)]; inputField.usesSingleLineMode = true; inputField.lineBreakMode = NSLineBreakByTruncatingHead; [alert setAccessoryView:inputField]; [alert beginSheetModalForWindow:self.window completionHandler:^(NSModalResponse returnCode) { if (returnCode == NSAlertFirstButtonReturn) { handler([inputField stringValue]); } }]; } - (void)showAlert:(NSString*)text { NSAlert* alert = [[NSAlert alloc] init]; [alert setInformativeText:text]; [alert beginSheetModalForWindow:self.window completionHandler:^(NSModalResponse returnCode) { ; }]; } - (IBAction)importFromStandardLink:(id)sender { [self askInputWithPrompt:@"Support standard vmess:// and ss:// link. Standard vmess:// link is still under discussion. Use \"Import from other links...\" to import other links, for example, vmess:// invented by v2rayN." handler:^(NSString *inputStr) { if (inputStr.length) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ NSMutableDictionary* ssOutbound = [ConfigImporter ssOutboundFromSSLink:inputStr]; if (ssOutbound) { [self.outbounds addObject:ssOutbound]; [self presentImportResultOfVmessCount:0 otherCount:1 ruleSetCount:0]; } else { [self presentImportResultOfVmessCount:0 otherCount:0 ruleSetCount:0]; } }); } }]; } - (void)presentImportResultOfVmessCount:(NSInteger)vmessCount otherCount:(NSInteger)otherCount ruleSetCount:(NSInteger)ruleSetCount { dispatch_async(dispatch_get_main_queue(), ^{ [self->_profileTable reloadData]; self.popover = [[NSPopover alloc] init]; self.importMessageField.stringValue = [NSString stringWithFormat:@"Imported %lu vmess and %lu other protocol outbounds, %lu routing rule sets.", vmessCount, otherCount, ruleSetCount]; self.popover.contentViewController = [[NSViewController alloc] init]; self.popover.contentViewController.view = self.importResultView; self.popover.behavior = NSPopoverBehaviorTransient; [self.popover showRelativeToRect:[self.importButton bounds] ofView:self.importButton preferredEdge:NSMaxYEdge]; }); } - (IBAction)importFromMiscLinks:(id)sender { [self askInputWithPrompt:@"V2RayX will try importing ssd://, vmess:// and http(s):// links from v2rayN and SSD(may cause failure)." handler:^(NSString *inputStr) { inputStr = [inputStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; if ([inputStr length] != 0) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ ServerProfile* p = [ConfigImporter importFromVmessOfV2RayN:inputStr]; NSInteger vmessCount = 0; NSInteger otherCount = 0; if (p) { [self.profiles addObject:p]; vmessCount = 1; } NSDictionary* ssdResult = [ConfigImporter importFromSubscriptionOfSSD:inputStr]; for (NSDictionary* d in ssdResult[@"other"]) { [self.outbounds addObject:[d mutableDeepCopy]]; otherCount += 1; } NSMutableDictionary* p2 = [ConfigImporter importFromHTTPSubscription:inputStr]; if (p2) { [self.profiles addObjectsFromArray:p2[@"vmess"]]; [self.outbounds addObjectsFromArray:p2[@"other"]]; vmessCount += [p2[@"vmess"] count]; otherCount += [p2[@"other"] count]; } [self presentImportResultOfVmessCount:vmessCount otherCount:otherCount ruleSetCount:0]; }); } }]; } - (IBAction)importFromJSONFiles:(id)sender { NSOpenPanel* openPanel = [NSOpenPanel openPanel]; [openPanel setCanChooseFiles:YES]; [openPanel setAllowsMultipleSelection:YES]; [openPanel setAllowedFileTypes:@[@"json"]]; [openPanel setDirectoryURL:[[NSFileManager defaultManager] homeDirectoryForCurrentUser]]; [openPanel beginSheetModalForWindow:[self window] completionHandler:^(NSModalResponse result) { if (result == NSModalResponseOK) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ NSArray* files = [openPanel URLs]; NSMutableDictionary* result = [ConfigImporter importFromStandardConfigFiles:files]; [self.profiles addObjectsFromArray:result[@"vmess"]]; [self.outbounds addObjectsFromArray:result[@"other"]]; [self.routingRuleSets addObjectsFromArray:result[@"rules"]]; [self presentImportResultOfVmessCount:[result[@"vmess"] count] otherCount:[result[@"other"] count] ruleSetCount:[result[@"rules"] count]]; }); } }]; } - (IBAction)showLog:(id)sender { [_appDelegate viewLog:sender]; } @end ================================================ FILE: V2RayX/Credits.rtf ================================================ {\rtf1\ansi\ansicpg1252\cocoartf1671\cocoasubrtf200 {\fonttbl\f0\fswiss\fcharset0 Helvetica;\f1\fswiss\fcharset0 Arial-BoldMT;\f2\fswiss\fcharset0 Helvetica-Bold; \f3\fswiss\fcharset0 Helvetica-Oblique;} {\colortbl;\red255\green255\blue255;} {\*\expandedcolortbl;;} \vieww9000\viewh8400\viewkind0 \pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardirnatural\partightenfactor0 \f0\fs24 \cf0 \ \pard\pardeftab720\qc\partightenfactor0 \f1\b\fs28 \cf0 \expnd0\expndtw0\kerning0 Stand on the shoulders of giants \f2\fs24 \kerning1\expnd0\expndtw0 \ \ \pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardeftab720\pardirnatural\qc\partightenfactor0 \cf0 V2RayX - GUI for V2Ray on macOS \f0\b0 \ \f3\i Cenmrev \f0\i0 \ https://github.com/Cenmrev/V2RayX\ \ For information on V2Ray, visit:\ https://www.v2ray.com\ \ Icon "copy" made by {\field{\*\fldinst{HYPERLINK "https://www.flaticon.com/authors/freepik"}}{\fldrslt Freepik}} from www.flaticon.com \ \pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardeftab720\pardirnatural\partightenfactor0 \cf0 \ \ \ } ================================================ FILE: V2RayX/Info.plist ================================================ CFBundleDevelopmentRegion en CFBundleExecutable $(EXECUTABLE_NAME) CFBundleIconFile CFBundleIdentifier $(PRODUCT_BUNDLE_IDENTIFIER) CFBundleInfoDictionaryVersion 6.0 CFBundleName $(PRODUCT_NAME) CFBundlePackageType APPL CFBundleShortVersionString 1.5.1 CFBundleSignature ???? CFBundleVersion 1297 LSMinimumSystemVersion $(MACOSX_DEPLOYMENT_TARGET) LSUIElement NSHumanReadableCopyright Copyright © 2019 Cenmrev. All rights reserved. NSMainNibFile MainMenu NSPrincipalClass NSApplication ================================================ FILE: V2RayX/MutableDeepCopying.h ================================================ // https://gist.github.com/yfujiki/1664847 #import @protocol MutableDeepCopying -(id) mutableDeepCopy; @end @interface NSDictionary (MutableDeepCopy) @end @interface NSArray (MutableDeepCopy) @end // Implementation @implementation NSDictionary (MutableDeepCopy) - (NSMutableDictionary *) mutableDeepCopy { NSMutableDictionary * returnDict = [[NSMutableDictionary alloc] initWithCapacity:self.count]; NSArray * keys = [self allKeys]; for(id key in keys) { id aValue = [self objectForKey:key]; id theCopy = nil; if([aValue conformsToProtocol:@protocol(MutableDeepCopying)]) { theCopy = [aValue mutableDeepCopy]; } else if([aValue conformsToProtocol:@protocol(NSMutableCopying)]) { theCopy = [aValue mutableCopy]; } else if([aValue conformsToProtocol:@protocol(NSCopying)]){ theCopy = [aValue copy]; } else { theCopy = aValue; } [returnDict setValue:theCopy forKey:key]; } return returnDict; } @end @implementation NSArray (MutableDeepCopy) -(NSMutableArray *)mutableDeepCopy { NSMutableArray *returnArray = [[NSMutableArray alloc] initWithCapacity:self.count]; for(id aValue in self) { id theCopy = nil; if([aValue conformsToProtocol:@protocol(MutableDeepCopying)]) { theCopy = [aValue mutableDeepCopy]; } else if([aValue conformsToProtocol:@protocol(NSMutableCopying)]) { theCopy = [aValue mutableCopy]; } else if([aValue conformsToProtocol:@protocol(NSCopying)]){ theCopy = [aValue copy]; } else { theCopy = aValue; } [returnArray addObject:theCopy]; } return returnArray; } @end ================================================ FILE: V2RayX/NSData+AES256Encryption.h ================================================ // // NSData+AES256Encryption.h // V2RayX // // #import @interface NSData (AES256Encryption) - (NSData *)encryptedDataWithKey:(NSString*)key; - (NSData* )decryptedDataWithKey:(NSString*)key; @end ================================================ FILE: V2RayX/NSData+AES256Encryption.m ================================================ // // NSData+AES256Encryption.m // V2RayX // // #import "NSData+AES256Encryption.h" #import #import @implementation NSData (AES256Encryption) - (NSData *)encryptedDataWithKey:(NSString*)key { NSUInteger dataLength = [self length]; size_t bufferSize = dataLength + kCCBlockSizeAES128; void *buffer = malloc( bufferSize ); //NSLog(@"%@, %@", key); size_t numBytesEncrypted = 0; CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES, kCCOptionPKCS7Padding|kCCOptionECBMode, [key cStringUsingEncoding:NSUTF8StringEncoding], kCCKeySizeAES256, NULL /* initialization vector */, [self bytes], dataLength, /* input */ buffer, bufferSize, /* output */ &numBytesEncrypted); if(cryptStatus == kCCSuccess) { return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted]; } free(buffer); return nil; } -(NSData* )decryptedDataWithKey:(NSString*)key { NSUInteger dataLength = [self length]; size_t bufferSize = dataLength + kCCBlockSizeAES128; void *buffer = malloc( bufferSize ); size_t numBytesDecrypted = 0; CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES, kCCOptionPKCS7Padding|kCCOptionECBMode, [key cStringUsingEncoding:NSUTF8StringEncoding], kCCKeySizeAES256, NULL /* initialization vector */, [self bytes], dataLength, /* input */ buffer, bufferSize, /* output */ &numBytesDecrypted); if(cryptStatus == kCCSuccess) { return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted]; } return nil; } @end ================================================ FILE: V2RayX/ServerProfile.h ================================================ // // ServerProfile.h // V2RayX // // Copyright © 2016年 Cenmrev. All rights reserved. // #import #import "AppDelegate.h" #import "utilities.h" typedef enum SecurityType : NSUInteger { auto_, aes_128_gcm, chacha20_poly130, none } SecurityType; typedef enum NetWorkType : NSUInteger { tcp, kcp, ws, http, quic } NetWorkType; @interface ServerProfile : NSObject - (NSMutableDictionary*)outboundProfile; + (ServerProfile* _Nullable )readFromAnOutboundDic:(NSDictionary*)outDict; + (NSArray*)profilesFromJson:(NSDictionary*)outboundJson; -(ServerProfile*)deepCopy; @property (nonatomic) NSString* address; @property (nonatomic) NSUInteger port; @property (nonatomic) NSString* userId; @property (nonatomic) NSUInteger alterId; @property (nonatomic) NSUInteger level; @property (nonatomic) NSString* outboundTag; @property (nonatomic) SecurityType security; @property (nonatomic) NetWorkType network; @property (nonatomic) NSString* sendThrough; @property (nonatomic) NSDictionary* streamSettings; // except network type. @property (nonatomic) NSDictionary* muxSettings; @end ================================================ FILE: V2RayX/ServerProfile.m ================================================ // // ServerProfile.m // V2RayX // // Copyright © 2016年 Cenmrev. All rights reserved. // #import "ServerProfile.h" @implementation ServerProfile - (ServerProfile*)init { self = [super init]; if (self) { [self setAddress:@"server.cc"]; [self setPort:10086]; [self setUserId:@"00000000-0000-0000-0000-000000000000"]; [self setAlterId:64]; [self setLevel:0]; [self setOutboundTag:@"test server"]; [self setSecurity:auto_]; [self setNetwork:tcp]; [self setSendThrough:@"0.0.0.0"]; [self setStreamSettings:@{ @"security": @"none", @"tlsSettings": @{ @"serverName": @"server.cc", @"alpn": @[@"http/1.1"], @"allowInsecure": [NSNumber numberWithBool:NO], @"allowInsecureCiphers": [NSNumber numberWithBool:NO] }, @"tcpSettings": @{ @"header": @{ @"type": @"none" } }, @"kcpSettings": @{ @"mtu": @1350, @"tti": @20, @"uplinkCapacity": @5, @"downlinkCapacity": @20, @"congestion": [NSNumber numberWithBool:NO], @"readBufferSize": @1, @"writeBufferSize": @1, @"header": @{ @"type": @"none" } }, @"wsSettings": @{ @"path": @"", @"headers": @{} }, @"httpSettings": @{ @"host": @[@""], @"path": @"" }, @"quicSettings": @{ @"security": @"none", @"key": @"", @"header": @{ @"type": @"none" } }, @"sockopt": @{} }]; [self setMuxSettings:@{ @"enabled": [NSNumber numberWithBool:NO], @"concurrency": @8 }]; } return self; } - (NSString*)description { return [[self outboundProfile] description]; } + (NSArray*)profilesFromJson:(NSDictionary*)outboundJson { if (![outboundJson[@"protocol"] isKindOfClass:[NSString class]] || ![outboundJson[@"protocol"] isEqualToString:@"vmess"] ) { return @[]; } NSMutableArray* profiles = [[NSMutableArray alloc] init]; NSString* sendThrough = nilCoalescing(outboundJson[@"sendThrough"], @"0.0.0.0"); if (![[outboundJson valueForKeyPath:@"settings.vnext"] isKindOfClass:[NSArray class]]) { return @[]; } for (NSDictionary* vnext in [outboundJson valueForKeyPath:@"settings.vnext"]) { ServerProfile* profile = [[ServerProfile alloc] init]; profile.address = nilCoalescing(vnext[@"address"], @"127.0.0.1"); profile.outboundTag = nilCoalescing(outboundJson[@"tag"], @""); profile.port = [vnext[@"port"] unsignedIntegerValue]; if (![vnext[@"users"] isKindOfClass:[NSArray class]] || [vnext[@"users"] count] == 0) { continue; } profile.userId = nilCoalescing(vnext[@"users"][0][@"id"], @"23ad6b10-8d1a-40f7-8ad0-e3e35cd38287"); profile.alterId = [vnext[@"users"][0][@"alterId"] unsignedIntegerValue]; profile.level = [vnext[@"users"][0][@"level"] unsignedIntegerValue]; profile.security = searchInArray(vnext[@"users"][0][@"security"], VMESS_SECURITY_LIST); if (outboundJson[@"streamSettings"] != nil) { profile.streamSettings = outboundJson[@"streamSettings"]; profile.network = searchInArray(outboundJson[@"streamSettings"][@"network"], NETWORK_LIST); } if (outboundJson[@"mux"] != nil) { profile.muxSettings = outboundJson[@"mux"]; } profile.sendThrough = sendThrough; [profiles addObject:profile]; } return profiles; } + (ServerProfile* _Nullable )readFromAnOutboundDic:(NSDictionary*)outDict { NSArray *allProfiles = [self profilesFromJson:outDict]; if ([allProfiles count] > 0) { return allProfiles[0]; } else { return NULL; } } -(ServerProfile*)deepCopy { ServerProfile* aCopy = [[ServerProfile alloc] init]; aCopy.address = [NSString stringWithString:nilCoalescing(self.address, @"")]; aCopy.port = self.port; aCopy.userId = [NSString stringWithString:nilCoalescing(self.userId, @"")]; aCopy.alterId = self.alterId; aCopy.level = self.level; aCopy.outboundTag = [NSString stringWithString:nilCoalescing(self.outboundTag, @"")]; aCopy.security = self.security; aCopy.network = self.network; aCopy.sendThrough = [NSString stringWithString:nilCoalescing(self.sendThrough, @"")]; aCopy.streamSettings = [NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:self.streamSettings]]; aCopy.muxSettings = [NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:self.muxSettings]]; return aCopy; } - (NSMutableDictionary*)outboundProfile { NSMutableDictionary* fullStreamSettings = [NSMutableDictionary dictionaryWithDictionary:streamSettings]; fullStreamSettings[@"network"] = NETWORK_LIST[network]; NSDictionary* result = @{ @"sendThrough": sendThrough, @"tag": nilCoalescing(outboundTag, @""), @"protocol": @"vmess", @"settings": [@{ @"vnext": @[ @{ @"address": nilCoalescing([address stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] , @""), @"port": [NSNumber numberWithUnsignedInteger:port], @"users": @[ @{ @"id": userId != nil ? [userId stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]: @"", @"alterId": [NSNumber numberWithUnsignedInteger:alterId], @"security": VMESS_SECURITY_LIST[security], @"level": [NSNumber numberWithUnsignedInteger:level] } ] } ] } mutableCopy], @"streamSettings": fullStreamSettings, @"mux": muxSettings, }; return [result mutableCopy]; } @synthesize address; @synthesize port; @synthesize userId; @synthesize alterId; @synthesize level; @synthesize outboundTag; @synthesize security; @synthesize network; @synthesize sendThrough; @synthesize muxSettings; @synthesize streamSettings; @end ================================================ FILE: V2RayX/TransportWindow.xib ================================================ QUIC is now an experiment in V2Ray. It implements IETF specification. As the spec is still being standardized, compatibility can't be guaranteed. ================================================ FILE: V2RayX/TransportWindowController.h ================================================ // // TransportWindowController.h // V2RayX // // #import #import "ConfigWindowController.h" #import "utilities.h" NS_ASSUME_NONNULL_BEGIN @interface TransportWindowController : NSWindowController - (instancetype)initWithWindowNibName:(NSNibName)windowNibName parentController:(ConfigWindowController*)parent; - (BOOL)checkInputs; - (NSArray*)generateSettings; //kcp fields @property (weak) IBOutlet NSTextField *kcpMtuField; @property (weak) IBOutlet NSTextField *kcpTtiField; @property (weak) IBOutlet NSTextField *kcpUcField; @property (weak) IBOutlet NSTextField *kcpDcField; @property (weak) IBOutlet NSTextField *kcpRbField; @property (weak) IBOutlet NSTextField *kcpWbField; @property (weak) IBOutlet NSPopUpButton *kcpCongestionButton; @property (weak) IBOutlet NSPopUpButton *kcpHeaderTypeButton; //tcp fields @property (weak) IBOutlet NSButton *tcpHeaderCusButton; @property (unsafe_unretained) IBOutlet NSTextView *tcpHeaderField; //ws fields @property (weak) IBOutlet NSTextField *wsPathField; @property (unsafe_unretained) IBOutlet NSTextView *wsHeaderField; //https fields @property (weak) IBOutlet NSTextField *httpHostsField; @property (weak) IBOutlet NSTextField *httpPathField; // quic fields @property (weak) IBOutlet NSPopUpButton *quicSecurityButton; @property (weak) IBOutlet NSTextField *quicKeyField; @property (weak) IBOutlet NSPopUpButton *quicHeaderButton; //tls fields @property (weak) IBOutlet NSButton *tlsUseButton; @property (weak) IBOutlet NSButton *tlsAiButton; @property (weak) IBOutlet NSButton *tlsAllowInsecureCiphersButton; @property (weak) IBOutlet NSTextField *tlsAlpnField; @property (weak) IBOutlet NSTextField *tlsServerNameField; //mux fields @property (weak) IBOutlet NSButton *muxEnableButton; @property (weak) IBOutlet NSTextField *muxConcurrencyField; //tcp fast open @property (weak) IBOutlet NSButton *tfoEnableButton; @end NS_ASSUME_NONNULL_END ================================================ FILE: V2RayX/TransportWindowController.m ================================================ // // TransportWindowController.m // V2RayX // // #import "TransportWindowController.h" @interface TransportWindowController () { ConfigWindowController* configWindowController; } @end @implementation TransportWindowController - (instancetype)initWithWindowNibName:(NSNibName)windowNibName parentController:(ConfigWindowController*)parent { self = [super initWithWindowNibName:windowNibName]; if (self) { configWindowController = parent; } return self; } - (void)windowDidLoad { [super windowDidLoad]; //add UI items [_kcpHeaderTypeButton removeAllItems]; [_quicHeaderButton removeAllItems]; for (NSString* header in OBFU_LIST) { [_kcpHeaderTypeButton addItemWithTitle:header]; [_quicHeaderButton addItemWithTitle:header]; } [_quicSecurityButton removeAllItems]; for (NSString* security in QUIC_SECURITY_LIST) { [_quicSecurityButton addItemWithTitle:security]; } //set display NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; [formatter setNumberStyle:NSNumberFormatterNoStyle]; [_kcpMtuField setFormatter:formatter]; [_kcpTtiField setFormatter:formatter]; [_kcpUcField setFormatter:formatter]; [_kcpDcField setFormatter:formatter]; [_kcpRbField setFormatter:formatter]; [_kcpWbField setFormatter:formatter]; [_muxConcurrencyField setFormatter:formatter]; // _tcpHdField setautomatcic [_tcpHeaderField setAutomaticQuoteSubstitutionEnabled:false]; [_wsHeaderField setAutomaticQuoteSubstitutionEnabled:false]; //read settings [self fillStream:configWindowController.selectedProfile.streamSettings andMuxSettings:configWindowController.selectedProfile.muxSettings]; } - (void)fillStream:(NSDictionary*)streamSettings andMuxSettings:(NSDictionary*)muxSettings { //kcp [_kcpMtuField setIntegerValue:[streamSettings[@"kcpSettings"][@"mtu"] integerValue]]; [_kcpTtiField setIntegerValue:[streamSettings[@"kcpSettings"][@"tti"] integerValue]]; [_kcpUcField setIntegerValue:[streamSettings[@"kcpSettings"][@"uplinkCapacity"] integerValue]]; [_kcpDcField setIntegerValue:[streamSettings[@"kcpSettings"][@"downlinkCapacity"] integerValue]]; [_kcpRbField setIntegerValue:[streamSettings[@"kcpSettings"][@"readBufferSize"] integerValue]]; [_kcpWbField setIntegerValue:[streamSettings[@"kcpSettings"][@"writeBufferSize"] integerValue]]; [_kcpCongestionButton selectItemAtIndex:[streamSettings[@"kcpSettings"][@"congestion"] boolValue] ? 1 : 0]; [_kcpHeaderTypeButton selectItemAtIndex:searchInArray(streamSettings[@"kcpSettings"][@"header"][@"type"], OBFU_LIST)]; //tcp [_tcpHeaderCusButton setState:[streamSettings[@"tcpSettings"][@"header"][@"type"] isEqualToString:@"http"] ? 1 : 0]; if ([_tcpHeaderCusButton state]) { [_tcpHeaderField setString: [[NSString alloc]initWithData:[NSJSONSerialization dataWithJSONObject:streamSettings[@"tcpSettings"][@"header"] options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding]]; } else { [_tcpHeaderField setString:@"{\"type\": \"none\"}"]; } //websocket NSString *savedWsPath = streamSettings[@"wsSettings"][@"path"]; [_wsPathField setStringValue: savedWsPath != nil ? savedWsPath : @""]; if (streamSettings[@"wsSettings"][@"headers"] != nil) { [_wsHeaderField setString:[[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:streamSettings[@"wsSettings"][@"headers"] options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding]]; } else { [_wsHeaderField setString:@"{}"]; } //http/2 [_httpPathField setStringValue:nilCoalescing(streamSettings[@"httpSettings"][@"path"], @"")]; NSString* hostString = @""; if ([streamSettings[@"httpSettings"] objectForKey:@"host"]) { NSArray* hostArray = streamSettings[@"httpSettings"][@"host"]; if([hostArray isKindOfClass:[NSArray class]] && [hostArray count] > 0) { hostString = [hostArray componentsJoinedByString:@","]; } } [_httpHostsField setStringValue:hostString]; //quic [_quicKeyField setStringValue:nilCoalescing(streamSettings[@"quicSettings"][@"key"], @"")]; [_quicSecurityButton selectItemAtIndex:searchInArray(streamSettings[@"quicSettings"][@"security"], QUIC_SECURITY_LIST)]; [_quicHeaderButton selectItemAtIndex:searchInArray(streamSettings[@"quicSettings"][@"header"][@"type"], OBFU_LIST)]; //tls [_tlsUseButton setState:[[streamSettings objectForKey:@"security"] boolValue]]; NSDictionary* tlsSettings = [streamSettings objectForKey:@"tlsSettings"]; [_tlsAiButton setState:[tlsSettings[@"allowInsecure"] boolValue]]; [_tlsAllowInsecureCiphersButton setState:[tlsSettings[@"allowInsecureCiphers"] boolValue]]; NSArray* alpnArray = streamSettings[@"tlsSettings"][@"alpn"]; NSString* alpnString = [alpnArray componentsJoinedByString:@","]; [_tlsAlpnField setStringValue:nilCoalescing(alpnString, @"http/1.1")]; [_tlsServerNameField setStringValue:streamSettings[@"tlsSettings"][@"serverName"]]; [self useTLS:nil]; // mux [_muxEnableButton setState:[nilCoalescing(muxSettings[@"enabled"], @NO) boolValue]]; [_muxConcurrencyField setIntegerValue:[nilCoalescing(muxSettings[@"concurrency"], @8) integerValue]]; // tcp fast open NSDictionary* tfoSettings = [streamSettings objectForKey:@"sockopt"]; [_tfoEnableButton setState:[tfoSettings[@"tcpFastOpen"] boolValue]]; } - (IBAction)useTLS:(id)sender { [_tlsAiButton setEnabled:[_tlsUseButton state]]; [_tlsAllowInsecureCiphersButton setEnabled:[_tlsUseButton state]]; } - (IBAction)tReset:(id)sender { ServerProfile *p = [[ServerProfile alloc] init]; [self fillStream:p.streamSettings andMuxSettings:p.muxSettings]; } - (IBAction)showTcpHeaderExample:(id)sender { runCommandLine(@"/usr/bin/open", @[[[NSBundle mainBundle] pathForResource:@"tcp_http_header_example" ofType:@"txt"], @"-a", @"/Applications/TextEdit.app"]); } - (IBAction)tCancel:(id)sender { [self.window.sheetParent endSheet:self.window returnCode:NSModalResponseCancel]; } - (IBAction)ok:(id)sender { NSLog(@"%@", [_httpPathField stringValue]); if ([self checkInputs]) { [self.window.sheetParent endSheet:self.window returnCode:NSModalResponseOK]; } } - (IBAction)transportHelp:(id)sender { [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"https://v2ray.com/chapter_02/05_transport.html"]]; } - (BOOL)checkInputs { NSError* httpHeaderParseError; if ([[_tcpHeaderField string] length] == 0) { [_tcpHeaderField setString:TCP_NONE_HEADER_OBJECT]; } [NSJSONSerialization JSONObjectWithData:[[_tcpHeaderField string] dataUsingEncoding:NSUTF8StringEncoding] options:0 error:&httpHeaderParseError]; if (httpHeaderParseError) { NSAlert* parseAlert = [[NSAlert alloc] init]; [parseAlert setMessageText:@"Error in parsing customized tcp http header!"]; [parseAlert beginSheetModalForWindow:[self window] completionHandler:^(NSModalResponse returnCode) { }]; return NO; } NSError* wsHeaderParseError; if ([[_wsHeaderField string] length] == 0) { [_wsHeaderField setString:@"{}"]; } [NSJSONSerialization JSONObjectWithData:[[_wsHeaderField string] dataUsingEncoding:NSUTF8StringEncoding] options:0 error:&wsHeaderParseError]; if(wsHeaderParseError) { NSAlert* parseAlert = [[NSAlert alloc] init]; [parseAlert setMessageText:@"Error in parsing customized WebSocket headers!"]; [parseAlert beginSheetModalForWindow:[self window] completionHandler:^(NSModalResponse returnCode) { }]; return NO; } return YES; } - (NSArray*)generateSettings { NSString* tcpHttpHeaderString = TCP_NONE_HEADER_OBJECT; if ([_tcpHeaderCusButton state]) { tcpHttpHeaderString = [_tcpHeaderField string]; } NSDictionary* tcpHttpHeader = [NSJSONSerialization JSONObjectWithData:[tcpHttpHeaderString dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil]; NSDictionary* wsHeader = [NSJSONSerialization JSONObjectWithData:[[_wsHeaderField string] dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil]; NSArray* httpHosts; if ([[[_httpHostsField stringValue] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length] == 0) { httpHosts = @[]; } else { NSString* hostsString = [[_httpHostsField stringValue] stringByReplacingOccurrencesOfString:@" " withString:@""]; httpHosts = [hostsString componentsSeparatedByString:@","]; } NSDictionary *httpSettings; if ([httpHosts count] > 0) { httpSettings = @{ @"host": httpHosts, @"path": [self->_httpPathField stringValue] }; } else { httpSettings = @{ @"path": [self->_httpPathField stringValue] }; } NSDictionary *streamSettingsImmutable = @{@"kcpSettings": @{@"mtu":[NSNumber numberWithInteger:[self->_kcpMtuField integerValue]], @"tti":[NSNumber numberWithInteger:[self->_kcpTtiField integerValue]], @"uplinkCapacity":[NSNumber numberWithInteger:[self->_kcpUcField integerValue]], @"downlinkCapacity":[NSNumber numberWithInteger:[self->_kcpDcField integerValue]], @"readBufferSize":[NSNumber numberWithInteger:[self->_kcpRbField integerValue]], @"writeBufferSize":[NSNumber numberWithInteger:[self->_kcpWbField integerValue]], @"congestion":[NSNumber numberWithBool:[self->_kcpCongestionButton indexOfSelectedItem] != 0], @"header":@{@"type":[[self->_kcpHeaderTypeButton selectedItem] title]} }, @"tcpSettings":@{@"header": tcpHttpHeader}, @"wsSettings": @{ @"path": [[_wsPathField stringValue] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]], @"headers": nilCoalescing(wsHeader, @{}) }, @"quicSettings": @{ @"security": [[self->_quicSecurityButton selectedItem] title], @"key": [_quicKeyField stringValue], @"header": @{ @"type": [[self->_quicHeaderButton selectedItem] title] } }, @"security": [self->_tlsUseButton state] ? @"tls" : @"none", @"tlsSettings": @{ @"serverName": [_tlsServerNameField stringValue], @"allowInsecure": [NSNumber numberWithBool:[self->_tlsAiButton state]==1], @"allowInsecureCiphers": [NSNumber numberWithBool:[self->_tlsAllowInsecureCiphersButton state]==1], @"alpn": [[[_tlsAlpnField stringValue] stringByReplacingOccurrencesOfString:@" " withString:@""] componentsSeparatedByString:@","] }, @"httpSettings": httpSettings }; NSMutableDictionary *streamSettings = [streamSettingsImmutable mutableCopy]; if ([self->_tfoEnableButton state]) { streamSettings[@"sockopt"] = @{ @"tcpFastOpen": @(YES) }; } NSDictionary* muxSettings = @{ @"enabled":[NSNumber numberWithBool:[self->_muxEnableButton state]==1], @"concurrency":[NSNumber numberWithInteger:[self->_muxConcurrencyField integerValue]] }; return @[streamSettings, muxSettings]; } @end ================================================ FILE: V2RayX/config-sample.plist ================================================ inboundDetour allocate concurrency 3 refresh 5 strategy always domainOverride http tls listen 127.0.0.1 port 8001 protocol http settings timeout 0 streamSettings tag httpDetour dns servers 8.8.8.8 8.8.4.4 localhost inbound listen 127.0.0.1 port 1080 protocol socks settings auth noauth ip 127.0.0.1 udp log error access loglevel warning outbound mux enabled protocol vmess settings vnext address 192.168.1.9 port 10086 users alterId 64 id 23ad6b10-8d1a-40f7-8ad0-e3e35cd38297 security auto streamSettings network tcp security none tlsSettings allowInsecure serverName v2ray.cool wsSettings path /v2ray.cool/ outboundDetour protocol freedom settings tag direct policy levels 0 uplinkOnly 0 routing settings domainStrategy IPIfNonMatch rules type field outboundTag direct domain localhost domain:me.com domain:lookup-api.apple.com domain:icloud-content.com domain:icloud.com domain:cdn-apple.com domain:apple-cloudkit.com domain:apple.com domain:apple.co domain:aaplimg.com domain:guzzoni.apple.com type field outboundTag direct ip geoip:private strategy rules ================================================ FILE: V2RayX/config-sample_new.plist ================================================ dns servers localhost inbounds listen 127.0.0.1 port 1081 protocol socks settings auth noauth ip 127.0.0.1 udp tag socksinbound listen 127.0.0.1 port 8001 protocol http settings timeout 0 tag httpinbound log outbounds routing ================================================ FILE: V2RayX/dlcore.sh ================================================ VERSION="4.18.0" RED='\033[0;31m' GREEN='\033[0;32m' BOLD='\033[1m' NORMAL='\033[0m' cd "$SRCROOT" output="v0" if [[ -f ./v2ray-core-bin/v2ray ]]; then output=$(./v2ray-core-bin/v2ray --version) fi existingVersion=${output:6:${#VERSION}} if [ "$VERSION" != "$existingVersion" ]; then getCore=0 mkdir -p v2ray-core-bin cd v2ray-core-bin curl -s -L -o v2ray-macos.zip https://github.com/v2ray/v2ray-core/releases/download/v${VERSION}/v2ray-macos.zip if [[ $? == 0 ]]; then unzip -o v2ray-macos.zip getCore=1 else unzip -o ~/Downloads/v2ray-macos.zip if [[ $? != 0 ]]; then getCore=0 else chmod +x v2ray-${VERSION}-macos/v2ray output=$(v2ray-${VERSION}-macos/v2ray --version) existingVersion=${output:6:${#VERSION}} if [ "$VERSION" != "$existingVersion" ]; then echo "${RED}v2ray-macos.zip in the Downloads folder does not contain version ${VERSION}." echo "下载文件夹里的v2ray-macos.zip不是${VERSION}版本。${NORMAL}" getCore=0 else getCore=1 fi fi fi if [[ $getCore == 0 ]]; then echo "${RED}download failed!" echo "Use whatever method you can think of, get v2ray-macos.zip of version ${VERSION} from v2ray.com, and put it in the folder 'Downloads' and try this script again." echo "用你能想到任何办法,从 v2ray.com 下载好${VERSION}版本的 v2ray-macos.zip,放在“下载”文件夹里面,然后再次运行这个脚本。${NORMAL}" exit 1 fi chmod +x ./v2ray chmod +x ./v2ctl rm -r v2ray-* else exit 0 fi ================================================ FILE: V2RayX/install_helper.sh ================================================ #!/bin/sh # install_helper.sh # V2RayX # # Copyright © 2016年 Cenmrev. All rights reserved. cd `dirname "${BASH_SOURCE[0]}"` sudo mkdir -p "/Library/Application Support/V2RayX/" sudo cp v2rayx_sysconf "/Library/Application Support/V2RayX/" sudo chown root:admin "/Library/Application Support/V2RayX/v2rayx_sysconf" sudo chmod +s "/Library/Application Support/V2RayX/v2rayx_sysconf" echo done ================================================ FILE: V2RayX/main.m ================================================ // // main.m // V2RayX // // Copyright © 2016年 Cenmrev. All rights reserved. // #import int main(int argc, const char * argv[]) { return NSApplicationMain(argc, argv); } ================================================ FILE: V2RayX/simple.pac ================================================ var V2Ray = "SOCKS5 127.0.0.1:1081; SOCKS 127.0.0.1:1081; DIRECT;"; var domains = [ "vpngate.net", "greatfire.org", "tox.im", "proxifier.com", "dnscrypt.org", "atgfw.org", "chinagfw.org", "whatismyip.com", "goagentplus.com", "shadowsocks.org", "falcop.com", "getlantern.org", "furbo.org", "goagentx.com", "github.com", "sourceforge.net", "torproject.org", "hideme.io", "mozilla.org", "shadowx.work", "v2ray.com", "astrill.com", //Design "deviantart.com", "disqus.com", "disquscdn.com", "tumblr.com", "flickr.com", "imgur.com", "evozi.com", "live.com", "1drv.com", "evernote.com", //blog "wp.com", "yam.com", "ashchan.com", "zuckclub.com", "blogspot.com", "blogspot.jp", "zalex2014.tk", "coreygilmore.com", "wordpress.com", "blogimg.jp", "leaskh.com", "blogger.com", "hexo.io", "medium.com", //GeneralNews "rfi.my", "rfi.fr", "washingtonpost.com", "tmagazine.com", "nytimes.com", "nytimg.com", "imrworldwide.com", "rankingsandreviews.com", "usnews.com", "bbc.co.uk", "bbci.co.uk", "bbc.com", "on-match.com", "solidot.org", //TechNews "engadget.com", //Network "amazonaws.com", "fastly.net", "akamaihd.net", "blogsmithmedia.com", "bit.ly", "d.pr", "ow.ly", "ift.tt", "nateparrott.com", "stacksocial.com", "feedly.com", "acgtea.com", //academy and develop "ieee.org", "mathoverflow.net", "tex.stackexchange.com", "academia.edu", "geogebra.org", "golang.org", "netspeak.org", "endreslab.com", //Universities "illinois.edu", "berkeley.edu", "wisc.edu", "cmu.edu", "rochester.edu", "purdue.edu", "technolutions.net", "netflix.com", //Online Dictionary "ldoceonline.com", "freedicts.com", //Softwares "formacx.com", "trionworlds.com", "line.me", //otaku "e-hentai.org", "nhentai.net", "nicovideo.jp", "nimg.jp", "pixnet.net", "fc2.com", "nyaatorrents.org", "nyaa.se", "share.dmhy.org", "loli.us", //facebook "facebook.net", "instagram.com", "facebook.com", "fb.me", "cdninstagram.com", "fbcdn.net", "booth.pm", "telegram.org", "telegram.me", "wikipedia.org", "pixiv.net", "twitch.tv", //Twitter "twitter.com", "t.co", "twimg.com", //Google "gmail.com", "googlemail.com", "mailchimp.com", "mail-archive.com", "google.com", "goo.gl", "google.com.hk", "google.com.tw", "google.co.jp", "googlecode.com", "googleapis.com", "ggpht.com", "youtube.com", "youtu.be", "ytimg.com", "youtube-nocookie.com", "googlevideo.com", "sketchup.com", "gstatic.com", "google-analytics.com", "googleusercontent.com", "chrome.com", "g.co", "googledrive.com", "googletagmanager.com", "googleadservices.com", "abc.xyz", //Dropbox "dropbox.com", "dropboxusercontent.com", "dropboxwiki.com", //iTuens "mzstatic.com", "itunes.apple.com", //cdn "cloudfront.net", "colwiz.com" ]; function FindProxyForURL(url, host) { for (var i = domains.length - 1; i >= 0; i--) { if (dnsDomainIs(host, domains[i])) { return V2Ray; } } return "DIRECT"; } ================================================ FILE: V2RayX/tcp_http_header_example.txt ================================================ { "type": "http", "request": { "version": "1.1", "method": "GET", "path": ["/"], "headers": { "Host": ["www.baidu.com", "www.bing.com"], "User-Agent": [ "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36", "Mozilla/5.0 (iPhone; CPU iPhone OS 10_0_2 like Mac OS X) AppleWebKit/601.1 (KHTML, like Gecko) CriOS/53.0.2785.109 Mobile/14A456 Safari/601.1.46" ], "Accept-Encoding": ["gzip, deflate"], "Connection": ["keep-alive"], "Pragma": "no-cache" } }, "response": { "version": "1.1", "status": "200", "reason": "OK", "headers": { "Content-Type": ["application/octet-stream", "video/mpeg"], "Transfer-Encoding": ["chunked"], "Connection": ["keep-alive"], "Pragma": "no-cache" } } } ================================================ FILE: V2RayX/utilities.h ================================================ // // utilities.h // V2RayX // // #ifndef utilities_h #define utilities_h #import #import "MutableDeepCopying.h" #define DOMAIN_STRATEGY_LIST (@[@"AsIs", @"IPIfNonMatch", @"IPOnDemand"]) #define ROUTING_NETWORK_LIST (@[@"tcp", @"udp", @"tcp,udp"]) #define OBFU_LIST (@[@"none", @"srtp", @"utp", @"wechat-video", @"dtls", @"wireguard"]) #define VMESS_SECURITY_LIST (@[@"auto", @"aes-128-gcm", @"chacha20-poly1305", @"none"]) #define NETWORK_LIST (@[@"tcp", @"kcp", @"ws", @"http", @"quic"]) #define QUIC_SECURITY_LIST (@[@"none", @"aes-128-gcm", @"chacha20-poly1305"]) #define nilCoalescing(a,b) ( (a != nil) ? (a) : (b) ) // equivalent to ?? operator in Swift #define TCP_NONE_HEADER_OBJECT (@"{\"type\": \"none\"}") #define ROUTING_DIRECT (@{@"name": @"all_to_direct",@"domainStrategy": @"AsIs",@"rules": @[@{@"type": @"field",@"port": @"0-65535",@"outboundTag": @"direct"}]}) #define ROUTING_GLOBAL (@{@"name": @"all_to_main",@"domainStrategy": @"AsIs",@"rules": @[@{@"type": @"field",@"port": @"0-65535",@"outboundTag": @"main"}]}) #define ROUTING_BYPASSCN_PRIVATE_APPLE (@{@"name": @"bypasscn_private_apple",@"domainStrategy":@"IPIfNonMatch",@"rules":@[@{@"domain":@[@"localhost",@"domain:me.com",@"domain:lookup-api.apple.com",@"domain:icloud-content.com",@"domain:icloud.com",@"domain:cdn-apple.com",@"domain:apple-cloudkit.com",@"domain:apple.com",@"domain:apple.co",@"domain:aaplimg.com",@"domain:guzzoni.apple.com",@"geosite:cn"],@"type":@"field",@"outboundTag":@"direct"},@{@"type":@"field",@"outboundTag":@"direct",@"ip":@[@"geoip:private",@"geoip:cn"]},@{@"type":@"field",@"outboundTag":@"main",@"port":@"0-65535"}]}) #define OUTBOUND_DIRECT (@{@"protocol":@"freedom",@"tag":@"direct",@"settings":@{}}) #define OUTBOUND_DECLINE (@{@"protocol":@"blackhole",@"tag":@"decline",@"settings": @{}}) #define RESERVED_TAGS (@[@"main", @"direct", @"decline", @"balance"]) #define SUPPORTED_SS_SECURITY (@[@"aes-256-cfb",@"aes-128-cfb",@"chacha20",@"chacha20-ietf",@"aes-256-gcm",@"aes-128-gcm",@"chacha20-poly1305", @"chacha20-ietf-poly1305"]) #define EMPTY_DICT ([[NSMutableDictionary alloc] init]) #define EMPTY_IMPORT_RESULT ([@{@"vmess": @[], @"other": @[], @"rules":@[]} mutableDeepCopy]) #define SNIFFING_PROTOCOL (@[@"http", @"tls", @"bittorrent"]) #define NOT_SUPPORTED_ROUTING (@[@"source", @"user"]) #define SUPPORTED_ROUTING (@[@"domain", @"ip", @"network", @"port", @"inboundTag", @"protocol"]) NSUInteger searchInArray(NSString* str, NSArray* array); #endif /* utilities_h */ ================================================ FILE: V2RayX/utilities.m ================================================ // // utilities.m // V2RayX // // #import "utilities.h" NSUInteger searchInArray(NSString* str, NSArray* array) { if ([str isKindOfClass:[NSString class]]) { NSUInteger index = 0; for (NSString* s in array) { if ([s isKindOfClass:[NSString class]] && [s isEqualToString:str]) { return index; } index += 1; } } return 0; } ================================================ FILE: V2RayX.xcodeproj/project.pbxproj ================================================ // !$*UTF8*$! { archiveVersion = 1; classes = { }; objectVersion = 46; objects = { /* Begin PBXBuildFile section */ 9504C07D1C662C3000352520 /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 9504C07C1C662C3000352520 /* AppDelegate.m */; }; 9504C0801C662C3000352520 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 9504C07F1C662C3000352520 /* main.m */; }; 9504C0821C662C3000352520 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 9504C0811C662C3000352520 /* Assets.xcassets */; }; 9504C0851C662C3000352520 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 9504C0831C662C3000352520 /* MainMenu.xib */; }; 9504C08D1C662C9100352520 /* ConfigWindow.xib in Resources */ = {isa = PBXBuildFile; fileRef = 9504C08C1C662C9100352520 /* ConfigWindow.xib */; }; 9504C0901C662CBF00352520 /* ConfigWindowController.m in Sources */ = {isa = PBXBuildFile; fileRef = 9504C08F1C662CBF00352520 /* ConfigWindowController.m */; }; 9504C0C11C662D9400352520 /* libz.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = 9504C0C01C662D9400352520 /* libz.tbd */; }; 9504C0C91C662DB500352520 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 9504C0C81C662DB500352520 /* main.m */; }; 9504C0CF1C662DE300352520 /* v2rayx_sysconf in Resources */ = {isa = PBXBuildFile; fileRef = 9504C0C61C662DB400352520 /* v2rayx_sysconf */; }; 9504C0D11C66373400352520 /* install_helper.sh in Resources */ = {isa = PBXBuildFile; fileRef = 9504C0D01C662E0800352520 /* install_helper.sh */; }; 9504C0D41C66511B00352520 /* ServerProfile.m in Sources */ = {isa = PBXBuildFile; fileRef = 9504C0D31C66511B00352520 /* ServerProfile.m */; }; 9565E28B1DB25C010082658C /* TransportWindow.xib in Resources */ = {isa = PBXBuildFile; fileRef = 9565E28A1DB25C010082658C /* TransportWindow.xib */; }; 9577E1B21C6B065E00093BD3 /* GCDWebServer.m in Sources */ = {isa = PBXBuildFile; fileRef = 9577E1951C6B065D00093BD3 /* GCDWebServer.m */; }; 9577E1B31C6B065E00093BD3 /* GCDWebServerConnection.m in Sources */ = {isa = PBXBuildFile; fileRef = 9577E1971C6B065D00093BD3 /* GCDWebServerConnection.m */; }; 9577E1B41C6B065E00093BD3 /* GCDWebServerFunctions.m in Sources */ = {isa = PBXBuildFile; fileRef = 9577E1991C6B065D00093BD3 /* GCDWebServerFunctions.m */; }; 9577E1B51C6B065E00093BD3 /* GCDWebServerRequest.m in Sources */ = {isa = PBXBuildFile; fileRef = 9577E19D1C6B065D00093BD3 /* GCDWebServerRequest.m */; }; 9577E1B61C6B065E00093BD3 /* GCDWebServerResponse.m in Sources */ = {isa = PBXBuildFile; fileRef = 9577E19F1C6B065D00093BD3 /* GCDWebServerResponse.m */; }; 9577E1B71C6B065E00093BD3 /* GCDWebServerDataRequest.m in Sources */ = {isa = PBXBuildFile; fileRef = 9577E1A21C6B065D00093BD3 /* GCDWebServerDataRequest.m */; }; 9577E1B81C6B065E00093BD3 /* GCDWebServerFileRequest.m in Sources */ = {isa = PBXBuildFile; fileRef = 9577E1A41C6B065D00093BD3 /* GCDWebServerFileRequest.m */; }; 9577E1B91C6B065E00093BD3 /* GCDWebServerMultiPartFormRequest.m in Sources */ = {isa = PBXBuildFile; fileRef = 9577E1A61C6B065D00093BD3 /* GCDWebServerMultiPartFormRequest.m */; }; 9577E1BA1C6B065E00093BD3 /* GCDWebServerURLEncodedFormRequest.m in Sources */ = {isa = PBXBuildFile; fileRef = 9577E1A81C6B065D00093BD3 /* GCDWebServerURLEncodedFormRequest.m */; }; 9577E1BB1C6B065E00093BD3 /* GCDWebServerDataResponse.m in Sources */ = {isa = PBXBuildFile; fileRef = 9577E1AB1C6B065E00093BD3 /* GCDWebServerDataResponse.m */; }; 9577E1BC1C6B065E00093BD3 /* GCDWebServerErrorResponse.m in Sources */ = {isa = PBXBuildFile; fileRef = 9577E1AD1C6B065E00093BD3 /* GCDWebServerErrorResponse.m */; }; 9577E1BD1C6B065E00093BD3 /* GCDWebServerFileResponse.m in Sources */ = {isa = PBXBuildFile; fileRef = 9577E1AF1C6B065E00093BD3 /* GCDWebServerFileResponse.m */; }; 9577E1BE1C6B065E00093BD3 /* GCDWebServerStreamedResponse.m in Sources */ = {isa = PBXBuildFile; fileRef = 9577E1B11C6B065E00093BD3 /* GCDWebServerStreamedResponse.m */; }; 95A143CC1C87FCDC008756B9 /* Cocoa.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 95A143CA1C87FC6E008756B9 /* Cocoa.framework */; }; 95E524CB1C674CC80008BB12 /* simple.pac in Resources */ = {isa = PBXBuildFile; fileRef = 95E524CA1C674CC80008BB12 /* simple.pac */; }; 9D24863421CD9EC100C529AB /* config-sample_new.plist in Resources */ = {isa = PBXBuildFile; fileRef = 9D24863321CD9EC000C529AB /* config-sample_new.plist */; }; 9D3CEE6F209E070F0077CCFE /* AdvancedWindow.xib in Resources */ = {isa = PBXBuildFile; fileRef = 9D3CEE6E209E070F0077CCFE /* AdvancedWindow.xib */; }; 9D5EAC151FDCD70300C14B46 /* geoip.dat in Resources */ = {isa = PBXBuildFile; fileRef = 9D5EAC101FDCD54700C14B46 /* geoip.dat */; }; 9D5EAC161FDCD70300C14B46 /* geosite.dat in Resources */ = {isa = PBXBuildFile; fileRef = 9D5EAC0F1FDCD54600C14B46 /* geosite.dat */; }; 9D5EAC171FDCD70300C14B46 /* v2ctl in Resources */ = {isa = PBXBuildFile; fileRef = 9D5EAC0E1FDCD54600C14B46 /* v2ctl */; }; 9D5EAC181FDCD70300C14B46 /* v2ray in Resources */ = {isa = PBXBuildFile; fileRef = 953B60571DB3F6B700D40654 /* v2ray */; }; 9D7109611E0F43BD008A6362 /* Credits.rtf in Resources */ = {isa = PBXBuildFile; fileRef = 9D7109601E0F43BD008A6362 /* Credits.rtf */; }; 9D71D61721D06006007DA052 /* ConfigImporter.m in Sources */ = {isa = PBXBuildFile; fileRef = 9D71D61621D06006007DA052 /* ConfigImporter.m */; }; 9D7DFE541EBEC947001FECBD /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 9D7DFE531EBEC947001FECBD /* main.m */; }; 9DA4A84120C14178000FF35D /* tcp_http_header_example.txt in Resources */ = {isa = PBXBuildFile; fileRef = 9DA4A84020C14178000FF35D /* tcp_http_header_example.txt */; }; 9DB4FE951F205BEB00CCEE5F /* config-sample.plist in Resources */ = {isa = PBXBuildFile; fileRef = 9DB4FE941F205BEB00CCEE5F /* config-sample.plist */; }; 9DBF54CF221615AD00B61D55 /* NSData+AES256Encryption.m in Sources */ = {isa = PBXBuildFile; fileRef = 9DBF54CE221615AD00B61D55 /* NSData+AES256Encryption.m */; }; 9DDC059121CA8CFF00C6C2D7 /* TransportWindowController.m in Sources */ = {isa = PBXBuildFile; fileRef = 9DDC059021CA8CFF00C6C2D7 /* TransportWindowController.m */; }; 9DDC059621CA8EAD00C6C2D7 /* utilities.m in Sources */ = {isa = PBXBuildFile; fileRef = 9DDC059521CA8EAD00C6C2D7 /* utilities.m */; }; 9DEB294D21CB64CF0052D2BB /* AdvancedWindowController.m in Sources */ = {isa = PBXBuildFile; fileRef = 9DEB294C21CB64CF0052D2BB /* AdvancedWindowController.m */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ 9504C0CD1C662DC500352520 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 9504C0701C662C3000352520 /* Project object */; proxyType = 1; remoteGlobalIDString = 9504C0C51C662DB400352520; remoteInfo = v2rayx_sysconf; }; /* End PBXContainerItemProxy section */ /* Begin PBXCopyFilesBuildPhase section */ 9504C0C41C662DB400352520 /* CopyFiles */ = { isa = PBXCopyFilesBuildPhase; buildActionMask = 2147483647; dstPath = /usr/share/man/man1/; dstSubfolderSpec = 0; files = ( ); runOnlyForDeploymentPostprocessing = 1; }; 9D7DFE4F1EBEC947001FECBD /* CopyFiles */ = { isa = PBXCopyFilesBuildPhase; buildActionMask = 2147483647; dstPath = /usr/share/man/man1/; dstSubfolderSpec = 0; files = ( ); runOnlyForDeploymentPostprocessing = 1; }; /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ 9504C0781C662C3000352520 /* V2RayX.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = V2RayX.app; sourceTree = BUILT_PRODUCTS_DIR; }; 9504C07B1C662C3000352520 /* AppDelegate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = ""; }; 9504C07C1C662C3000352520 /* AppDelegate.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = ""; }; 9504C07F1C662C3000352520 /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = ""; }; 9504C0811C662C3000352520 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 9504C0841C662C3000352520 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/MainMenu.xib; sourceTree = ""; }; 9504C0861C662C3000352520 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 9504C08C1C662C9100352520 /* ConfigWindow.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = ConfigWindow.xib; sourceTree = ""; }; 9504C08E1C662CBF00352520 /* ConfigWindowController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ConfigWindowController.h; sourceTree = ""; }; 9504C08F1C662CBF00352520 /* ConfigWindowController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = ConfigWindowController.m; sourceTree = ""; }; 9504C0C01C662D9400352520 /* libz.tbd */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = libz.tbd; path = usr/lib/libz.tbd; sourceTree = SDKROOT; }; 9504C0C61C662DB400352520 /* v2rayx_sysconf */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = v2rayx_sysconf; sourceTree = BUILT_PRODUCTS_DIR; }; 9504C0C81C662DB500352520 /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = ""; }; 9504C0D01C662E0800352520 /* install_helper.sh */ = {isa = PBXFileReference; lastKnownFileType = text.script.sh; path = install_helper.sh; sourceTree = ""; }; 9504C0D21C66511B00352520 /* ServerProfile.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ServerProfile.h; sourceTree = ""; }; 9504C0D31C66511B00352520 /* ServerProfile.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = ServerProfile.m; sourceTree = ""; }; 953B60551DB3F65A00D40654 /* dlcore.sh */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.script.sh; path = dlcore.sh; sourceTree = ""; }; 953B60571DB3F6B700D40654 /* v2ray */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.executable"; name = v2ray; path = "../v2ray-core-bin/v2ray"; sourceTree = ""; }; 9565E28A1DB25C010082658C /* TransportWindow.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = TransportWindow.xib; sourceTree = ""; }; 9577E1941C6B065D00093BD3 /* GCDWebServer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GCDWebServer.h; sourceTree = ""; }; 9577E1951C6B065D00093BD3 /* GCDWebServer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GCDWebServer.m; sourceTree = ""; }; 9577E1961C6B065D00093BD3 /* GCDWebServerConnection.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GCDWebServerConnection.h; sourceTree = ""; }; 9577E1971C6B065D00093BD3 /* GCDWebServerConnection.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GCDWebServerConnection.m; sourceTree = ""; }; 9577E1981C6B065D00093BD3 /* GCDWebServerFunctions.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GCDWebServerFunctions.h; sourceTree = ""; }; 9577E1991C6B065D00093BD3 /* GCDWebServerFunctions.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GCDWebServerFunctions.m; sourceTree = ""; }; 9577E19A1C6B065D00093BD3 /* GCDWebServerHTTPStatusCodes.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GCDWebServerHTTPStatusCodes.h; sourceTree = ""; }; 9577E19B1C6B065D00093BD3 /* GCDWebServerPrivate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GCDWebServerPrivate.h; sourceTree = ""; }; 9577E19C1C6B065D00093BD3 /* GCDWebServerRequest.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GCDWebServerRequest.h; sourceTree = ""; }; 9577E19D1C6B065D00093BD3 /* GCDWebServerRequest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GCDWebServerRequest.m; sourceTree = ""; }; 9577E19E1C6B065D00093BD3 /* GCDWebServerResponse.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GCDWebServerResponse.h; sourceTree = ""; }; 9577E19F1C6B065D00093BD3 /* GCDWebServerResponse.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GCDWebServerResponse.m; sourceTree = ""; }; 9577E1A11C6B065D00093BD3 /* GCDWebServerDataRequest.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GCDWebServerDataRequest.h; sourceTree = ""; }; 9577E1A21C6B065D00093BD3 /* GCDWebServerDataRequest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GCDWebServerDataRequest.m; sourceTree = ""; }; 9577E1A31C6B065D00093BD3 /* GCDWebServerFileRequest.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GCDWebServerFileRequest.h; sourceTree = ""; }; 9577E1A41C6B065D00093BD3 /* GCDWebServerFileRequest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GCDWebServerFileRequest.m; sourceTree = ""; }; 9577E1A51C6B065D00093BD3 /* GCDWebServerMultiPartFormRequest.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GCDWebServerMultiPartFormRequest.h; sourceTree = ""; }; 9577E1A61C6B065D00093BD3 /* GCDWebServerMultiPartFormRequest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GCDWebServerMultiPartFormRequest.m; sourceTree = ""; }; 9577E1A71C6B065D00093BD3 /* GCDWebServerURLEncodedFormRequest.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GCDWebServerURLEncodedFormRequest.h; sourceTree = ""; }; 9577E1A81C6B065D00093BD3 /* GCDWebServerURLEncodedFormRequest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GCDWebServerURLEncodedFormRequest.m; sourceTree = ""; }; 9577E1AA1C6B065E00093BD3 /* GCDWebServerDataResponse.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GCDWebServerDataResponse.h; sourceTree = ""; }; 9577E1AB1C6B065E00093BD3 /* GCDWebServerDataResponse.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GCDWebServerDataResponse.m; sourceTree = ""; }; 9577E1AC1C6B065E00093BD3 /* GCDWebServerErrorResponse.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GCDWebServerErrorResponse.h; sourceTree = ""; }; 9577E1AD1C6B065E00093BD3 /* GCDWebServerErrorResponse.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GCDWebServerErrorResponse.m; sourceTree = ""; }; 9577E1AE1C6B065E00093BD3 /* GCDWebServerFileResponse.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GCDWebServerFileResponse.h; sourceTree = ""; }; 9577E1AF1C6B065E00093BD3 /* GCDWebServerFileResponse.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GCDWebServerFileResponse.m; sourceTree = ""; }; 9577E1B01C6B065E00093BD3 /* GCDWebServerStreamedResponse.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GCDWebServerStreamedResponse.h; sourceTree = ""; }; 9577E1B11C6B065E00093BD3 /* GCDWebServerStreamedResponse.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GCDWebServerStreamedResponse.m; sourceTree = ""; }; 95862BD41DB2862E00F4A9CA /* compilefromsource.sh */ = {isa = PBXFileReference; lastKnownFileType = text.script.sh; path = compilefromsource.sh; sourceTree = ""; }; 95A143CA1C87FC6E008756B9 /* Cocoa.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Cocoa.framework; path = System/Library/Frameworks/Cocoa.framework; sourceTree = SDKROOT; }; 95E524CA1C674CC80008BB12 /* simple.pac */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = simple.pac; sourceTree = ""; }; 9D24863321CD9EC000C529AB /* config-sample_new.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = "config-sample_new.plist"; sourceTree = ""; }; 9D3CEE6E209E070F0077CCFE /* AdvancedWindow.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; path = AdvancedWindow.xib; sourceTree = ""; }; 9D5EAC0E1FDCD54600C14B46 /* v2ctl */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.executable"; name = v2ctl; path = "v2ray-core-bin/v2ctl"; sourceTree = SOURCE_ROOT; }; 9D5EAC0F1FDCD54600C14B46 /* geosite.dat */ = {isa = PBXFileReference; lastKnownFileType = file; name = geosite.dat; path = "v2ray-core-bin/geosite.dat"; sourceTree = SOURCE_ROOT; }; 9D5EAC101FDCD54700C14B46 /* geoip.dat */ = {isa = PBXFileReference; lastKnownFileType = file; name = geoip.dat; path = "v2ray-core-bin/geoip.dat"; sourceTree = SOURCE_ROOT; }; 9D7109601E0F43BD008A6362 /* Credits.rtf */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.rtf; path = Credits.rtf; sourceTree = ""; }; 9D71D61521D06006007DA052 /* ConfigImporter.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ConfigImporter.h; sourceTree = ""; }; 9D71D61621D06006007DA052 /* ConfigImporter.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = ConfigImporter.m; sourceTree = ""; }; 9D7DFE511EBEC947001FECBD /* jsonplist */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = jsonplist; sourceTree = BUILT_PRODUCTS_DIR; }; 9D7DFE531EBEC947001FECBD /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = ""; }; 9DA398B5209ECED400784947 /* sysconf_version.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = sysconf_version.h; sourceTree = ""; }; 9DA4A84020C14178000FF35D /* tcp_http_header_example.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = tcp_http_header_example.txt; sourceTree = ""; }; 9DB4FE941F205BEB00CCEE5F /* config-sample.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = "config-sample.plist"; sourceTree = ""; }; 9DBF3AA3213E1921008C7249 /* MutableDeepCopying.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MutableDeepCopying.h; sourceTree = ""; }; 9DBF54CD221615AD00B61D55 /* NSData+AES256Encryption.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "NSData+AES256Encryption.h"; sourceTree = ""; }; 9DBF54CE221615AD00B61D55 /* NSData+AES256Encryption.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = "NSData+AES256Encryption.m"; sourceTree = ""; }; 9DDC058F21CA8CFF00C6C2D7 /* TransportWindowController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = TransportWindowController.h; sourceTree = ""; }; 9DDC059021CA8CFF00C6C2D7 /* TransportWindowController.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = TransportWindowController.m; sourceTree = ""; }; 9DDC059421CA8DE900C6C2D7 /* utilities.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = utilities.h; sourceTree = ""; }; 9DDC059521CA8EAD00C6C2D7 /* utilities.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = utilities.m; sourceTree = ""; }; 9DEB294B21CB64CF0052D2BB /* AdvancedWindowController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AdvancedWindowController.h; sourceTree = ""; }; 9DEB294C21CB64CF0052D2BB /* AdvancedWindowController.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AdvancedWindowController.m; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ 9504C0751C662C3000352520 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( 95A143CC1C87FCDC008756B9 /* Cocoa.framework in Frameworks */, 9504C0C11C662D9400352520 /* libz.tbd in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; 9504C0C31C662DB400352520 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( ); runOnlyForDeploymentPostprocessing = 0; }; 9D7DFE4E1EBEC947001FECBD /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ 9504C06F1C662C3000352520 = { isa = PBXGroup; children = ( 95862BD41DB2862E00F4A9CA /* compilefromsource.sh */, 9D7DFE521EBEC947001FECBD /* jsonplist */, 95FCB2451C688BB20081B6FD /* Frameworks */, 9504C07A1C662C3000352520 /* V2RayX */, 9504C0C71C662DB500352520 /* v2rayx_sysconf */, 9504C0791C662C3000352520 /* Products */, ); sourceTree = ""; }; 9504C0791C662C3000352520 /* Products */ = { isa = PBXGroup; children = ( 9504C0781C662C3000352520 /* V2RayX.app */, 9504C0C61C662DB400352520 /* v2rayx_sysconf */, 9D7DFE511EBEC947001FECBD /* jsonplist */, ); name = Products; sourceTree = ""; }; 9504C07A1C662C3000352520 /* V2RayX */ = { isa = PBXGroup; children = ( 9DBF54CD221615AD00B61D55 /* NSData+AES256Encryption.h */, 9DBF54CE221615AD00B61D55 /* NSData+AES256Encryption.m */, 9577E1921C6B065D00093BD3 /* GCDWebServer */, 9504C07B1C662C3000352520 /* AppDelegate.h */, 9504C07C1C662C3000352520 /* AppDelegate.m */, 9504C0811C662C3000352520 /* Assets.xcassets */, 9504C0831C662C3000352520 /* MainMenu.xib */, 9504C08C1C662C9100352520 /* ConfigWindow.xib */, 9D71D61521D06006007DA052 /* ConfigImporter.h */, 9D71D61621D06006007DA052 /* ConfigImporter.m */, 9D3CEE6E209E070F0077CCFE /* AdvancedWindow.xib */, 9DEB294B21CB64CF0052D2BB /* AdvancedWindowController.h */, 9DEB294C21CB64CF0052D2BB /* AdvancedWindowController.m */, 9565E28A1DB25C010082658C /* TransportWindow.xib */, 9DDC058F21CA8CFF00C6C2D7 /* TransportWindowController.h */, 9DDC059021CA8CFF00C6C2D7 /* TransportWindowController.m */, 9504C08E1C662CBF00352520 /* ConfigWindowController.h */, 9504C08F1C662CBF00352520 /* ConfigWindowController.m */, 9504C0D21C66511B00352520 /* ServerProfile.h */, 9504C0D31C66511B00352520 /* ServerProfile.m */, 9504C0861C662C3000352520 /* Info.plist */, 9504C07E1C662C3000352520 /* Supporting Files */, ); path = V2RayX; sourceTree = ""; }; 9504C07E1C662C3000352520 /* Supporting Files */ = { isa = PBXGroup; children = ( 9DDC059421CA8DE900C6C2D7 /* utilities.h */, 9DDC059521CA8EAD00C6C2D7 /* utilities.m */, 9DBF3AA3213E1921008C7249 /* MutableDeepCopying.h */, 9DB4FE941F205BEB00CCEE5F /* config-sample.plist */, 9D24863321CD9EC000C529AB /* config-sample_new.plist */, 9DA4A84020C14178000FF35D /* tcp_http_header_example.txt */, 95E524CA1C674CC80008BB12 /* simple.pac */, 9504C0D01C662E0800352520 /* install_helper.sh */, 953B60551DB3F65A00D40654 /* dlcore.sh */, 9D5EAC111FDCD54F00C14B46 /* v2ray-core */, 9D7109601E0F43BD008A6362 /* Credits.rtf */, 9504C07F1C662C3000352520 /* main.m */, ); name = "Supporting Files"; sourceTree = ""; }; 9504C0C71C662DB500352520 /* v2rayx_sysconf */ = { isa = PBXGroup; children = ( 9504C0C81C662DB500352520 /* main.m */, 9DA398B5209ECED400784947 /* sysconf_version.h */, ); path = v2rayx_sysconf; sourceTree = ""; }; 9577E1921C6B065D00093BD3 /* GCDWebServer */ = { isa = PBXGroup; children = ( 9577E1931C6B065D00093BD3 /* Core */, 9577E1A01C6B065D00093BD3 /* Requests */, 9577E1A91C6B065E00093BD3 /* Responses */, ); name = GCDWebServer; path = GCDWebServer/GCDWebServer; sourceTree = SOURCE_ROOT; }; 9577E1931C6B065D00093BD3 /* Core */ = { isa = PBXGroup; children = ( 9577E1941C6B065D00093BD3 /* GCDWebServer.h */, 9577E1951C6B065D00093BD3 /* GCDWebServer.m */, 9577E1961C6B065D00093BD3 /* GCDWebServerConnection.h */, 9577E1971C6B065D00093BD3 /* GCDWebServerConnection.m */, 9577E1981C6B065D00093BD3 /* GCDWebServerFunctions.h */, 9577E1991C6B065D00093BD3 /* GCDWebServerFunctions.m */, 9577E19A1C6B065D00093BD3 /* GCDWebServerHTTPStatusCodes.h */, 9577E19B1C6B065D00093BD3 /* GCDWebServerPrivate.h */, 9577E19C1C6B065D00093BD3 /* GCDWebServerRequest.h */, 9577E19D1C6B065D00093BD3 /* GCDWebServerRequest.m */, 9577E19E1C6B065D00093BD3 /* GCDWebServerResponse.h */, 9577E19F1C6B065D00093BD3 /* GCDWebServerResponse.m */, ); path = Core; sourceTree = ""; }; 9577E1A01C6B065D00093BD3 /* Requests */ = { isa = PBXGroup; children = ( 9577E1A11C6B065D00093BD3 /* GCDWebServerDataRequest.h */, 9577E1A21C6B065D00093BD3 /* GCDWebServerDataRequest.m */, 9577E1A31C6B065D00093BD3 /* GCDWebServerFileRequest.h */, 9577E1A41C6B065D00093BD3 /* GCDWebServerFileRequest.m */, 9577E1A51C6B065D00093BD3 /* GCDWebServerMultiPartFormRequest.h */, 9577E1A61C6B065D00093BD3 /* GCDWebServerMultiPartFormRequest.m */, 9577E1A71C6B065D00093BD3 /* GCDWebServerURLEncodedFormRequest.h */, 9577E1A81C6B065D00093BD3 /* GCDWebServerURLEncodedFormRequest.m */, ); path = Requests; sourceTree = ""; }; 9577E1A91C6B065E00093BD3 /* Responses */ = { isa = PBXGroup; children = ( 9577E1AA1C6B065E00093BD3 /* GCDWebServerDataResponse.h */, 9577E1AB1C6B065E00093BD3 /* GCDWebServerDataResponse.m */, 9577E1AC1C6B065E00093BD3 /* GCDWebServerErrorResponse.h */, 9577E1AD1C6B065E00093BD3 /* GCDWebServerErrorResponse.m */, 9577E1AE1C6B065E00093BD3 /* GCDWebServerFileResponse.h */, 9577E1AF1C6B065E00093BD3 /* GCDWebServerFileResponse.m */, 9577E1B01C6B065E00093BD3 /* GCDWebServerStreamedResponse.h */, 9577E1B11C6B065E00093BD3 /* GCDWebServerStreamedResponse.m */, ); path = Responses; sourceTree = ""; }; 95FCB2451C688BB20081B6FD /* Frameworks */ = { isa = PBXGroup; children = ( 95A143CA1C87FC6E008756B9 /* Cocoa.framework */, 9504C0C01C662D9400352520 /* libz.tbd */, ); name = Frameworks; path = V2RayX; sourceTree = ""; }; 9D5EAC111FDCD54F00C14B46 /* v2ray-core */ = { isa = PBXGroup; children = ( 9D5EAC101FDCD54700C14B46 /* geoip.dat */, 9D5EAC0F1FDCD54600C14B46 /* geosite.dat */, 9D5EAC0E1FDCD54600C14B46 /* v2ctl */, 953B60571DB3F6B700D40654 /* v2ray */, ); name = "v2ray-core"; sourceTree = ""; }; 9D7DFE521EBEC947001FECBD /* jsonplist */ = { isa = PBXGroup; children = ( 9D7DFE531EBEC947001FECBD /* main.m */, ); path = jsonplist; sourceTree = ""; }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ 9504C0771C662C3000352520 /* V2RayX */ = { isa = PBXNativeTarget; buildConfigurationList = 9504C0891C662C3000352520 /* Build configuration list for PBXNativeTarget "V2RayX" */; buildPhases = ( 9504C0741C662C3000352520 /* Sources */, 9504C0751C662C3000352520 /* Frameworks */, 9DB94D77209D273A0001E9DD /* Run Script */, 953B60541DB3E31D00D40654 /* Run Script */, 9504C0761C662C3000352520 /* Resources */, ); buildRules = ( ); dependencies = ( 9504C0CE1C662DC500352520 /* PBXTargetDependency */, ); name = V2RayX; productName = V2RayX; productReference = 9504C0781C662C3000352520 /* V2RayX.app */; productType = "com.apple.product-type.application"; }; 9504C0C51C662DB400352520 /* v2rayx_sysconf */ = { isa = PBXNativeTarget; buildConfigurationList = 9504C0CA1C662DB500352520 /* Build configuration list for PBXNativeTarget "v2rayx_sysconf" */; buildPhases = ( 9504C0C21C662DB400352520 /* Sources */, 9504C0C31C662DB400352520 /* Frameworks */, 9504C0C41C662DB400352520 /* CopyFiles */, ); buildRules = ( ); dependencies = ( ); name = v2rayx_sysconf; productName = v2rayx_sysconf; productReference = 9504C0C61C662DB400352520 /* v2rayx_sysconf */; productType = "com.apple.product-type.tool"; }; 9D7DFE501EBEC947001FECBD /* jsonplist */ = { isa = PBXNativeTarget; buildConfigurationList = 9D7DFE571EBEC947001FECBD /* Build configuration list for PBXNativeTarget "jsonplist" */; buildPhases = ( 9D7DFE4D1EBEC947001FECBD /* Sources */, 9D7DFE4E1EBEC947001FECBD /* Frameworks */, 9D7DFE4F1EBEC947001FECBD /* CopyFiles */, ); buildRules = ( ); dependencies = ( ); name = jsonplist; productName = jsonplist; productReference = 9D7DFE511EBEC947001FECBD /* jsonplist */; productType = "com.apple.product-type.tool"; }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ 9504C0701C662C3000352520 /* Project object */ = { isa = PBXProject; attributes = { LastUpgradeCheck = 0930; ORGANIZATIONNAME = "Project V2Ray"; TargetAttributes = { 9504C0771C662C3000352520 = { CreatedOnToolsVersion = 7.2.1; }; 9504C0C51C662DB400352520 = { CreatedOnToolsVersion = 7.2.1; }; 9D7DFE501EBEC947001FECBD = { CreatedOnToolsVersion = 8.3.2; ProvisioningStyle = Automatic; }; }; }; buildConfigurationList = 9504C0731C662C3000352520 /* Build configuration list for PBXProject "V2RayX" */; compatibilityVersion = "Xcode 3.2"; developmentRegion = English; hasScannedForEncodings = 0; knownRegions = ( en, Base, ); mainGroup = 9504C06F1C662C3000352520; productRefGroup = 9504C0791C662C3000352520 /* Products */; projectDirPath = ""; projectRoot = ""; targets = ( 9504C0771C662C3000352520 /* V2RayX */, 9504C0C51C662DB400352520 /* v2rayx_sysconf */, 9D7DFE501EBEC947001FECBD /* jsonplist */, ); }; /* End PBXProject section */ /* Begin PBXResourcesBuildPhase section */ 9504C0761C662C3000352520 /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( 9D5EAC151FDCD70300C14B46 /* geoip.dat in Resources */, 9D5EAC161FDCD70300C14B46 /* geosite.dat in Resources */, 9D3CEE6F209E070F0077CCFE /* AdvancedWindow.xib in Resources */, 9D5EAC171FDCD70300C14B46 /* v2ctl in Resources */, 9D5EAC181FDCD70300C14B46 /* v2ray in Resources */, 9DB4FE951F205BEB00CCEE5F /* config-sample.plist in Resources */, 95E524CB1C674CC80008BB12 /* simple.pac in Resources */, 9504C0D11C66373400352520 /* install_helper.sh in Resources */, 9504C0CF1C662DE300352520 /* v2rayx_sysconf in Resources */, 9DA4A84120C14178000FF35D /* tcp_http_header_example.txt in Resources */, 9504C0821C662C3000352520 /* Assets.xcassets in Resources */, 9D7109611E0F43BD008A6362 /* Credits.rtf in Resources */, 9504C0851C662C3000352520 /* MainMenu.xib in Resources */, 9565E28B1DB25C010082658C /* TransportWindow.xib in Resources */, 9504C08D1C662C9100352520 /* ConfigWindow.xib in Resources */, 9D24863421CD9EC100C529AB /* config-sample_new.plist in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ 953B60541DB3E31D00D40654 /* Run Script */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); name = "Run Script"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "\"$SRCROOT\"/V2RayX/dlcore.sh\n"; }; 9DB94D77209D273A0001E9DD /* Run Script */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); name = "Run Script"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; shellScript = "buildNumber=$(/usr/libexec/PlistBuddy -c \"Print CFBundleVersion\" \"$INFOPLIST_FILE\")\nbuildNumber=$(($buildNumber + 1))\n/usr/libexec/PlistBuddy -c \"Set :CFBundleVersion $buildNumber\" \"$INFOPLIST_FILE\"\n"; }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ 9504C0741C662C3000352520 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( 9DDC059621CA8EAD00C6C2D7 /* utilities.m in Sources */, 9504C0901C662CBF00352520 /* ConfigWindowController.m in Sources */, 9577E1B81C6B065E00093BD3 /* GCDWebServerFileRequest.m in Sources */, 9577E1BE1C6B065E00093BD3 /* GCDWebServerStreamedResponse.m in Sources */, 9DDC059121CA8CFF00C6C2D7 /* TransportWindowController.m in Sources */, 9504C0801C662C3000352520 /* main.m in Sources */, 9577E1BB1C6B065E00093BD3 /* GCDWebServerDataResponse.m in Sources */, 9577E1BA1C6B065E00093BD3 /* GCDWebServerURLEncodedFormRequest.m in Sources */, 9577E1B71C6B065E00093BD3 /* GCDWebServerDataRequest.m in Sources */, 9577E1BC1C6B065E00093BD3 /* GCDWebServerErrorResponse.m in Sources */, 9577E1BD1C6B065E00093BD3 /* GCDWebServerFileResponse.m in Sources */, 9DBF54CF221615AD00B61D55 /* NSData+AES256Encryption.m in Sources */, 9DEB294D21CB64CF0052D2BB /* AdvancedWindowController.m in Sources */, 9577E1B31C6B065E00093BD3 /* GCDWebServerConnection.m in Sources */, 9504C07D1C662C3000352520 /* AppDelegate.m in Sources */, 9577E1B51C6B065E00093BD3 /* GCDWebServerRequest.m in Sources */, 9577E1B91C6B065E00093BD3 /* GCDWebServerMultiPartFormRequest.m in Sources */, 9577E1B61C6B065E00093BD3 /* GCDWebServerResponse.m in Sources */, 9577E1B21C6B065E00093BD3 /* GCDWebServer.m in Sources */, 9D71D61721D06006007DA052 /* ConfigImporter.m in Sources */, 9504C0D41C66511B00352520 /* ServerProfile.m in Sources */, 9577E1B41C6B065E00093BD3 /* GCDWebServerFunctions.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; 9504C0C21C662DB400352520 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( 9504C0C91C662DB500352520 /* main.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; 9D7DFE4D1EBEC947001FECBD /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( 9D7DFE541EBEC947001FECBD /* main.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ /* Begin PBXTargetDependency section */ 9504C0CE1C662DC500352520 /* PBXTargetDependency */ = { isa = PBXTargetDependency; target = 9504C0C51C662DB400352520 /* v2rayx_sysconf */; targetProxy = 9504C0CD1C662DC500352520 /* PBXContainerItemProxy */; }; /* End PBXTargetDependency section */ /* Begin PBXVariantGroup section */ 9504C0831C662C3000352520 /* MainMenu.xib */ = { isa = PBXVariantGroup; children = ( 9504C0841C662C3000352520 /* Base */, ); name = MainMenu.xib; sourceTree = ""; }; /* End PBXVariantGroup section */ /* Begin XCBuildConfiguration section */ 9504C0871C662C3000352520 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; CODE_SIGN_IDENTITY = "-"; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = dwarf; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_DYNAMIC_NO_PIC = NO; GCC_NO_COMMON_BLOCKS = YES; GCC_OPTIMIZATION_LEVEL = 0; GCC_PREPROCESSOR_DEFINITIONS = ( "DEBUG=1", "$(inherited)", ); GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; MACOSX_DEPLOYMENT_TARGET = 10.12; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = macosx; }; name = Debug; }; 9504C0881C662C3000352520 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; CLANG_WARN_STRICT_PROTOTYPES = YES; CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; CODE_SIGN_IDENTITY = "-"; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; MACOSX_DEPLOYMENT_TARGET = 10.12; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = macosx; }; name = Release; }; 9504C08A1C662C3000352520 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; COMBINE_HIDPI_IMAGES = YES; INFOPLIST_FILE = V2RayX/Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = cenmrev.V2RayX; PRODUCT_NAME = "$(TARGET_NAME)"; }; name = Debug; }; 9504C08B1C662C3000352520 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; COMBINE_HIDPI_IMAGES = YES; INFOPLIST_FILE = V2RayX/Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = cenmrev.V2RayX; PRODUCT_NAME = "$(TARGET_NAME)"; }; name = Release; }; 9504C0CB1C662DB500352520 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { PRODUCT_NAME = "$(TARGET_NAME)"; }; name = Debug; }; 9504C0CC1C662DB500352520 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { PRODUCT_NAME = "$(TARGET_NAME)"; }; name = Release; }; 9D7DFE551EBEC947001FECBD /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { CLANG_ANALYZER_NONNULL = YES; CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; MACOSX_DEPLOYMENT_TARGET = 10.12; PRODUCT_NAME = "$(TARGET_NAME)"; }; name = Debug; }; 9D7DFE561EBEC947001FECBD /* Release */ = { isa = XCBuildConfiguration; buildSettings = { CLANG_ANALYZER_NONNULL = YES; CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; MACOSX_DEPLOYMENT_TARGET = 10.12; PRODUCT_NAME = "$(TARGET_NAME)"; }; name = Release; }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ 9504C0731C662C3000352520 /* Build configuration list for PBXProject "V2RayX" */ = { isa = XCConfigurationList; buildConfigurations = ( 9504C0871C662C3000352520 /* Debug */, 9504C0881C662C3000352520 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; 9504C0891C662C3000352520 /* Build configuration list for PBXNativeTarget "V2RayX" */ = { isa = XCConfigurationList; buildConfigurations = ( 9504C08A1C662C3000352520 /* Debug */, 9504C08B1C662C3000352520 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; 9504C0CA1C662DB500352520 /* Build configuration list for PBXNativeTarget "v2rayx_sysconf" */ = { isa = XCConfigurationList; buildConfigurations = ( 9504C0CB1C662DB500352520 /* Debug */, 9504C0CC1C662DB500352520 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; 9D7DFE571EBEC947001FECBD /* Build configuration list for PBXNativeTarget "jsonplist" */ = { isa = XCConfigurationList; buildConfigurations = ( 9D7DFE551EBEC947001FECBD /* Debug */, 9D7DFE561EBEC947001FECBD /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; /* End XCConfigurationList section */ }; rootObject = 9504C0701C662C3000352520 /* Project object */; } ================================================ FILE: compilefromsource.sh ================================================ #!/bin/sh # compilefromsource.sh # V2RayX # # Created by Cenmrev on 10/15/16. # Copyright © 2016 Cenmrev. All rights reserved. # http://apple.stackexchange.com/questions/50844/how-to-move-files-to-trash-from-command-line function moveToTrash () { local path for path in "$@"; do # ignore any arguments if [[ "$path" = -* ]]; then : else # remove trailing slash local mindtrailingslash=${path%/} # remove preceding directory path local dst=${mindtrailingslash##*/} # append the time if necessary while [ -e ~/.Trash/"$dst" ]; do dst="`expr "$dst" : '\(.*\)\.[^.]*'` `date +%H-%M-%S`.`expr "$dst" : '.*\.\([^.]*\)'`" done mv "$path" ~/.Trash/"$dst" fi done } RED='\033[0;31m' GREEN='\033[0;32m' BOLD='\033[1m' NORMAL='\033[0m' datetime=$(date "+%Y-%m-%dTIME%H%M%S") if [[ ! -f /Applications/Xcode.app/Contents/MacOS/Xcode ]]; then echo "${RED}Xcode is needed to build V2RayX, Please install Xcode from App Store!${NORMAL}" echo "${RED}编译 V2RayX 需要 Xcode.app,请从 App Store 里安装 Xcode.${NORMAL}" else echo "${BOLD}-- Downloading source code --${NORMAL}" echo "${BOLD}-- 正在下载源码 --${NORMAL}" git clone --recursive https://github.com/Cenmrev/V2RayX.git "V2RayX${datetime}" cd "V2RayX${datetime}" echo "${BOLD}-- Start building V2RayX --${NORMAL}" echo "${BOLD}-- 开始编译 V2RayX --${NORMAL}" xcodebuild -project V2RayX.xcodeproj -target V2RayX -configuration Release if [[ $? == 0 ]]; then echo "${GREEN}-- Build succeeded --${NORMAL}" echo "${GREEN}-- 编译成功 --${NORMAL}" echo "${BOLD}V2RayX.app: $(pwd)/build/Release/V2RayX.app${NORMAL}" else echo "${RED}-- Build failed --${NORMAL}" echo "${RED}-- 编译失败 --${NORMAL}" fi fi ================================================ FILE: jsonplist/main.m ================================================ // // main.m // jsonplist // // Copyright © 2017 Project V2Ray. All rights reserved. // #import int main(int argc, const char * argv[]) { @autoreleasepool { if (argc < 2) { printf("Please provide at least one input file!\n"); return 1; } NSString* imputFile = [NSString stringWithFormat:@"%s", argv[1]]; NSInteger length = [imputFile length]; if ([[[imputFile substringFromIndex:length - 4] lowercaseString] isEqualToString:@"json"]) { NSDictionary* dict = [NSJSONSerialization JSONObjectWithData: [NSData dataWithContentsOfFile:imputFile] options:NSJSONReadingMutableLeaves error:nil]; NSString* targetFile = [[imputFile substringToIndex:length - 4] stringByAppendingString:@"plist"]; [dict writeToFile:targetFile atomically:NO]; printf("%s\n", [targetFile cStringUsingEncoding:NSUTF8StringEncoding]); return 0; } else if ([[[imputFile substringFromIndex:length - 5] lowercaseString] isEqualToString:@"plist"]) { NSDictionary* dict = [[NSDictionary alloc] initWithContentsOfFile:imputFile]; NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil]; NSString* targetFile = [[imputFile substringToIndex:length - 5] stringByAppendingString:@".plist"]; [jsonData writeToFile:targetFile atomically:NO]; printf("%s\n", [targetFile cStringUsingEncoding:NSUTF8StringEncoding]); return 0; } else { printf("Only json and plist are supported!\n"); return 1; } } return 0; } ================================================ FILE: prepare_zip.sh ================================================ isbeta=$(git describe --abbrev=0 --tags | grep beta) if [[ "$isbeta" != "" ]] then xcodebuild -project V2RayX.xcodeproj -target V2RayX -configuration Debug -s cd build/Debug/ else cd build/Release/ fi zip -r V2RayX.app.zip V2RayX.app cd ../.. ================================================ FILE: v2rayx_sysconf/main.m ================================================ // // main.m // v2rayx_sysconf // // Copyright © 2016年 Cenmrev. All rights reserved. // #import #import #import "sysconf_version.h" #define INFO "v2rayx_sysconf\n the helper tool for V2RayX, modified from clowwindy's shadowsocks_sysconf.\nusage: v2rayx_sysconf [options]\noff\t turn off proxy\nauto\t auto proxy change\nglobal port \t global proxy at the specified port number\n" int main(int argc, const char * argv[]) { if (argc < 2 || argc >4) { printf(INFO); return 1; } @autoreleasepool { NSString *mode = [NSString stringWithUTF8String:argv[1]]; NSSet *support_args = [NSSet setWithObjects:@"off", @"auto", @"global", @"save", @"restore", @"-v", nil]; if (![support_args containsObject:mode]) { printf(INFO); return 1; } if ([mode isEqualToString:@"-v"]) { printf("%s", [VERSION UTF8String]); return 0; } static AuthorizationRef authRef; static AuthorizationFlags authFlags; authFlags = kAuthorizationFlagDefaults | kAuthorizationFlagExtendRights | kAuthorizationFlagInteractionAllowed | kAuthorizationFlagPreAuthorize; OSStatus authErr = AuthorizationCreate(nil, kAuthorizationEmptyEnvironment, authFlags, &authRef); if (authErr != noErr) { authRef = nil; } else { if (authRef == NULL) { NSLog(@"No authorization has been granted to modify network configuration"); return 1; } SCPreferencesRef prefRef = SCPreferencesCreateWithAuthorization(nil, CFSTR("V2RayX"), nil, authRef); NSDictionary *sets = (__bridge NSDictionary *)SCPreferencesGetValue(prefRef, kSCPrefNetworkServices); NSDictionary* originalSets; if ([mode isEqualToString:@"save"]) { [sets writeToURL:[NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/Library/Application Support/V2RayX/system_proxy_backup.plist",NSHomeDirectory()]] atomically:NO]; return 0; } // 遍历系统中的网络设备列表,设置 AirPort 和 Ethernet 的代理 if([mode isEqualToString:@"restore"]) { originalSets = [NSDictionary dictionaryWithContentsOfURL:[NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/Library/Application Support/V2RayX/system_proxy_backup.plist",NSHomeDirectory()]]]; } for (NSString *key in [sets allKeys]) { NSMutableDictionary *dict = [sets objectForKey:key]; NSString *hardware = [dict valueForKeyPath:@"Interface.Hardware"]; // NSLog(@"%@", hardware); if ([hardware isEqualToString:@"AirPort"] || [hardware isEqualToString:@"Wi-Fi"] || [hardware isEqualToString:@"Ethernet"]) { NSMutableDictionary *proxies = [sets[key][@"Proxies"] mutableCopy]; [proxies setObject:[NSNumber numberWithInt:0] forKey:(NSString *)kCFNetworkProxiesHTTPEnable]; [proxies setObject:[NSNumber numberWithInt:0] forKey:(NSString *)kCFNetworkProxiesHTTPSEnable]; [proxies setObject:[NSNumber numberWithInt:0] forKey:(NSString *)kCFNetworkProxiesProxyAutoConfigEnable]; [proxies setObject:[NSNumber numberWithInt:0] forKey:(NSString *)kCFNetworkProxiesSOCKSEnable]; if ([mode isEqualToString:@"restore"]) { if ([originalSets objectForKey:key]){ proxies = originalSets[key][@"Proxies"]; } } if ([mode isEqualToString:@"auto"]) { [proxies setObject:@"http://127.0.0.1:8070/proxy.pac" forKey:(NSString *)kCFNetworkProxiesProxyAutoConfigURLString]; [proxies setObject:[NSNumber numberWithInt:1] forKey:(NSString *)kCFNetworkProxiesProxyAutoConfigEnable]; } else if ([mode isEqualToString:@"global"]) { int localPort = 0; int httpPort = 0; if (sscanf (argv[2], "%i", &localPort)!=1 || localPort > 65535 || localPort < 0) { printf ("error - not a valid port number"); return 1; } if (sscanf (argv[3], "%i", &httpPort)!=1 || httpPort > 65535 || httpPort < 0) { printf ("error - not a valid port number"); return 1; } NSLog(@"in helper %d %d", localPort, httpPort); if (localPort > 0) { [proxies setObject:@"127.0.0.1" forKey:(NSString *) kCFNetworkProxiesSOCKSProxy]; [proxies setObject:[NSNumber numberWithInt:localPort] forKey:(NSString*) kCFNetworkProxiesSOCKSPort]; [proxies setObject:[NSNumber numberWithInt:1] forKey:(NSString*) kCFNetworkProxiesSOCKSEnable]; } if (httpPort > 0) { [proxies setObject:@"127.0.0.1" forKey:(NSString *) kCFNetworkProxiesHTTPProxy]; [proxies setObject:@"127.0.0.1" forKey:(NSString *) kCFNetworkProxiesHTTPSProxy]; [proxies setObject:[NSNumber numberWithInt:httpPort] forKey:(NSString*) kCFNetworkProxiesHTTPPort]; [proxies setObject:[NSNumber numberWithInt:httpPort] forKey:(NSString*) kCFNetworkProxiesHTTPSPort]; [proxies setObject:[NSNumber numberWithInt:1] forKey:(NSString*) kCFNetworkProxiesHTTPEnable]; [proxies setObject:[NSNumber numberWithInt:1] forKey:(NSString*) kCFNetworkProxiesHTTPSEnable]; } } SCPreferencesPathSetValue(prefRef, (__bridge CFStringRef)[NSString stringWithFormat:@"/%@/%@/%@", kSCPrefNetworkServices, key, kSCEntNetProxies], (__bridge CFDictionaryRef)proxies); } } SCPreferencesCommitChanges(prefRef); SCPreferencesApplyChanges(prefRef); SCPreferencesSynchronize(prefRef); } printf("proxy set to %s\n", [mode UTF8String]); } return 0; } ================================================ FILE: v2rayx_sysconf/sysconf_version.h ================================================ // // sysconf_version.h // V2RayX // // #ifndef sysconf_version_h #define sysconf_version_h #define VERSION @"v2rayx_sysconf 1.4.0" #endif /* sysconf_version_h */