Compare commits

...
52 Commits
Author SHA1 Message Date
Cameron Gutman f3a06e5379 Version 2.1 2018-11-20 18:10:38 -08:00
Cameron Gutman c7565256b5 Add support for PCP on the first hop 2018-11-20 18:09:28 -08:00
Cameron Gutman 5840e39e94 Improve message box text 2018-11-20 17:33:34 -08:00
Cameron Gutman 2ce09f5fea Assume that NAT-PMP rules are present if we found a NAT-PMP gateway 2018-11-20 17:30:11 -08:00
Cameron Gutman de806ad57e Add simple installer UI and license 2018-11-20 17:14:21 -08:00
Cameron Gutman 3145d34381 Print computer name when looking for mappings 2018-11-20 17:12:30 -08:00
Cameron Gutman c6837c95f1 Remove IPv6 UPnP code from MISS 2018-11-20 17:12:13 -08:00
Cameron Gutman 23ef57c20f Remove echo port from WOL list to avoid possible reflection from internal network hosts 2018-11-18 10:58:58 -08:00
Cameron Gutman 56a0b2f2ad Update README.md 2018-11-10 14:36:42 -08:00
Cameron Gutman 8875db4bd5 Update README.md 2018-11-10 14:14:25 -08:00
Cameron Gutman d2ab2c1180 Update README.md 2018-11-10 14:12:42 -08:00
Cameron Gutman b496b90888 Version 2.0 2018-11-10 00:27:45 -08:00
Cameron Gutman e7b5b07c4a Several minor bugfixes from final pre-release testing 2018-11-10 00:21:01 -08:00
Cameron Gutman 732b430da8 Implement best-effort forwarding for Wake-on-LAN 2018-11-09 17:06:31 -08:00
Cameron Gutman 5aea5aedab Ensure IPv6 PCP requests come from the correct address by explicitly binding 2018-11-08 19:46:43 -08:00
Cameron Gutman 5325a57e20 Improve failure messages for double NAT and NAT reflection failure 2018-11-08 19:31:52 -08:00
Cameron Gutman 92eeadadca Use PCP for mapping on CGNs 2018-11-08 19:19:18 -08:00
Cameron Gutman e7e37b8dfb Use a per-server PCP nonce to fix unmapping 2018-11-08 18:09:27 -08:00
Cameron Gutman 3906de1a3a Initial PCP implementation (not fully tested) 2018-11-07 22:06:40 -08:00
Cameron Gutman c47014887a Avoid making duplicate NAT-PMP requests to a UPnP gateway that was disconnected 2018-11-07 21:13:27 -08:00
Cameron Gutman 9dd169ba02 Fix memory leak if UPnP gateway lacked IPv6FC support 2018-11-07 18:00:54 -08:00
Cameron Gutman 4ee5b9d28a Fix handling of malformed SSDP responses 2018-11-07 17:55:11 -08:00
Cameron Gutman 176a1762d6 Allow deletion of upstream mappings if we can guarantee they are ours 2018-11-07 17:44:49 -08:00
Cameron Gutman 2ba42e6dd5 Handle large SSDP responses better 2018-11-07 17:35:46 -08:00
Cameron Gutman 852ee8df8d Fix socket leak in getUPnPDevicesByAddress() 2018-11-07 17:30:18 -08:00
Cameron Gutman 1b3fef5408 Fix RFC 6598 netmask for CGN 2018-11-07 17:28:33 -08:00
Cameron Gutman 1137825a4f Add the ability to punch through multiple NATs in some situations 2018-11-06 21:57:17 -08:00
Cameron Gutman c964830213 Move IPv6 FW check to the correct location 2018-11-06 20:39:59 -08:00
Cameron Gutman 1b8f15e259 Wait for the NAT-PMP response when deleting a conflicting entry 2018-11-06 20:24:45 -08:00
Cameron Gutman d379a4ee74 Don't hardcode the testing IP address 2018-11-06 20:13:47 -08:00
Cameron Gutman 1c9ecbfb78 Add traceroute code for experimental double NAT handling 2018-11-05 21:38:36 -08:00
Cameron Gutman 2899843900 Avoid using IPv6 FC if no control URL was present 2018-11-05 19:43:50 -08:00
Cameron Gutman 81ca65d7d4 Rewrite STUN code based on moonlight-common-c and with TCP+UDP support 2018-11-05 18:55:59 -08:00
Cameron Gutman e62ed6ccc5 Try deleting conflicting UPnP mappings 2018-11-05 17:51:37 -08:00
Cameron Gutman 774878ed17 Per RFC 6886, we should set publicport to 0 when deleting a NAT-PMP port mapping 2018-10-23 21:50:33 -07:00
Cameron Gutman aeb288b62b Version 1.3 2018-10-23 17:38:06 -07:00
Cameron Gutman d9320bed7d Print a version header on logs and console output 2018-10-23 17:36:48 -07:00
Cameron Gutman e8c39d1919 Print a message when we discover no UPnP devices at all 2018-10-23 17:13:09 -07:00
Cameron Gutman 1efebca1bd Fix displaying 2 dialogs when we detect a Double NAT 2018-10-23 17:12:47 -07:00
Cameron Gutman 222ed5a568 Catch bogus private port values returned for NAT-PMP conflict 2018-10-23 17:11:55 -07:00
Cameron Gutman 5da85a1fb2 Fix malformed UPnP lease duration 2018-10-23 17:11:05 -07:00
Cameron Gutman 83c4413926 Remove port forwarding entries when MISS is stopped 2018-10-22 09:33:18 -07:00
Cameron Gutman 15d60ed10a Offer to show the troubleshooting log for terminal warnings too 2018-10-21 23:45:22 -07:00
Cameron Gutman f1738fc11e Fix a misleading message if GameStream has never been enabled 2018-10-21 21:41:36 -07:00
Cameron Gutman 0867814ae8 Fix double NAT port test 2018-10-21 21:32:30 -07:00
Cameron Gutman 541a0bf9d9 Version 1.2 2018-10-21 21:23:02 -07:00
Cameron Gutman 632bba6da8 Minor cosmetic changes to wording and warnings 2018-10-21 21:17:25 -07:00
Cameron Gutman 0ec33223f4 Rename mist.log to mis-test.log 2018-10-21 21:04:29 -07:00
Cameron Gutman 45b624c203 Improve reliability with NAT reflection disabled, UPnP IGD reporting disconnected, double-NATs, and CGNs 2018-10-21 21:04:08 -07:00
Cameron Gutman 7bc806edb4 Increase polling rate to once per 2 minutes to ensure rules are updated quickly after a router reboot 2018-10-21 20:33:18 -07:00
Cameron Gutman afe60bfe30 Fix handling of IGD returning empty IP address and success status 2018-10-21 19:27:55 -07:00
Cameron Gutman ac4e0101f2 Fix brown-paper-bag comment mistake in subnet calculation 2018-10-21 19:25:11 -07:00
16 changed files with 1459 additions and 365 deletions
+12 -2
View File
@@ -1,2 +1,12 @@
# Internet-Streaming-Helper
Automatically configure and troubleshoot your router for using Moonlight over the Internet
# Moonlight Internet Streaming Helper
* Enable Moonlight streaming from your PC over the Internet with no configuration required
* Troubleshoot streaming issues with the included testing tool
# How to Use
1. Install the MSI package from the [GitHub Releases Page](https://github.com/moonlight-stream/Internet-Streaming-Helper/releases) on your host gaming PC.
2. If neccessary, run the Moonlight Internet Streaming Tester installed with this software.
# Technical Features
- Supports all major port forwarding protocols (UPnP, NAT-PMP, and PCP) for the best possible router compatibility
- Supports successful forwarding in double-NAT environments by configuring port mappings on all NATs found on the way to the Internet
- Supports forwarding on Carrier-Grade NATs (CGNs) by directly using PCP when the ISP doesn't implement UPnP-PCP interoperability
+3
View File
@@ -8,6 +8,9 @@
<MajorUpgrade DowngradeErrorMessage="A newer version of [ProductName] is already installed." />
<MediaTemplate EmbedCab="yes" />
<WixVariable Id="WixUILicenseRtf" Value="license.rtf" />
<UIRef Id="WixUI_Minimal" />
<Feature Id="ProductFeature" Title="MISHSetup" Level="1">
<ComponentGroupRef Id="ProductComponents" />
</Feature>
+124
View File
@@ -0,0 +1,124 @@
{\rtf1\ansi\deff0\nouicompat{\fonttbl{\f0\fswiss Helvetica;}{\f1\fswiss\fcharset0 Helvetica;}}
{\colortbl ;\red0\green0\blue255;}
{\*\generator Riched20 10.0.17713}\viewkind4\uc1
\pard\sa180\b\f0\fs28\lang9 GNU GENERAL PUBLIC LICENSE\par
\b0\fs24 Version 3, 29 June 2007\par
Copyright \f1\'a9 2007 Free Software Foundation, Inc. <{{\field{\*\fldinst{HYPERLINK "https://fsf.org/"}}{\fldrslt{https://fsf.org/\ul0\cf0}}}}\f1\fs24 >\par
\f0 Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.\par
\b\fs28 Preamble\par
\b0\fs24 The GNU General Public License is a free, copyleft license for software and other kinds of works.\par
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.\par
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.\par
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.\par
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.\par
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.\par
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.\par
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.\par
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.\par
The precise terms and conditions for copying, distribution and modification follow.\par
\b\fs28 TERMS AND CONDITIONS\par
\fs24 0. Definitions.\par
\b0\ldblquote This License\rdblquote refers to version 3 of the GNU General Public License.\par
\ldblquote Copyright\rdblquote also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.\par
\ldblquote The Program\rdblquote refers to any copyrightable work licensed under this License. Each licensee is addressed as \ldblquote you\rdblquote . \ldblquote Licensees\rdblquote and \ldblquote recipients\rdblquote may be individuals or organizations.\par
To \ldblquote modify\rdblquote 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 \ldblquote modified version\rdblquote of the earlier work or a work \ldblquote based on\rdblquote the earlier work.\par
A \ldblquote covered work\rdblquote means either the unmodified Program or a work based on the Program.\par
To \ldblquote propagate\rdblquote 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.\par
To \ldblquote convey\rdblquote 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.\par
An interactive user interface displays \ldblquote Appropriate Legal Notices\rdblquote 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.\par
\b 1. Source Code.\par
\b0 The \ldblquote source code\rdblquote for a work means the preferred form of the work for making modifications to it. \ldblquote Object code\rdblquote means any non-source form of a work.\par
A \ldblquote Standard Interface\rdblquote 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.\par
The \ldblquote System Libraries\rdblquote 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 \ldblquote Major Component\rdblquote , 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.\par
The \ldblquote Corresponding Source\rdblquote 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.\par
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.\par
The Corresponding Source for a work in source code form is that same work.\par
\b 2. Basic Permissions.\par
\b0 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.\par
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.\par
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.\par
\b 3. Protecting Users' Legal Rights From Anti-Circumvention Law.\par
\b0 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.\par
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.\par
\b 4. Conveying Verbatim Copies.\par
\b0 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.\par
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.\par
\b 5. Conveying Modified Source Versions.\par
\b0 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:\par
\pard\fi-360\li360\tx360\bullet\tab a) The work must carry prominent notices stating that you modified it, and giving a relevant date.\par
\bullet\tab 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 \ldblquote keep intact all notices\rdblquote .\par
\bullet\tab 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.\par
\pard\fi-360\li360\sa180\tx360\bullet\tab 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.\par
\pard\sa180 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 \ldblquote aggregate\rdblquote 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.\par
\b 6. Conveying Non-Source Forms.\par
\b0 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:\par
\pard\fi-360\li360\tx360\bullet\tab 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.\par
\bullet\tab 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.\par
\bullet\tab 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.\par
\bullet\tab 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.\par
\pard\fi-360\li360\sa180\tx360\bullet\tab 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.\par
\pard\sa180 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.\par
A \ldblquote User Product\rdblquote is either (1) a \ldblquote consumer product\rdblquote , 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, \ldblquote normally used\rdblquote 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.\par
\ldblquote Installation Information\rdblquote 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.\par
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).\par
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.\par
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.\par
\b 7. Additional Terms.\par
\b0\ldblquote Additional permissions\rdblquote 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.\par
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.\par
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:\par
\pard\fi-360\li360\tx360\bullet\tab a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or\par
\bullet\tab 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\par
\bullet\tab 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\par
\bullet\tab d) Limiting the use for publicity purposes of names of licensors or authors of the material; or\par
\bullet\tab e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or\par
\pard\fi-360\li360\sa180\tx360\bullet\tab 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.\par
\pard\sa180 All other non-permissive additional terms are considered \ldblquote further restrictions\rdblquote 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.\par
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.\par
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.\par
\b 8. Termination.\par
\b0 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).\par
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.\par
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.\par
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.\par
\b 9. Acceptance Not Required for Having Copies.\par
\b0 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.\par
\b 10. Automatic Licensing of Downstream Recipients.\par
\b0 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.\par
An \ldblquote entity transaction\rdblquote 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.\par
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.\par
\b 11. Patents.\par
\b0 A \ldblquote contributor\rdblquote 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 \ldblquote contributor version\rdblquote .\par
A contributor's \ldblquote essential patent claims\rdblquote 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, \ldblquote control\rdblquote includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.\par
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.\par
In the following three paragraphs, a \ldblquote patent license\rdblquote 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 \ldblquote grant\rdblquote such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.\par
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. \ldblquote Knowingly relying\rdblquote 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.\par
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.\par
A patent license is \ldblquote discriminatory\rdblquote 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.\par
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.\par
\b 12. No Surrender of Others' Freedom.\par
\b0 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.\par
\b 13. Use with the GNU Affero General Public License.\par
\b0 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.\par
\b 14. Revised Versions of this License.\par
\b0 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.\par
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License \ldblquote or any later version\rdblquote 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.\par
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.\par
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.\par
\b 15. Disclaimer of Warranty.\par
\b0 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 \ldblquote AS IS\rdblquote 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.\par
\b 16. Limitation of Liability.\par
\b0 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.\par
\b 17. Interpretation of Sections 15 and 16.\par
\b0 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.\b\fs28\par
}
+4
View File
@@ -44,6 +44,10 @@
<HintPath>$(WixExtDir)\WixFirewallExtension.dll</HintPath>
<Name>WixFirewallExtension</Name>
</WixExtension>
<WixExtension Include="WixUIExtension">
<HintPath>$(WixExtDir)\WixUIExtension.dll</HintPath>
<Name>WixUIExtension</Name>
</WixExtension>
</ItemGroup>
<Import Project="$(WixTargetsPath)" Condition=" '$(WixTargetsPath)' != '' " />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\WiX\v3.x\Wix.targets" Condition=" '$(WixTargetsPath)' == '' AND Exists('$(MSBuildExtensionsPath32)\Microsoft\WiX\v3.x\Wix.targets') " />
+369 -136
View File
@@ -1,4 +1,5 @@
#define _CRT_SECURE_NO_WARNINGS
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
@@ -11,6 +12,8 @@
#include <assert.h>
#include <stdlib.h>
#include "..\version.h"
#pragma comment(lib, "miniupnpc.lib")
#pragma comment(lib, "libnatpmp.lib")
#pragma comment(lib, "ws2_32.lib")
@@ -24,11 +27,15 @@
#define NATPMP_STATICLIB
#include <natpmp.h>
bool getHopsIP4(IN_ADDR* hopAddress, int* hopAddressCount);
struct UPNPDev* getUPnPDevicesByAddress(IN_ADDR address);
bool PCPMapPort(PSOCKADDR_STORAGE localAddr, int localAddrLen, PSOCKADDR_STORAGE pcpAddr, int pcpAddrLen, int proto, int port, bool enable, bool indefinite);
#define NL "\n"
#define STR(x) #x
#define SERVICE_NAME "MISS"
#define UPNP_SERVICE_NAME "Moonlight"
#define POLLING_DELAY_SEC 120
#define PORT_MAPPING_DURATION_SEC 3600
#define UPNP_DISCOVERY_DELAY_MS 5000
@@ -46,28 +53,9 @@ static struct port_entry {
{IPPROTO_UDP, 48010}
};
void UPnPCreatePinholeForPort(struct UPNPUrls* urls, struct IGDdatas* data, int proto, const char* myAddr, int port)
{
char uniqueId[8];
char protoStr[3];
char portStr[6];
static const int k_WolPorts[] = { 9 };
snprintf(portStr, sizeof(portStr), "%d", port);
snprintf(protoStr, sizeof(protoStr), "%d", proto);
printf("Creating UPnP IPv6 pinhole for %s %s -> %s...", protoStr, portStr, myAddr);
// Lease time is in seconds - 7200 = 2 hours
int err = UPNP_AddPinhole(urls->controlURL_6FC, data->IPv6FC.servicetype, "empty", portStr, myAddr, portStr, protoStr, "7200", uniqueId);
if (err == UPNPCOMMAND_SUCCESS) {
printf("OK" NL);
}
else {
printf("ERROR %d (%s)" NL, err, strupnperror(err));
}
}
bool UPnPMapPort(struct UPNPUrls* urls, struct IGDdatas* data, int proto, const char* myAddr, int port, bool enable)
bool UPnPMapPort(struct UPNPUrls* urls, struct IGDdatas* data, int proto, const char* myAddr, int port, bool enable, bool indefinite)
{
char intClient[16];
char intPort[6];
@@ -100,7 +88,7 @@ bool UPnPMapPort(struct UPNPUrls* urls, struct IGDdatas* data, int proto, const
return false;
}
printf("Checking for existing UPnP port mapping for %s %s -> %s...", protoStr, portStr, myAddr);
printf("Checking for existing UPnP port mapping for %s %s -> %s %s...", protoStr, portStr, myAddr, computerName);
int err = UPNP_GetSpecificPortMappingEntry(
urls->controlURL, data->first.servicetype, portStr, protoStr, nullptr,
intClient, intPort, desc, enabled, leaseDuration);
@@ -132,10 +120,27 @@ bool UPnPMapPort(struct UPNPUrls* urls, struct IGDdatas* data, int proto, const
}
}
else {
// UPnP IGDs won't let unauthenticated clients delete other conflicting port mappings
// for security reasons, so we have to give up in this case.
printf("CONFLICT: %s %s" NL, intClient, desc);
return false;
// Some UPnP IGDs won't let unauthenticated clients delete other conflicting port mappings
// for security reasons, but we will give it a try anyway. If GameStream is not enabled,
// we will leave the conflicting entry alone to avoid disturbing another PC's port forwarding
// (especially if we're double NATed).
if (enable) {
printf("Trying to delete conflicting UPnP mapping for %s %s -> %s...", protoStr, portStr, intClient);
err = UPNP_DeletePortMapping(urls->controlURL, data->first.servicetype, portStr, protoStr, nullptr);
if (err == UPNPCOMMAND_SUCCESS) {
printf("OK" NL);
}
else if (err == 606) {
printf("UNAUTHORIZED" NL);
return false;
}
else {
printf("ERROR %d" NL, err);
return false;
}
}
}
}
else {
@@ -148,11 +153,13 @@ bool UPnPMapPort(struct UPNPUrls* urls, struct IGDdatas* data, int proto, const
}
// Create or update the expiration time of an existing mapping
snprintf(leaseDuration, sizeof(leaseDuration), "%d",
indefinite ? 0 : PORT_MAPPING_DURATION_SEC);
printf("Updating UPnP port mapping for %s %s -> %s...", protoStr, portStr, myAddr);
err = UPNP_AddPortMapping(
urls->controlURL, data->first.servicetype, portStr,
portStr, myAddr, myDesc, protoStr, nullptr, STR(PORT_MAPPING_DURATION_SEC));
if (err == 725) { // OnlyPermanentLeasesSupported
portStr, myAddr, myDesc, protoStr, nullptr, leaseDuration);
if (err == 725 && !indefinite) { // OnlyPermanentLeasesSupported
err = UPNP_AddPortMapping(
urls->controlURL, data->first.servicetype, portStr,
portStr, myAddr, myDesc, protoStr, nullptr, "0");
@@ -168,7 +175,7 @@ bool UPnPMapPort(struct UPNPUrls* urls, struct IGDdatas* data, int proto, const
}
}
bool ResolveStableIP6Address(char* tmpAddr)
bool GetIP4OnLinkPrefixLength(char* lanAddressString, int* prefixLength)
{
union {
IP_ADAPTER_ADDRESSES addresses;
@@ -178,13 +185,13 @@ bool ResolveStableIP6Address(char* tmpAddr)
ULONG length;
PIP_ADAPTER_ADDRESSES currentAdapter;
PIP_ADAPTER_UNICAST_ADDRESS currentAddress;
in6_addr targetAddress;
in_addr targetAddress;
inet_pton(AF_INET6, tmpAddr, &targetAddress);
inet_pton(AF_INET, lanAddressString, &targetAddress);
// Get a list of all interfaces with IPv6 addresses on the system
// Get a list of all interfaces with IPv4 addresses on the system
length = sizeof(buffer);
error = GetAdaptersAddresses(AF_INET6,
error = GetAdaptersAddresses(AF_INET,
GAA_FLAG_SKIP_ANYCAST |
GAA_FLAG_SKIP_MULTICAST |
GAA_FLAG_SKIP_DNS_SERVER |
@@ -200,71 +207,37 @@ bool ResolveStableIP6Address(char* tmpAddr)
currentAdapter = &addresses;
currentAddress = nullptr;
while (currentAdapter != nullptr) {
// First, search for the adapter
currentAddress = currentAdapter->FirstUnicastAddress;
while (currentAddress != nullptr) {
assert(currentAddress->Address.lpSockaddr->sa_family == AF_INET6);
assert(currentAddress->Address.lpSockaddr->sa_family == AF_INET);
PSOCKADDR_IN6 currentAddrV6 = (PSOCKADDR_IN6)currentAddress->Address.lpSockaddr;
PSOCKADDR_IN currentAddrV4 = (PSOCKADDR_IN)currentAddress->Address.lpSockaddr;
if (RtlEqualMemory(&currentAddrV6->sin6_addr, &targetAddress, sizeof(targetAddress))) {
// Found interface with matching address
break;
if (RtlEqualMemory(&currentAddrV4->sin_addr, &targetAddress, sizeof(targetAddress))) {
*prefixLength = currentAddress->OnLinkPrefixLength;
return true;
}
currentAddress = currentAddress->Next;
}
if (currentAddress != nullptr) {
// Get out of the loop if we found the matching address
break;
}
currentAdapter = currentAdapter->Next;
}
if (currentAdapter == nullptr) {
printf("No adapter found with IPv6 address: %s" NL, tmpAddr);
return false;
}
// Now currentAdapter is the adapter we reached the IGD with. Find a suitable
// public address that we can use to create the pinhole.
currentAddress = currentAdapter->FirstUnicastAddress;
while (currentAddress != nullptr) {
assert(currentAddress->Address.lpSockaddr->sa_family == AF_INET6);
PSOCKADDR_IN6 currentAddrV6 = (PSOCKADDR_IN6)currentAddress->Address.lpSockaddr;
// Exclude temporary addresses and link-local addresses
if (currentAddress->SuffixOrigin != IpSuffixOriginRandom && currentAddrV6->sin6_scope_id == 0) {
break;
}
currentAddress = currentAddress->Next;
}
if (currentAddress == nullptr) {
printf("No suitable alternate address found for %s" NL, tmpAddr);
return false;
}
PSOCKADDR_IN6 currentAddrV6 = (PSOCKADDR_IN6)currentAddress->Address.lpSockaddr;
inet_ntop(AF_INET6, &currentAddrV6->sin6_addr, tmpAddr, 128);
return true;
printf("No adapter found with IPv4 address: %s" NL, lanAddressString);
return false;
}
bool UPnPHandleDeviceList(struct UPNPDev* list, bool ipv6, bool enable)
bool UPnPHandleDeviceList(struct UPNPDev* list, bool enable, char* lanAddrOverride, char* wanAddr)
{
struct UPNPUrls urls;
struct IGDdatas data;
char myAddr[128];
char wanAddr[128];
char localAddress[128];
char* portMappingInternalAddress;
int pinholeAllowed = false;
bool success = true;
int ret = UPNP_GetValidIGD(list, &urls, &data, myAddr, sizeof(myAddr));
int ret = UPNP_GetValidIGD(list, &urls, &data, localAddress, sizeof(localAddress));
if (ret == 0) {
printf("No UPnP device found!" NL);
return false;
@@ -288,40 +261,55 @@ bool UPnPHandleDeviceList(struct UPNPDev* list, bool ipv6, bool enable)
return false;
}
if (ipv6) {
// Convert what is likely a IPv6 temporary address into
// the stable IPv6 address for the same interface.
if (ResolveStableIP6Address(myAddr)) {
printf("Stable global IPv6 address is: %s" NL, myAddr);
int firewallEnabled;
ret = UPNP_GetFirewallStatus(urls.controlURL_6FC, data.IPv6FC.servicetype, &firewallEnabled, &pinholeAllowed);
if (ret == UPNPCOMMAND_SUCCESS) {
printf("UPnP IPv6 firewall control available. Firewall is %s, pinhole is %s" NL,
firewallEnabled ? "enabled" : "disabled",
pinholeAllowed ? "allowed" : "disallowed");
}
else {
printf("UPnP IPv6 firewall control is unavailable with error %d (%s)" NL, ret, strupnperror(ret));
pinholeAllowed = false;
}
}
ret = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, wanAddr);
if (ret == UPNPCOMMAND_SUCCESS) {
printf("UPnP IGD WAN address is: %s" NL, wanAddr);
}
else {
ret = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, wanAddr);
if (ret == UPNPCOMMAND_SUCCESS) {
printf("UPnP IGD WAN address is: %s" NL, wanAddr);
}
// Empty string
*wanAddr = 0;
}
// We may be mapping on behalf of another device
if (lanAddrOverride != nullptr) {
portMappingInternalAddress = lanAddrOverride;
}
else {
portMappingInternalAddress = localAddress;
}
for (int i = 0; i < ARRAYSIZE(k_Ports); i++) {
if (!ipv6) {
if (!UPnPMapPort(&urls, &data, k_Ports[i].proto, myAddr, k_Ports[i].port, enable)) {
success = false;
if (!UPnPMapPort(&urls, &data, k_Ports[i].proto, portMappingInternalAddress, k_Ports[i].port, enable, false)) {
success = false;
}
}
// Do a best-effort for IPv4 Wake-on-LAN broadcast mappings
for (int i = 0; i < ARRAYSIZE(k_WolPorts); i++) {
if (lanAddrOverride == nullptr) {
// Map the port to the broadcast address (may not work on all routers). This
// ensures delivery even after the ARP entry for this PC times out on the router.
int onLinkPrefixLen;
if (GetIP4OnLinkPrefixLength(localAddress, &onLinkPrefixLen)) {
int netmask = 0;
for (int j = 0; j < onLinkPrefixLen; j++) {
netmask |= (1 << j);
}
in_addr broadcastAddr;
broadcastAddr.S_un.S_addr = inet_addr(localAddress);
broadcastAddr.S_un.S_addr |= ~netmask;
char broadcastAddrStr[128];
inet_ntop(AF_INET, &broadcastAddr, broadcastAddrStr, sizeof(broadcastAddrStr));
UPnPMapPort(&urls, &data, IPPROTO_UDP, broadcastAddrStr, k_WolPorts[i], enable, true);
}
}
if (pinholeAllowed) {
UPnPCreatePinholeForPort(&urls, &data, k_Ports[i].proto, myAddr, k_Ports[i].port);
else {
// When we're mapping the WOL ports upstream of our router, we map directly to
// the port on the upstream address (likely our router's WAN interface).
UPnPMapPort(&urls, &data, IPPROTO_UDP, lanAddrOverride, k_WolPorts[i], enable, true);
}
}
@@ -329,7 +317,7 @@ bool UPnPHandleDeviceList(struct UPNPDev* list, bool ipv6, bool enable)
return success;
}
bool NATPMPMapPort(natpmp_t* natpmp, int proto, int port, bool enable)
bool NATPMPMapPort(natpmp_t* natpmp, int proto, int port, bool enable, bool indefinite)
{
int natPmpProto;
@@ -346,8 +334,20 @@ bool NATPMPMapPort(natpmp_t* natpmp, int proto, int port, bool enable)
return false;
}
int lifetime;
if (!enable) {
lifetime = 0;
}
else if (indefinite) {
lifetime = 604800; // 1 week
}
else {
lifetime = 3600;
}
printf("Updating NAT-PMP port mapping for %s %d...", proto == IPPROTO_TCP ? "TCP" : "UDP", port);
int err = sendnewportmappingrequest(natpmp, natPmpProto, port, port, enable ? PORT_MAPPING_DURATION_SEC : 0);
int err = sendnewportmappingrequest(natpmp, natPmpProto, port, enable ? port : 0, lifetime);
if (err < 0) {
printf("ERROR %d" NL, err);
return false;
@@ -384,10 +384,53 @@ bool NATPMPMapPort(natpmp_t* natpmp, int proto, int port, bool enable)
}
else if (response.pnu.newportmapping.mappedpublicport != port) {
printf("CONFLICT" NL);
// Some buggy routers (Untangle) will change the *internal* port when
// adjusting a port mapping request that collides. This is why we also
// pass privateport back from the response and not from the port we originally
// asked for. Warn in this case.
if (response.pnu.newportmapping.privateport != port) {
printf("Buggy router changed the internal port when handling NAT-PMP conflict! (%d -> %d)" NL,
port, response.pnu.newportmapping.privateport);
}
// It couldn't assign us the external port we requested and gave us an alternate external port.
// We can't use this alternate mapping, so immediately release it.
sendnewportmappingrequest(natpmp, natPmpProto, port, response.pnu.newportmapping.mappedpublicport, 0);
return false;
printf("Deleting unwanted NAT-PMP mapping for %s %d...", proto == IPPROTO_TCP ? "TCP" : "UDP", response.pnu.newportmapping.mappedpublicport);
err = sendnewportmappingrequest(natpmp, natPmpProto, response.pnu.newportmapping.privateport, 0, 0);
if (err < 0) {
printf("ERROR %d" NL, err);
return false;
}
else {
do {
fd_set fds;
struct timeval timeout;
FD_ZERO(&fds);
FD_SET(natpmp->s, &fds);
err = getnatpmprequesttimeout(natpmp, &timeout);
if (err != 0) {
assert(err == 0);
printf("WAIT FAILED: %d" NL, err);
return false;
}
select(0, &fds, nullptr, nullptr, &timeout);
err = readnatpmpresponseorretry(natpmp, &response);
} while (err == NATPMP_TRYAGAIN);
if (err == 0) {
printf("OK" NL);
return false;
}
else {
printf("FAILED %d" NL, err);
return false;
}
}
}
else {
printf("OK (%d seconds remaining)" NL, response.pnu.newportmapping.lifetime);
@@ -425,14 +468,19 @@ bool IsGameStreamEnabled()
}
}
void UpdatePortMappings(bool enable)
void UpdatePortMappingsForTarget(bool enable, char* targetAddressIP4, char* internalAddressIP4, char* upstreamAddressIP4)
{
natpmp_t natpmp;
bool tryNatPmp = true;
bool tryPcp = true;
char upstreamAddrNatPmp[128] = {};
char upstreamAddrUPnP[128] = {};
printf("Starting port mapping update..." NL);
printf("Starting port mapping update on %s to %s..." NL,
targetAddressIP4 ? targetAddressIP4 : "default gateway",
internalAddressIP4 ? internalAddressIP4 : "local machine");
int natPmpErr = initnatpmp(&natpmp, 0, 0);
int natPmpErr = initnatpmp(&natpmp, targetAddressIP4 ? 1 : 0, targetAddressIP4 ? inet_addr(targetAddressIP4) : 0);
if (natPmpErr != 0) {
printf("initnatpmp() failed: %d" NL, natPmpErr);
}
@@ -448,18 +496,27 @@ void UpdatePortMappings(bool enable)
{
int upnpErr;
struct UPNPDev* ipv4Devs = upnpDiscoverAll(UPNP_DISCOVERY_DELAY_MS, nullptr, nullptr, UPNP_LOCAL_PORT_ANY, 0, 2, &upnpErr);
struct UPNPDev* ipv4Devs;
if (targetAddressIP4 == nullptr) {
// If we have no target, use discovery to find the first hop
ipv4Devs = upnpDiscoverAll(UPNP_DISCOVERY_DELAY_MS, nullptr, nullptr, UPNP_LOCAL_PORT_ANY, 0, 2, &upnpErr);
printf("UPnP IPv4 IGD discovery completed with error code: %d" NL, upnpErr);
}
else {
// We have a specified target, so do discovery against that directly (may be outside our subnet in case of double-NAT)
struct in_addr addr;
addr.S_un.S_addr = inet_addr(targetAddressIP4);
ipv4Devs = getUPnPDevicesByAddress(addr);
}
printf("UPnP IPv4 IGD discovery completed with error code: %d" NL, upnpErr);
// Use the delay of upnpDiscoverAll() to also allow the NAT-PMP endpoint time to respond
// Use the delay of discovery to also allow the NAT-PMP endpoint time to respond
if (natPmpErr >= 0) {
natpmpresp_t response;
natPmpErr = readnatpmpresponseorretry(&natpmp, &response);
if (natPmpErr == 0) {
char addrStr[64];
inet_ntop(AF_INET, &response.pnu.publicaddress.addr, addrStr, sizeof(addrStr));
printf("NAT-PMP WAN address is: %s" NL, addrStr);
inet_ntop(AF_INET, &response.pnu.publicaddress.addr, upstreamAddrNatPmp, sizeof(upstreamAddrNatPmp));
printf("NAT-PMP upstream address is: %s" NL, upstreamAddrNatPmp);
}
else {
printf("NAT-PMP public address request failed: %d" NL, natPmpErr);
@@ -468,12 +525,13 @@ void UpdatePortMappings(bool enable)
}
// Don't try NAT-PMP if UPnP succeeds
if (UPnPHandleDeviceList(ipv4Devs, false, enable)) {
if (UPnPHandleDeviceList(ipv4Devs, enable, internalAddressIP4, upstreamAddrUPnP)) {
printf("UPnP IPv4 port mapping successful" NL);
if (enable) {
// We still want to try NAT-PMP if we're removing
// rules to ensure any NAT-PMP rules get cleaned up
tryNatPmp = false;
tryPcp = false;
}
}
@@ -482,36 +540,200 @@ void UpdatePortMappings(bool enable)
fflush(stdout);
{
int upnpErr;
struct UPNPDev* ipv6Devs = upnpDiscoverAll(UPNP_DISCOVERY_DELAY_MS, nullptr, nullptr, UPNP_LOCAL_PORT_ANY, 1, 2, &upnpErr);
printf("UPnP IPv6 IGD discovery completed with error code: %d" NL, upnpErr);
// Ignore whether IPv6 succeeded when decided to use NAT-PMP
UPnPHandleDeviceList(ipv6Devs, true, enable);
freeUPNPDevlist(ipv6Devs);
}
fflush(stdout);
if (natPmpErr == 0) {
// NAT-PMP has no description field or other token that we can use to determine
// if we created the rules we'd be deleting. Since we don't have that, we can't
// safely remove mappings that could be shared by another machine behind a double NAT.
if (!enable && targetAddressIP4 != nullptr) {
printf("Not removing upstream NAT-PMP mappings on non-default gateway device" NL);
tryNatPmp = false;
}
// Don't try with NAT-PMP if the UPnP attempt for the same gateway failed due to being
// disconnected or some other error. This will avoid overwriting UPnP rules on a disconnected IGD
// with duplicate NAT-PMP rules. We want to allow deletion of NAT-PMP rules in any case though.
if (enable && !strcmp(upstreamAddrNatPmp, upstreamAddrUPnP)) {
printf("Not attempting to use NAT-PMP/PCP to talk to the same UPnP gateway\n");
tryNatPmp = false;
// We have both UPnP and NAT-PMP on the same upstream gateway, so let's
// assume PCP is on the same box too.
tryPcp = false;
}
if (tryNatPmp) {
bool success = true;
for (int i = 0; i < ARRAYSIZE(k_Ports); i++) {
if (!NATPMPMapPort(&natpmp, k_Ports[i].proto, k_Ports[i].port, enable)) {
if (!NATPMPMapPort(&natpmp, k_Ports[i].proto, k_Ports[i].port, enable, false)) {
success = false;
}
}
// We can only map ports for the non-default gateway case because
// it will use our LAN address as the internal client address, which
// doesn't work (needs to be broadcast) for the last hop.
if (targetAddressIP4 != nullptr) {
// Best effort, don't care if we fail for WOL
for (int i = 0; i < ARRAYSIZE(k_WolPorts); i++) {
// Indefinite mapping since we may not be awake to refresh it
NATPMPMapPort(&natpmp, IPPROTO_UDP, k_WolPorts[i], enable, true);
}
}
if (success) {
printf("NAT-PMP IPv4 port mapping successful" NL);
// Always try all possibilities when disabling to ensure
// we completely clean up
if (enable) {
tryPcp = false;
}
}
}
closenatpmp(&natpmp);
}
// Try PCP for IPv4 if UPnP and NAT-PMP have both failed. This may be the case for CGN that only supports PCP.
if (tryPcp) {
SOCKADDR_IN targetAddr = {};
SOCKADDR_IN internalAddr = {};
targetAddr.sin_family = AF_INET;
internalAddr.sin_family = AF_INET;
if (targetAddressIP4 != nullptr && internalAddressIP4 != nullptr) {
targetAddr.sin_addr.S_un.S_addr = inet_addr(targetAddressIP4);
internalAddr.sin_addr.S_un.S_addr = inet_addr(internalAddressIP4);
}
else {
MIB_IPFORWARDROW route;
DWORD error = GetBestRoute(0, 0, &route);
if (error == NO_ERROR) {
targetAddr.sin_addr.S_un.S_addr = route.dwForwardNextHop;
}
else {
printf("GetBestRoute() failed: %d" NL, error);
goto Exit;
}
}
bool success = true;
for (int i = 0; i < ARRAYSIZE(k_Ports); i++) {
if (!PCPMapPort((PSOCKADDR_STORAGE)&internalAddr, sizeof(internalAddr),
(PSOCKADDR_STORAGE)&targetAddr, sizeof(targetAddr),
k_Ports[i].proto, k_Ports[i].port, enable, false)) {
success = false;
}
}
// We can only map ports for the non-default gateway case because
// it will use our internal address as the internal client address, which
// doesn't work (needs to be broadcast) for the last hop.
if (internalAddressIP4 != nullptr) {
// Best effort, don't care if we fail for WOL
for (int i = 0; i < ARRAYSIZE(k_WolPorts); i++) {
// Indefinite mapping since we may not be awake to refresh it
PCPMapPort((PSOCKADDR_STORAGE)&internalAddr, sizeof(internalAddr),
(PSOCKADDR_STORAGE)&targetAddr, sizeof(targetAddr),
IPPROTO_UDP, k_WolPorts[i], enable, true);
}
}
if (success) {
printf("PCP IPv4 port mapping successful" NL);
}
}
Exit:
// Write this at the end to avoid clobbering an input parameter
if (upstreamAddrNatPmp[0] != 0 && inet_addr(upstreamAddrNatPmp) != 0) {
printf("Using NAT-PMP upstream IPv4 address: %s" NL, upstreamAddrNatPmp);
strcpy(upstreamAddressIP4, upstreamAddrNatPmp);
}
else if (upstreamAddrUPnP[0] != 0 && inet_addr(upstreamAddrUPnP) != 0) {
printf("Using UPnP upstream IPv4 address: %s" NL, upstreamAddrUPnP);
strcpy(upstreamAddressIP4, upstreamAddrUPnP);
}
else {
printf("No valid upstream IPv4 address found!" NL);
upstreamAddressIP4[0] = 0;
}
}
bool IsLikelyNAT(unsigned long netByteOrderAddr)
{
DWORD addr = htonl(netByteOrderAddr);
// 10.0.0.0/8
if ((addr & 0xFF000000) == 0x0A000000) {
return true;
}
// 172.16.0.0/12
else if ((addr & 0xFFF00000) == 0xAC100000) {
return true;
}
// 192.168.0.0/16
else if ((addr & 0xFFFF0000) == 0xC0A80000) {
return true;
}
// 100.64.0.0/10 - RFC6598 official CGN address
else if ((addr & 0xFFC00000) == 0x64400000) {
return true;
}
return false;
}
void UpdatePortMappings(bool enable)
{
IN_ADDR hops[4];
int hopCount = ARRAYSIZE(hops);
char upstreamAddrStr[128];
unsigned long upstreamAddr;
printf("Finding upstream IPv4 hops via traceroute..." NL);
if (!getHopsIP4(hops, &hopCount)) {
hopCount = 0;
}
else {
printf("Found %d hops" NL, hopCount);
}
// getHopsIP4() already skips the default gateway, so 0
// is actually the first hop after the default gateway
int nextHopIndex = 0;
// Start by probing for the default gateway
UpdatePortMappingsForTarget(enable, nullptr, nullptr, upstreamAddrStr);
while (upstreamAddrStr[0] != 0 && (upstreamAddr = inet_addr(upstreamAddrStr)) != 0) {
// We got an upstream address. Let's check if this is a NAT
if (IsLikelyNAT(upstreamAddr)) {
printf("Upstream address %s is likely a NAT" NL, upstreamAddrStr);
if (nextHopIndex >= hopCount) {
printf("Traceroute didn't reach this hop! Aborting!" NL);
break;
}
char targetAddress[128];
inet_ntop(AF_INET, &hops[nextHopIndex], targetAddress, sizeof(targetAddress));
// It's a NAT, so let's direct our UPnP/NAT-PMP messages to it.
// The internal IP address for the new mapping will be the upstream address of the last one.
// The target IP address to which to send the UPnP/NAT-PMP is the next hop of the traceroute.
UpdatePortMappingsForTarget(enable, targetAddress, upstreamAddrStr, upstreamAddrStr);
}
else {
// If we reach a proper public IP address, we're done
printf("Reached the Internet at hop %d" NL, nextHopIndex);
break;
}
// Next hop
nextHopIndex++;
}
fflush(stdout);
}
@@ -536,6 +758,9 @@ void ResetLogFile()
// Redirect stdout to this new file
freopen(currentLogFilePath, "w", stdout);
// Print a log header
printf("Moonlight Internet Streaming Service v" VER_VERSION_STR NL);
}
DWORD WINAPI GameStreamStateChangeThread(PVOID Context)
@@ -590,7 +815,7 @@ int Run()
fflush(stdout);
ULONGLONG beforeSleepTime = GetTickCount64();
DWORD ret = WaitForMultipleObjects(ARRAYSIZE(events), events, false, (PORT_MAPPING_DURATION_SEC * 1000) / 2);
DWORD ret = WaitForMultipleObjects(ARRAYSIZE(events), events, false, POLLING_DELAY_SEC * 1000);
if (ret == WAIT_OBJECT_0) {
ResetLogFile();
@@ -627,6 +852,14 @@ HandlerEx(DWORD dwControl, DWORD dwEventType, LPVOID lpEventData, LPVOID lpConte
return NO_ERROR;
case SERVICE_CONTROL_STOP:
ServiceStatus.dwCurrentState = SERVICE_STOP_PENDING;
ServiceStatus.dwControlsAccepted = 0;
SetServiceStatus(ServiceStatusHandle, &ServiceStatus);
printf("Removing UPnP/NAT-PMP/PCP rules after service stop request\n");
UpdatePortMappings(false);
printf("The service is stopping\n");
ServiceStatus.dwCurrentState = SERVICE_STOPPED;
SetServiceStatus(ServiceStatusHandle, &ServiceStatus);
return NO_ERROR;
+2 -2
View File
@@ -2,7 +2,7 @@
#include "../version.h"
VS_VERSION_INFO VERSIONINFO
FILEVERSION VER_FILEVERSION
FILEVERSION VER_VERSION
BEGIN
BLOCK "StringFileInfo"
BEGIN
@@ -10,7 +10,7 @@ BEGIN
BEGIN
VALUE "CompanyName", VER_COMPANYNAME_STR
VALUE "FileDescription", "Moonlight Internet Streaming Service"
VALUE "FileVersion", VER_FILEVERSION_STR
VALUE "ProductName", VER_PRODUCTNAME_STR
END
END
+2
View File
@@ -162,6 +162,8 @@
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="miss.cpp" />
<ClCompile Include="pcp.cpp" />
<ClCompile Include="tracer.cpp" />
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="miss.rc" />
+6
View File
@@ -18,6 +18,12 @@
<ClCompile Include="miss.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="tracer.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="pcp.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="miss.rc">
+307
View File
@@ -0,0 +1,307 @@
#define _CRT_RAND_S
#define _CRT_SECURE_NO_WARNINGS
#include <stdlib.h>
#define WIN32_LEAN_AND_MEAN
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include <Windows.h>
#include <WinSock2.h>
#include <WS2tcpip.h>
#pragma comment(lib, "Shlwapi.lib")
#include <shlwapi.h>
#include <assert.h>
#include <stdio.h>
#define RECV_TIMEOUT_SEC 3
#define PCP_VERSION 2
#define OPCODE_MAP_REQUEST 0x01
#define OPCODE_MAP_RESPONSE 0x81
#define CODE_PREFER_FAILURE 2
#pragma pack(push, 1)
typedef struct _PCP_REQUEST_HEADER {
unsigned char version;
unsigned char opcode;
unsigned short reserved;
unsigned int lifetime;
unsigned char localAddress[16];
} PCP_REQUEST_HEADER, *PPCP_REQUEST_HEADER;
typedef struct _PCP_RESPONSE_HEADER {
unsigned char version;
unsigned char opcode;
unsigned char reserved;
unsigned char result;
unsigned int lifetime;
unsigned int epoch;
unsigned char reserved2[12];
} PCP_RESPONSE_HEADER, *PPCP_RESPONSE_HEADER;
typedef struct _PCP_OPTION_HEADER {
unsigned char code;
unsigned char reserved;
unsigned short length;
} PCP_OPTION_HEADER, *PPCP_OPTION_HEADER;
typedef struct _PCP_MAP_REQUEST {
PCP_REQUEST_HEADER hdr;
unsigned char mappingNonce[12];
unsigned char protocol;
unsigned char reserved[3];
unsigned short internalPort;
unsigned short externalPort;
unsigned char externalAddress[16];
// We send PREFER_FAILURE too for MAP requests
PCP_OPTION_HEADER preferFailureOption;
} PCP_MAP_REQUEST, *PPCP_MAP_REQUEST;
typedef struct _PCP_MAP_RESPONSE {
PCP_RESPONSE_HEADER hdr;
unsigned char mappingNonce[12];
unsigned char protocol;
unsigned char reserved[3];
unsigned short internalPort;
unsigned short externalPort;
unsigned char externalAddress[16];
} PCP_MAP_RESPONSE, *PPCP_MAP_RESPONSE;
#pragma pack(pop)
static void populateMappingNonce(PPCP_MAP_REQUEST request, PSOCKADDR_STORAGE pcpAddr, int pcpAddrLen)
{
struct {
unsigned short port;
unsigned char localAddress[16];
SOCKADDR_STORAGE targetAddress;
} dataToHash;
assert(request->internalPort != 0);
dataToHash.port = request->internalPort;
memcpy(dataToHash.localAddress, request->hdr.localAddress, sizeof(dataToHash.localAddress));
memcpy(&dataToHash.targetAddress, pcpAddr, pcpAddrLen);
HashData((BYTE*)&dataToHash, 18 + pcpAddrLen, request->mappingNonce, sizeof(request->mappingNonce));
}
static void populateAddressFromSockAddr(PSOCKADDR_STORAGE sockAddr, unsigned char* address)
{
if (sockAddr->ss_family == AF_INET) {
PSOCKADDR_IN sin = (PSOCKADDR_IN)sockAddr;
memset(&address[0], 0, 10);
memset(&address[10], 0xFF, 2);
memcpy(&address[12], &sin->sin_addr, 4);
}
else if (sockAddr->ss_family == AF_INET6) {
PSOCKADDR_IN6 sin6 = (PSOCKADDR_IN6)sockAddr;
memcpy(address, &sin6->sin6_addr, 16);
}
else {
assert(false);
}
}
bool PCPMapPort(PSOCKADDR_STORAGE localAddr, int localAddrLen, PSOCKADDR_STORAGE pcpAddr, int pcpAddrLen, int proto, int port, bool enable, bool indefinite)
{
SOCKET sock;
PCP_MAP_REQUEST reqMsg;
int reqMsgLen;
int i;
int bytesRead;
union {
PCP_MAP_RESPONSE hdr;
char buf[1024];
} resp;
int lifetime;
if (!enable) {
lifetime = 0;
}
else if (indefinite) {
lifetime = 604800; // 1 week
}
else {
lifetime = 3600;
}
assert(localAddr->ss_family == pcpAddr->ss_family);
printf("Updating PCP port mapping for %s %d...", proto == IPPROTO_TCP ? "TCP" : "UDP", port);
sock = socket(localAddr->ss_family, SOCK_DGRAM, IPPROTO_UDP);
if (sock == INVALID_SOCKET) {
printf("socket() failed: %d\n", WSAGetLastError());
return false;
}
if (localAddr->ss_family == AF_INET6) {
// Make sure we're sourcing from the correct IPv6 address to ensure the port
// is opened correctly and that the PCP server doesn't refuse our mapping.
((PSOCKADDR_IN6)localAddr)->sin6_port = 0;
if (bind(sock, (struct sockaddr*)localAddr, localAddrLen) == SOCKET_ERROR) {
printf("bind() failed: %d\n", WSAGetLastError());
closesocket(sock);
return false;
}
}
((PSOCKADDR_IN)pcpAddr)->sin_port = htons(5351);
if (connect(sock, (struct sockaddr*)pcpAddr, pcpAddrLen) == SOCKET_ERROR) {
printf("connect() failed: %d\n", WSAGetLastError());
closesocket(sock);
return false;
}
// If we didn't get a local address, use the address of the interface we bound to.
// NB: We can't do this in all cases because we may be impersonating an upstream
// device if we're behind multiple NATs.
if (localAddr->ss_family == AF_INET && ((PSOCKADDR_IN)localAddr)->sin_addr.S_un.S_addr == 0) {
if (getsockname(sock, (struct sockaddr*)localAddr, &localAddrLen) == SOCKET_ERROR) {
printf("getsockname() failed: %d\n", WSAGetLastError());
closesocket(sock);
return false;
}
}
reqMsg = {};
reqMsg.hdr.version = PCP_VERSION;
reqMsg.hdr.opcode = OPCODE_MAP_REQUEST;
reqMsg.hdr.lifetime = htonl(lifetime);
populateAddressFromSockAddr(localAddr, reqMsg.hdr.localAddress);
reqMsg.protocol = proto;
reqMsg.internalPort = htons(port);
reqMsg.externalPort = htons(port);
SOCKADDR_STORAGE noneAddr = {};
noneAddr.ss_family = localAddr->ss_family;
populateAddressFromSockAddr(&noneAddr, reqMsg.externalAddress);
if (enable) {
// We don't want an alternate allocation if this fails
reqMsg.preferFailureOption.code = CODE_PREFER_FAILURE;
reqMsg.preferFailureOption.length = 0;
reqMsgLen = sizeof(reqMsg);
}
else {
// We don't append PREFER_FAILURE for an unmap request
reqMsgLen = sizeof(reqMsg) - sizeof(reqMsg.preferFailureOption);
}
// This must be done after the rest of the message is populated
populateMappingNonce(&reqMsg, pcpAddr, pcpAddrLen);
bytesRead = 0;
for (i = 0; i < RECV_TIMEOUT_SEC; i++) {
// Retransmit the request every second until the timeout elapses
if (send(sock, (char *)&reqMsg, reqMsgLen, 0) == SOCKET_ERROR) {
printf("send() failed: %d\n", WSAGetLastError());
closesocket(sock);
return false;
}
fd_set fds;
FD_ZERO(&fds);
FD_SET(sock, &fds);
struct timeval tv;
tv.tv_sec = 1;
tv.tv_usec = 0;
int selectRes = select(0, &fds, nullptr, nullptr, &tv);
if (selectRes == 0) {
// Timeout - continue looping
continue;
}
else if (selectRes == SOCKET_ERROR) {
printf("select() failed: %d\n", WSAGetLastError());
closesocket(sock);
return false;
}
// Error handling is below
bytesRead = recv(sock, resp.buf, sizeof(resp.buf), 0);
break;
}
if (bytesRead == 0) {
printf("NO RESPONSE\n");
goto fail;
}
else if (bytesRead == SOCKET_ERROR) {
printf("Failed to read PCP response: %d\n", WSAGetLastError());
goto fail;
}
else if (bytesRead < sizeof(resp.hdr)) {
printf("PCP message truncated: %d\n", bytesRead);
goto fail;
}
else if (resp.hdr.hdr.opcode != OPCODE_MAP_RESPONSE) {
printf("PCP message type mismatch: %x\n", resp.hdr.hdr.opcode);
goto fail;
}
else if (resp.hdr.hdr.result != 0) {
switch (resp.hdr.hdr.result) {
case 1: // UNSUPP_VERSION
printf("UNSUPPORTED\n");
break;
case 2: // NOT_AUTHORIZED
printf("UNAUTHORIZED\n");
break;
case 11: // CANNOT_PROVIDE_EXTERNAL
printf("CONFLICT\n");
break;
default:
printf("ERROR: %d\n", resp.hdr.hdr.result);
break;
}
goto fail;
}
else if (memcmp(reqMsg.mappingNonce, resp.hdr.mappingNonce, sizeof(reqMsg.mappingNonce))) {
printf("PCP mapping nonce mismatch\n");
goto fail;
}
else if (reqMsg.protocol != resp.hdr.protocol) {
printf("PCP protocol mismatch: %d wanted %d\n", resp.hdr.protocol, reqMsg.protocol);
goto fail;
}
else if (reqMsg.internalPort != resp.hdr.internalPort) {
printf("PCP internal port mismatch: %d wanted %d\n", htons(resp.hdr.internalPort), htons(reqMsg.internalPort));
goto fail;
}
else if (reqMsg.externalPort != resp.hdr.externalPort) {
printf("PCP returned different external port: %d wanted %d\n", htons(resp.hdr.externalPort), htons(reqMsg.externalPort));
if (enable) {
// Clear the port mapping by modifying and resending the old request (with the same nonce)
reqMsg.hdr.lifetime = 0;
reqMsg.externalPort = resp.hdr.externalPort;
reqMsgLen = sizeof(reqMsg) - sizeof(reqMsg.preferFailureOption);
if (send(sock, (char*)&reqMsg, reqMsgLen, 0) == SOCKET_ERROR) {
printf("Failed to unmap unexpected external port: %d\n", WSAGetLastError());
}
}
goto fail;
}
if (enable) {
printf("OK (%d seconds remaining)\n", ntohl(resp.hdr.hdr.lifetime));
}
else {
printf("DELETED\n");
}
closesocket(sock);
return true;
fail:
closesocket(sock);
return false;
}
+227
View File
@@ -0,0 +1,227 @@
#define WIN32_LEAN_AND_MEAN
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#include <Windows.h>
#include <WinSock2.h>
#include <WS2tcpip.h>
#include <iphlpapi.h>
#include <icmpapi.h>
#include <stdio.h>
#include <stdlib.h>
#define MINIUPNP_STATICLIB
#include <miniupnpc/miniupnpc.h>
static const char* k_SsdpSearchFormatString =
"M-SEARCH * HTTP/1.1\r\n"
"HOST: %s:1900\r\n"
"ST: ssdp:all\r\n"
"MAN: \"ssdp:discover\"\r\n"
"MX: 5\r\n"
"\r\n";
struct UPNPDev* getUPnPDevicesByAddress(IN_ADDR address)
{
SOCKET s;
SOCKADDR_IN connAddr;
char searchBuffer[512];
int chars;
s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (s == INVALID_SOCKET) {
printf("socket() failed: %d\n", WSAGetLastError());
return nullptr;
}
connAddr = {};
connAddr.sin_family = AF_INET;
connAddr.sin_port = htons(1900);
connAddr.sin_addr = address;
// Use connect() to ensure we don't get responses from other devices
if (connect(s, (struct sockaddr*)&connAddr, sizeof(connAddr)) == SOCKET_ERROR) {
printf("connect() failed: %d\n", WSAGetLastError());
closesocket(s);
return nullptr;
}
// Send the first search message with HOST set properly
chars = snprintf(searchBuffer, ARRAYSIZE(searchBuffer), k_SsdpSearchFormatString, inet_ntoa(address));
if (send(s, searchBuffer, chars, 0) == SOCKET_ERROR) {
printf("send() failed: %d\n", WSAGetLastError());
closesocket(s);
return nullptr;
}
// Send another search message with HOST set to 239.255.255.250 to avoid issues
// on routers that explicitly check for that HOST value
chars = snprintf(searchBuffer, ARRAYSIZE(searchBuffer), k_SsdpSearchFormatString, "239.255.255.250");
if (send(s, searchBuffer, chars, 0) == SOCKET_ERROR) {
printf("send() failed: %d\n", WSAGetLastError());
closesocket(s);
return nullptr;
}
Sleep(5000);
// Switch to non-blocking mode to read the responses
u_long mode = 1;
ioctlsocket(s, FIONBIO, &mode);
char responseBuffer[2048];
struct UPNPDev* deviceList = nullptr;
for (;;) {
int bytesRead = recv(s, responseBuffer, sizeof(responseBuffer) - 1, 0);
if (bytesRead == SOCKET_ERROR) {
if (WSAGetLastError() == WSAEMSGSIZE) {
// Skip packets larger than our buffer
printf("recv() message too large\n");
continue;
}
else if (WSAGetLastError() != WSAEWOULDBLOCK) {
printf("recv() failed: %d\n", WSAGetLastError());
}
break;
}
// Null-terminate the buffer
responseBuffer[bytesRead] = 0;
// Parse the first status line:
// HTTP/1.1 200 OK
char* protocol = strtok(responseBuffer, " ");
char* statusCodeStr = strtok(nullptr, " ");
char* statusMessage = strtok(nullptr, "\r");
// Check for a valid response header
if (protocol == nullptr) {
printf("Missing protocol in SSDP header\n");
continue;
}
else if (statusCodeStr == nullptr) {
printf("Missing status code in SSDP header\n");
continue;
}
// FIXME: Should we require statusMessage too?
else if (_stricmp(protocol, "HTTP/1.0") && _stricmp(protocol, "HTTP/1.1")) {
printf("Unexpected protocol: %s\n", protocol);
continue;
}
else if (atoi(statusCodeStr) != 200) {
printf("Unexpected status: %s %s\n", statusCodeStr, statusMessage);
continue;
}
// Parse the header options
// SERVER: FreeBSD/11.2-RELEASE-p2 UPnP/1.1 MiniUPnPd/2.0\r\n
char* location = nullptr;
char* st = nullptr;
while (char* headerName = strtok(nullptr, "\r\n:")) {
char* headerValue = strtok(nullptr, "\r");
if (headerValue == nullptr) {
printf("Unexpected end of SSDP header\n");
break;
}
// Skip leading spaces
while (*headerValue == ' ') headerValue++;
if (!_stricmp(headerName, "LOCATION")) {
location = headerValue;
}
else if (!_stricmp(headerName, "ST")) {
st = headerValue;
}
}
if (!location || location[0] == 0 || !st || st[0] == 0) {
printf("Required value missing: \"%s\" \"%s\"\n", location, st);
continue;
}
struct UPNPDev* newDev = (struct UPNPDev*)malloc(sizeof(*newDev) + strlen(location) + strlen(st) + 2);
newDev->pNext = deviceList;
newDev->usn = &newDev->buffer[0]; newDev->buffer[0] = 0;
newDev->descURL = strcpy(newDev->usn + strlen(newDev->usn) + 1, location);
newDev->st = strcpy(newDev->descURL + strlen(newDev->descURL) + 1, st);
newDev->scope_id = 0; // IPv6 only
deviceList = newDev;
}
closesocket(s);
return deviceList;
}
// Start at TTL 2 to skip contacting our default gateway
#define TTL_START 2
bool getHopsIP4(IN_ADDR* hopAddress, int* hopAddressCount)
{
HANDLE icmpFile;
struct hostent* host;
const char* requestBuffer = "Test";
union {
ICMP_ECHO_REPLY replies[ANYSIZE_ARRAY];
char replyBuffer[128];
};
host = gethostbyname("google.com");
if (host == nullptr) {
printf("gethostbyname() failed: %d\n", WSAGetLastError());
return false;
}
icmpFile = IcmpCreateFile();
if (icmpFile == INVALID_HANDLE_VALUE) {
printf("IcmpCreateFile() failed: %d\n", GetLastError());
return false;
}
int ttl;
for (ttl = TTL_START; ttl - TTL_START < *hopAddressCount; ttl++)
{
IP_OPTION_INFORMATION ipOptions;
ipOptions.Ttl = ttl;
ipOptions.Tos = 0;
ipOptions.Flags = 0;
ipOptions.OptionsSize = 0;
DWORD replyCount = IcmpSendEcho(icmpFile,
*(IPAddr*)host->h_addr,
(LPVOID)requestBuffer, sizeof(requestBuffer),
&ipOptions,
replyBuffer, sizeof(replyBuffer),
3000);
if (replyCount == 0) {
printf("IcmpSendEcho() failed: %d\n", GetLastError());
break;
}
else if (replyCount != 1) {
printf("Got extra replies: %d\n", replyCount);
break;
}
if (replies[0].Status == IP_TTL_EXPIRED_TRANSIT) {
// Get the IP address that responded to us
printf("Hop %d: %s\n", ttl - TTL_START, inet_ntoa(*(IN_ADDR*)&replies[0].Address));
hopAddress[ttl - TTL_START] = *(IN_ADDR*)&replies[0].Address;
}
else {
// Bail on anything else
printf("Hop %d: %s (error %d)\n", ttl - TTL_START, inet_ntoa(*(IN_ADDR*)&replies[0].Address), replies[0].Status);
break;
}
}
IcmpCloseHandle(icmpFile);
*hopAddressCount = ttl - TTL_START;
return true;
}
+182 -221
View File
@@ -12,6 +12,8 @@
#include <shellapi.h>
#include <objbase.h>
#include "..\version.h"
#pragma comment(lib, "miniupnpc.lib")
#pragma comment(lib, "libnatpmp.lib")
#pragma comment(lib, "ws2_32.lib")
@@ -25,28 +27,7 @@
#define NATPMP_STATICLIB
#include <natpmp.h>
#define STUN_MESSAGE_BINDING_REQUEST 0x0001
#define STUN_MESSAGE_BINDING_SUCCESS 0x0101
#define STUN_MESSAGE_COOKIE 0x2112a442
#define STUN_ATTRIBUTE_MAPPED_ADDRESS 0x0001
#define STUN_ATTRIBUTE_XOR_MAPPED_ADDRESS 0x0020
typedef struct _STUN_MAPPED_IPV4_ADDRESS_ATTRIBUTE {
USHORT attributeType;
USHORT attributeLength;
UCHAR reserved;
UCHAR addressFamily;
USHORT port;
ULONG address;
} STUN_MAPPED_IPV4_ADDRESS_ATTRIBUTE, *PSTUN_MAPPED_IPV4_ADDRESS_ATTRIBUTE;
typedef struct _STUN_MESSAGE {
USHORT messageType;
USHORT messageLength;
UINT magicCookie;
UINT transactionId[3];
} STUN_MESSAGE, *PSTUN_MESSAGE;
bool getExternalAddressPortIP4(int proto, unsigned short localPort, PSOCKADDR_IN wanAddr);
static struct port_entry {
int proto;
@@ -65,33 +46,53 @@ static struct port_entry {
char logFilePath[MAX_PATH + 1];
void DisplayMessage(const char* message, bool error = true)
enum MessagePriority {
MpInfo,
MpWarn,
MpError
};
void DisplayMessage(const char* message, MessagePriority priority = MpError, bool terminal = true)
{
printf("%s\n", message);
printf("--------------- MISS LOG -------------------\n");
char missPath[MAX_PATH + 1];
ExpandEnvironmentStringsA("%ProgramData%\\MISS\\miss-current.log", missPath, sizeof(missPath));
FILE* f = fopen(missPath, "r");
if (f != nullptr) {
char buffer[1024];
while (!feof(f)) {
int bytesRead = fread(buffer, 1, ARRAYSIZE(buffer), f);
fwrite(buffer, 1, bytesRead, stdout);
if (terminal) {
printf("--------------- MISS LOG -------------------\n");
char missPath[MAX_PATH + 1];
ExpandEnvironmentStringsA("%ProgramData%\\MISS\\miss-current.log", missPath, sizeof(missPath));
FILE* f = fopen(missPath, "r");
if (f != nullptr) {
char buffer[1024];
while (!feof(f)) {
int bytesRead = fread(buffer, 1, ARRAYSIZE(buffer), f);
fwrite(buffer, 1, bytesRead, stdout);
}
fclose(f);
}
fclose(f);
}
else {
printf("Failed to find MISS log\n");
else {
printf("Failed to find MISS log\n");
}
fflush(stdout);
}
fflush(stdout);
DWORD flags = MB_OK | MB_TOPMOST | MB_SETFOREGROUND;
flags |= error ? MB_ICONERROR : MB_ICONINFORMATION;
switch (priority) {
case MpInfo:
flags |= MB_ICONINFORMATION;
break;
case MpWarn:
flags |= MB_ICONWARNING;
break;
case MpError:
flags |= MB_ICONERROR;
break;
}
MessageBoxA(nullptr, message, "Moonlight Internet Streaming Tester", flags);
if (error) {
if (priority != MpInfo && terminal) {
flags = MB_YESNO | MB_TOPMOST | MB_SETFOREGROUND | MB_ICONINFORMATION;
switch (MessageBoxA(nullptr, "Would you like to view the troubleshooting log?",
"Moonlight Internet Streaming Tester", flags))
@@ -115,19 +116,18 @@ bool IsGameStreamEnabled()
error = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "Software\\NVIDIA Corporation\\NvStream", 0, KEY_READ | KEY_WOW64_64KEY, &key);
if (error != ERROR_SUCCESS) {
printf("RegOpenKeyEx() failed: %d\n", error);
DisplayMessage("GeForce Experience is not installed. Please install GeForce Experience to use Moonlight.");
DisplayMessage("GeForce Experience was not detected on this PC. Make sure you're installing this utility on your GeForce GameStream-compatible PC, not the device running Moonlight.");
return false;
}
len = sizeof(enabled);
error = RegQueryValueExA(key, "EnableStreaming", nullptr, nullptr, (LPBYTE)&enabled, &len);
RegCloseKey(key);
if (error != ERROR_SUCCESS) {
printf("RegQueryValueExA() failed: %d\n", error);
DisplayMessage("GeForce Experience is not installed. Please install GeForce Experience to use Moonlight.");
return false;
}
else if (!enabled) {
if (error != ERROR_SUCCESS || !enabled) {
// GFE may not even write EnableStreaming until the user enables GameStream for the first time
if (error != ERROR_SUCCESS) {
printf("RegQueryValueExA() failed: %d\n", error);
}
DisplayMessage("GameStream is not enabled in GeForce Experience. Please open GeForce Experience settings, navigate to the Shield tab, and turn GameStream on.");
return false;
}
@@ -253,7 +253,7 @@ PortTestStatus TestPort(PSOCKADDR_STORAGE addr, int proto, int port, bool withSe
return err == 1 ? PortTestOk : PortTestError;
}
else {
const char testMsg[] = "mist-test";
const char testMsg[] = "moonlight-test";
err = sendto(clientSock, testMsg, sizeof(testMsg), 0, (struct sockaddr*)&sin6, addrLen);
if (err == SOCKET_ERROR) {
printf("sendto() failed: %d\n", WSAGetLastError());
@@ -289,13 +289,10 @@ PortTestStatus TestPort(PSOCKADDR_STORAGE addr, int proto, int port, bool withSe
}
}
bool TestAllPorts(PSOCKADDR_STORAGE addr, const char* baseMessage, char* message, int messageLength)
bool TestAllPorts(PSOCKADDR_STORAGE addr, char* portMsg, int portMsgLen)
{
strcpy_s(message, messageLength, baseMessage);
message += strlen(baseMessage);
messageLength -= strlen(baseMessage);
bool ret = true;
for (int i = 0; i < ARRAYSIZE(k_Ports); i++) {
printf("Testing %s %d...",
k_Ports[i].proto == IPPROTO_TCP ? "TCP" : "UDP",
@@ -305,11 +302,11 @@ bool TestAllPorts(PSOCKADDR_STORAGE addr, const char* baseMessage, char* message
// If we got an unknown result, assume it matches with whatever
// we've gotten so far.
if (status == PortTestError || !ret) {
int msgLen = snprintf(message, messageLength, "%s %d\n",
int msgLen = snprintf(portMsg, portMsgLen, "%s %d\n",
k_Ports[i].proto == IPPROTO_TCP ? "TCP" : "UDP",
k_Ports[i].port);
message += msgLen;
messageLength -= msgLen;
portMsg += msgLen;
portMsgLen -= msgLen;
// Keep going to check all ports and report the failing ones
ret = false;
@@ -323,9 +320,16 @@ bool TestAllPorts(PSOCKADDR_STORAGE addr, const char* baseMessage, char* message
bool FindLocalInterfaceIP4Address(PSOCKADDR_IN addr)
{
SOCKET s;
struct hostent* host;
printf("Finding local IP address...");
host = gethostbyname("google.com");
if (host == nullptr) {
printf("gethostbyname() failed: %d\n", WSAGetLastError());
return false;
}
s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (s == INVALID_SOCKET) {
printf("socket() failed: %d\n", WSAGetLastError());
@@ -335,7 +339,7 @@ bool FindLocalInterfaceIP4Address(PSOCKADDR_IN addr)
SOCKADDR_IN sin = {};
sin.sin_family = AF_INET;
sin.sin_port = htons(443);
sin.sin_addr.S_un.S_addr = inet_addr("8.8.8.8");
sin.sin_addr = *(struct in_addr*)host->h_addr;
int err = connect(s, (struct sockaddr*)&sin, sizeof(sin));
if (err == SOCKET_ERROR) {
printf("connect() failed: %d\n", WSAGetLastError());
@@ -415,123 +419,15 @@ UPnPPortStatus UPnPCheckPort(struct UPNPUrls* urls, struct IGDdatas* data, int p
}
}
bool STUNFindWanAddress(PSOCKADDR_IN wanAddr)
{
SOCKET s;
s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (s == INVALID_SOCKET) {
printf("socket() failed: %d\n", WSAGetLastError());
return false;
}
struct hostent *host;
host = gethostbyname("stun.stunprotocol.org");
if (host == nullptr) {
printf("gethostbyname() failed\n");
closesocket(s);
return false;
}
SOCKADDR_IN sin = {};
sin.sin_family = AF_INET;
sin.sin_port = htons(3478);
sin.sin_addr = *(struct in_addr*)host->h_addr;
int err = connect(s, (struct sockaddr*)&sin, sizeof(sin));
if (err == SOCKET_ERROR) {
printf("connect() failed: %d\n", WSAGetLastError());
closesocket(s);
return false;
}
STUN_MESSAGE reqMsg;
reqMsg.messageType = htons(STUN_MESSAGE_BINDING_REQUEST);
reqMsg.messageLength = 0;
reqMsg.magicCookie = htonl(STUN_MESSAGE_COOKIE);
for (int i = 0; i < ARRAYSIZE(reqMsg.transactionId); i++) {
rand_s(&reqMsg.transactionId[i]);
}
err = send(s, (char *)&reqMsg, sizeof(reqMsg), 0);
if (err == SOCKET_ERROR) {
printf("send() failed: %d\n", WSAGetLastError());
closesocket(s);
return false;
}
union {
struct {
STUN_MESSAGE respMsg;
STUN_MAPPED_IPV4_ADDRESS_ATTRIBUTE mappedAddress;
};
char respBuf[128];
};
int bytesRead = recv(s, respBuf, sizeof(respBuf), 0);
if (bytesRead == SOCKET_ERROR) {
printf("recv() failed: %d\n", WSAGetLastError());
closesocket(s);
return false;
}
else if (bytesRead < sizeof(respMsg)) {
printf("STUN message truncated: %d\n", bytesRead);
closesocket(s);
return false;
}
closesocket(s);
if (htonl(respMsg.magicCookie) != STUN_MESSAGE_COOKIE) {
printf("Bad STUN cookie value: %x\n", htonl(respMsg.magicCookie));
return false;
}
else if (!RtlEqualMemory(reqMsg.transactionId, respMsg.transactionId, sizeof(reqMsg.transactionId))) {
printf("STUN transaction ID mismatch\n");
return false;
}
else if (htons(respMsg.messageType) != STUN_MESSAGE_BINDING_SUCCESS) {
printf("STUN message type mismatch: %x\n", htons(respMsg.messageType));
return false;
}
else if (bytesRead < sizeof(respMsg) + sizeof(mappedAddress)) {
printf("STUN message too short: %d\n", bytesRead);
return false;
}
else if (htons(mappedAddress.attributeType) != STUN_ATTRIBUTE_MAPPED_ADDRESS &&
htons(mappedAddress.attributeType) != STUN_ATTRIBUTE_XOR_MAPPED_ADDRESS) {
printf("STUN attribute type mismatch: %x\n", htons(mappedAddress.attributeType));
return false;
}
else if (htons(mappedAddress.attributeLength) != 8) {
printf("STUN address length mismatch: %d\n", htons(mappedAddress.attributeLength));
return false;
}
else if (mappedAddress.addressFamily != 1) {
printf("STUN address family mismatch: %x\n", mappedAddress.addressFamily);
return false;
}
if (htons(mappedAddress.attributeType) == STUN_ATTRIBUTE_MAPPED_ADDRESS) {
// The address is directly encoded
wanAddr->sin_addr.S_un.S_addr = mappedAddress.address;
}
else {
// The address is XORed
wanAddr->sin_addr.S_un.S_addr = mappedAddress.address ^ respMsg.magicCookie;
}
return true;
}
bool CheckWANAccess(PSOCKADDR_IN wanAddr, bool* foundPortForwardingRules)
bool CheckWANAccess(PSOCKADDR_IN wanAddr, PSOCKADDR_IN reportedWanAddr, bool* foundPortForwardingRules, bool* igdDisconnected)
{
natpmp_t natpmp;
bool foundUpnpIgd = false;
*foundPortForwardingRules = false;
*igdDisconnected = false;
printf("Finding WAN IP address...");
bool gotWanAddress = false;
bool gotReportedWanAddress = false;
int natPmpErr = initnatpmp(&natpmp, 0, 0);
if (natPmpErr != 0) {
printf("initnatpmp() failed: %d\n", natPmpErr);
@@ -556,11 +452,23 @@ bool CheckWANAccess(PSOCKADDR_IN wanAddr, bool* foundPortForwardingRules)
if (ret != 0) {
// Connected or disconnected IGD
if (ret == 1 || ret == 2) {
foundUpnpIgd = true;
if (ret == 2) {
*igdDisconnected = true;
}
printf("Discovered UPnP IGD at: %s\n", urls.controlURL);
printf("Detecting WAN IP address via UPnP...");
ret = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, wanAddrStr);
if (ret == UPNPCOMMAND_SUCCESS) {
wanAddr->sin_addr.S_un.S_addr = inet_addr(wanAddrStr);
printf("%s (UPnP)\n", wanAddrStr);
gotWanAddress = true;
if (ret == UPNPCOMMAND_SUCCESS && strlen(wanAddrStr) > 0) {
reportedWanAddr->sin_addr.S_un.S_addr = wanAddr->sin_addr.S_un.S_addr = inet_addr(wanAddrStr);
printf("%s\n", wanAddrStr);
if (wanAddr->sin_addr.S_un.S_addr != 0) {
gotReportedWanAddress = true;
}
}
else {
printf("FAILED %d\n", ret);
}
char conflictMessage[512];
@@ -585,53 +493,77 @@ bool CheckWANAccess(PSOCKADDR_IN wanAddr, bool* foundPortForwardingRules)
}
}
}
else {
printf("No UPnP IGD detected\n");
}
FreeUPNPUrls(&urls);
}
else {
printf("No UPnP devices detected\n");
}
}
// Use the delay of upnpDiscoverAll() to also allow the NAT-PMP endpoint time to respond
if (natPmpErr >= 0) {
printf("Detecting WAN IP address via NAT-PMP...");
natpmpresp_t response;
natPmpErr = readnatpmpresponseorretry(&natpmp, &response);
closenatpmp(&natpmp);
if (natPmpErr == 0 && !gotWanAddress) {
if (natPmpErr == 0) {
char addrStr[64];
wanAddr->sin_addr = response.pnu.publicaddress.addr;
reportedWanAddr->sin_addr = wanAddr->sin_addr = response.pnu.publicaddress.addr;
inet_ntop(AF_INET, &response.pnu.publicaddress.addr, addrStr, sizeof(addrStr));
printf("%s (NAT-PMP)\n", addrStr);
gotWanAddress = true;
printf("%s\n", addrStr);
if (wanAddr->sin_addr.S_un.S_addr != 0) {
gotReportedWanAddress = true;
if (!foundUpnpIgd) {
// Just in case we have a NAT-PMP gateway that doesn't do NAT reflection
// let's assume it's all okay if we got any response at all
*foundPortForwardingRules = true;
}
}
}
else {
printf("FAILED %d\n", natPmpErr);
}
}
if (!gotWanAddress) {
if (!STUNFindWanAddress(wanAddr)) {
printf("FAILED\n");
DisplayMessage("MIST was unable to determine your public IP address. Please check your Internet connection.");
printf("Detecting WAN IP address via STUN...");
if (!getExternalAddressPortIP4(IPPROTO_UDP, 0, wanAddr)) {
if (!gotReportedWanAddress) {
DisplayMessage("Unable to determine your public IP address. Please check your Internet connection.");
return false;
}
char addrStr[64];
inet_ntop(AF_INET, &wanAddr->sin_addr, addrStr, sizeof(addrStr));
printf("%s (STUN)\n", addrStr);
return true;
}
else {
return true;
char addrStr[64];
inet_ntop(AF_INET, &wanAddr->sin_addr, addrStr, sizeof(addrStr));
printf("%s\n", addrStr);
if (!gotReportedWanAddress) {
// If we didn't get anything from UPnP or NAT-PMP, just populate the reported
// address with what we got from STUN
*reportedWanAddr = *wanAddr;
}
}
return true;
}
bool IsPossibleCGN(PSOCKADDR_IN wanAddr)
{
DWORD addr = htonl(wanAddr->sin_addr.S_un.S_addr);
// 10.0.0.0/24 - ISPs used to use this
// 10.0.0.0/8 - ISPs used to use this
if ((addr & 0xFF000000) == 0x0A000000) {
return true;
}
// 100.64.0.0 - RFC6598 official CGN address
else if ((addr & 0xFFC0) == 0x64400000) {
// 100.64.0.0/10 - RFC6598 official CGN address
else if ((addr & 0xFFC00000) == 0x64400000) {
return true;
}
@@ -642,11 +574,11 @@ bool IsDoubleNAT(PSOCKADDR_IN wanAddr)
{
DWORD addr = htonl(wanAddr->sin_addr.S_un.S_addr);
// 10.0.0.0/24
// 10.0.0.0/8
if ((addr & 0xFF000000) == 0x0A000000) {
return true;
}
// 172.16.0.0/20
// 172.16.0.0/12
else if ((addr & 0xFFF00000) == 0xAC100000) {
return true;
}
@@ -665,9 +597,15 @@ int main(int argc, char* argv[])
char tempPath[MAX_PATH + 1];
GetTempPathA(sizeof(tempPath), tempPath);
snprintf(logFilePath, sizeof(logFilePath), "%s\\%s", tempPath, "mist.log");
snprintf(logFilePath, sizeof(logFilePath), "%s\\%s", tempPath, "mis-test.log");
freopen(logFilePath, "w", stdout);
// Print a log header
printf("Moonlight Internet Streaming Tester v" VER_VERSION_STR "\n");
// Print a console header
fprintf(stderr, "Moonlight Internet Streaming Tester v" VER_VERSION_STR "\n\n");
int err = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (err != NO_ERROR) {
DisplayMessage("Unable to initialize WinSock");
@@ -687,6 +625,7 @@ int main(int argc, char* argv[])
SOCKADDR_IN6 sin6;
};
char msgBuf[2048];
char portMsgBuf[512];
fprintf(stderr, "Testing local GameStream connectivity...\n");
@@ -695,9 +634,10 @@ int main(int argc, char* argv[])
sin.sin_family = AF_INET;
sin.sin_addr = in4addr_loopback;
printf("Testing GameStream ports via loopback\n");
if (!TestAllPorts(&ss,
"Local GameStream connectivity check failed. Please try reinstalling GeForce Experience.\n\nThe following ports were not working:\n",
msgBuf, sizeof(msgBuf))) {
if (!TestAllPorts(&ss, portMsgBuf, sizeof(portMsgBuf))) {
snprintf(msgBuf, sizeof(msgBuf),
"Local GameStream connectivity check failed. Please try reinstalling GeForce Experience.\n\nThe following ports were not working:\n%s",
portMsgBuf);
DisplayMessage(msgBuf);
return -1;
}
@@ -711,47 +651,68 @@ int main(int argc, char* argv[])
// Try to connect via LAN IPv4 address
printf("Testing GameStream ports via local network\n");
if (!TestAllPorts(&ss,
"Local network GameStream connectivity check failed. Try temporarily disabling your firewall software or adding firewall exceptions for the following ports:\n",
msgBuf, sizeof(msgBuf))) {
if (!TestAllPorts(&ss, portMsgBuf, sizeof(portMsgBuf))) {
snprintf(msgBuf, sizeof(msgBuf),
"Local network GameStream connectivity check failed. Try temporarily disabling your firewall software or adding firewall exceptions for the following ports:\n%s",
portMsgBuf);
DisplayMessage(msgBuf);
return -1;
}
fprintf(stderr, "Detecting public IP address...\n");
bool upnpRulesFound;
if (!CheckWANAccess(&sin, &upnpRulesFound)) {
bool rulesFound, igdDisconnected;
SOCKADDR_IN locallyReportedWanAddr;
if (!CheckWANAccess(&sin, &locallyReportedWanAddr, &rulesFound, &igdDisconnected)) {
return -1;
}
// Detect a double NAT by detecting STUN and and UPnP mismatches
if (sin.sin_addr.S_un.S_addr != locallyReportedWanAddr.sin_addr.S_un.S_addr) {
printf("Testing GameStream ports via UPnP/NAT-PMP reported WAN address\n");
// We don't actually care about the outcome here but it's nice to have in logs
// to determine whether solving the double NAT will actually make Moonlight work.
TestAllPorts((PSOCKADDR_STORAGE)&locallyReportedWanAddr, portMsgBuf, sizeof(portMsgBuf));
printf("Detected inconsistency between UPnP/NAT-PMP and STUN reported WAN addresses!\n");
}
fprintf(stderr, "Testing Internet GameStream connectivity...\n");
char wanAddrStr[64];
inet_ntop(AF_INET, &sin.sin_addr, wanAddrStr, sizeof(wanAddrStr));
// Try to connect via WAN IPv4 address
printf("Testing GameStream ports via WAN address\n");
if (!TestAllPorts(&ss,
upnpRulesFound ? "Found UPnP rules, but they did not work correctly. Check for conflicting port forwarding entries in your router settings.\n\nThe following ports were not forwarded properly:\n" :
"Internet GameStream connectivity check failed. Make sure UPnP is enabled in your router settings.\n\nThe following ports were not forwarded properly:\n",
msgBuf, sizeof(msgBuf))) {
DisplayMessage(msgBuf);
printf("Testing GameStream ports via STUN-reported WAN address\n");
if (!TestAllPorts(&ss, portMsgBuf, sizeof(portMsgBuf))) {
if (IsDoubleNAT(&locallyReportedWanAddr)) {
snprintf(msgBuf, sizeof(msgBuf), "Your router appears be connected to the Internet through another router. Make sure both routers have UPnP or NAT-PMP enabled, or better yet, switch one of the routers into bridge/AP mode.");
DisplayMessage(msgBuf);
}
else if (IsPossibleCGN(&locallyReportedWanAddr)) {
snprintf(msgBuf, sizeof(msgBuf), "Your ISP is running a Carrier-Grade NAT that is preventing you from hosting services like Moonlight on the Internet. Contact your ISP and ask for a dedicated public IP address.");
DisplayMessage(msgBuf);
}
else if (igdDisconnected) {
snprintf(msgBuf, sizeof(msgBuf), "Internet GameStream connectivity check failed. Make sure you don't have two devices acting as routers connected together.");
DisplayMessage(msgBuf);
}
else if (rulesFound) {
snprintf(msgBuf, sizeof(msgBuf), "Manual Internet streaming test required!\n\n"
"Connect your client device to a different network or cellular data (it MUST NOT on be the same network as this PC for testing!). If Moonlight doesn't automatically connect, you can type the following address into Moonlight's Add PC dialog: %s\n\n"
"If that doesn't work, check your router settings for any existing Moonlight port forwarding entries and delete them or try restarting your router.", wanAddrStr);
DisplayMessage(msgBuf, MpWarn);
}
else {
snprintf(msgBuf, sizeof(msgBuf), "Internet GameStream connectivity check failed. Make sure UPnP or NAT-PMP is enabled in your router settings.\n\nThe following ports were not forwarded properly:\n%s", portMsgBuf);
DisplayMessage(msgBuf);
}
return -1;
}
// Check for double-NAT
if (IsDoubleNAT(&sin)) {
DisplayMessage("Your router appears be connected to another router. This configuration breaks port forwarding. To resolve this, switch one of the devices into bridge mode.");
return -1;
}
// Check for CGN
else if (IsPossibleCGN(&sin)) {
DisplayMessage("Your ISP is running a Carrier-Grade NAT. This prevents you from hosting services like GameStream. Contact your ISP to get a real public IP address.");
return -1;
}
char addrStr[64];
inet_ntop(AF_INET, &sin.sin_addr, addrStr, sizeof(addrStr));
snprintf(msgBuf, sizeof(msgBuf), "All tests passed! You should be able to stream by typing the following address into Moonlight's Add PC dialog: %s", addrStr);
DisplayMessage(msgBuf, false);
snprintf(msgBuf, sizeof(msgBuf), "All tests passed! If Moonlight doesn't automatically connect outside your network, you can type the following address into Moonlight's Add PC dialog: %s", wanAddrStr);
DisplayMessage(msgBuf, MpInfo);
return 0;
}
+2 -2
View File
@@ -2,7 +2,7 @@
#include "../version.h"
VS_VERSION_INFO VERSIONINFO
FILEVERSION VER_FILEVERSION
FILEVERSION VER_VERSION
BEGIN
BLOCK "StringFileInfo"
BEGIN
@@ -10,7 +10,7 @@ BEGIN
BEGIN
VALUE "CompanyName", VER_COMPANYNAME_STR
VALUE "FileDescription", "Moonlight Internet Streaming Tester"
VALUE "FileVersion", VER_FILEVERSION_STR
VALUE "ProductName", VER_PRODUCTNAME_STR
END
END
+1
View File
@@ -160,6 +160,7 @@
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="mist.cpp" />
<ClCompile Include="stun.cpp" />
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="mist.rc" />
+3
View File
@@ -18,6 +18,9 @@
<ClCompile Include="mist.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="stun.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\version.h">
+211
View File
@@ -0,0 +1,211 @@
#define _CRT_RAND_S
#define _CRT_SECURE_NO_WARNINGS
#include <stdlib.h>
#define WIN32_LEAN_AND_MEAN
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include <Windows.h>
#include <WinSock2.h>
#include <stdio.h>
#define STUN_PORT 3478
#define STUN_RECV_TIMEOUT_SEC 3
#define STUN_MESSAGE_BINDING_REQUEST 0x0001
#define STUN_MESSAGE_BINDING_SUCCESS 0x0101
#define STUN_MESSAGE_COOKIE 0x2112a442
#define STUN_ATTRIBUTE_MAPPED_ADDRESS 0x0001
#define STUN_ATTRIBUTE_XOR_MAPPED_ADDRESS 0x0020
#pragma pack(push, 1)
typedef struct _STUN_ATTRIBUTE_HEADER {
unsigned short type;
unsigned short length;
} STUN_ATTRIBUTE_HEADER, *PSTUN_ATTRIBUTE_HEADER;
typedef struct _STUN_MAPPED_IPV4_ADDRESS_ATTRIBUTE {
STUN_ATTRIBUTE_HEADER hdr;
unsigned char reserved;
unsigned char addressFamily;
unsigned short port;
unsigned int address;
} STUN_MAPPED_IPV4_ADDRESS_ATTRIBUTE, *PSTUN_MAPPED_IPV4_ADDRESS_ATTRIBUTE;
#define TXID_DWORDS 3
typedef struct _STUN_MESSAGE {
unsigned short messageType;
unsigned short messageLength;
unsigned int magicCookie;
int transactionId[TXID_DWORDS];
} STUN_MESSAGE, *PSTUN_MESSAGE;
#pragma pack(pop)
bool getExternalAddressPortIP4(int proto, unsigned short localPort, PSOCKADDR_IN wanAddr)
{
SOCKET sock;
STUN_MESSAGE reqMsg;
int i;
int bytesRead;
int tries;
int timeout;
PSTUN_ATTRIBUTE_HEADER attribute;
PSTUN_MAPPED_IPV4_ADDRESS_ATTRIBUTE ipv4Attrib;
struct hostent *host;
union {
STUN_MESSAGE hdr;
char buf[1024];
} resp;
host = gethostbyname("stun.stunprotocol.org");
if (host == nullptr) {
printf("gethostbyname() failed: %d\n", WSAGetLastError());
return false;
}
sock = socket(AF_INET, proto == IPPROTO_TCP ? SOCK_STREAM : SOCK_DGRAM, proto);
if (sock == INVALID_SOCKET) {
printf("socket() failed: %d\n", WSAGetLastError());
return false;
}
struct sockaddr_in bindAddr = {};
bindAddr.sin_family = AF_INET;
bindAddr.sin_port = htons(localPort);
if (bind(sock, (struct sockaddr*)&bindAddr, sizeof(bindAddr)) == SOCKET_ERROR) {
printf("bind() failed: %d\n", WSAGetLastError());
closesocket(sock);
return false;
}
reqMsg.messageType = htons(STUN_MESSAGE_BINDING_REQUEST);
reqMsg.messageLength = 0;
reqMsg.magicCookie = htonl(STUN_MESSAGE_COOKIE);
for (i = 0; i < TXID_DWORDS; i++) {
reqMsg.transactionId[i] = rand();
}
SOCKADDR_IN stunAddr = {};
stunAddr.sin_family = AF_INET;
stunAddr.sin_port = htons(STUN_PORT);
stunAddr.sin_addr = *(struct in_addr*)host->h_addr;
// We'll connect() even for UDP so we can use send()/recv() and share more code
if (connect(sock, (struct sockaddr*)&stunAddr, sizeof(stunAddr)) == SOCKET_ERROR) {
printf("connect() failed: %d\n", WSAGetLastError());
closesocket(sock);
return false;
}
// For UDP, we'll do 3 iterations of 1 second each. For TCP,
// we'll do one iteration with a 3 second wait.
if (proto == IPPROTO_TCP) {
tries = 1;
timeout = STUN_RECV_TIMEOUT_SEC;
}
else {
tries = STUN_RECV_TIMEOUT_SEC;
timeout = 1;
}
bytesRead = SOCKET_ERROR;
for (i = 0; i < tries; i++) {
// Retransmit the request every second until the timeout elapses
if (send(sock, (char *)&reqMsg, sizeof(reqMsg), 0) == SOCKET_ERROR) {
printf("send() failed: %d\n", WSAGetLastError());
closesocket(sock);
return false;
}
fd_set fds;
FD_ZERO(&fds);
FD_SET(sock, &fds);
struct timeval tv;
tv.tv_sec = timeout;
tv.tv_usec = 0;
int selectRes = select(0, &fds, nullptr, nullptr, &tv);
if (selectRes == 0) {
// Timeout - continue looping
continue;
}
else if (selectRes == SOCKET_ERROR) {
printf("select() failed: %d\n", WSAGetLastError());
closesocket(sock);
return false;
}
// Error handling is below
bytesRead = recv(sock, resp.buf, sizeof(resp.buf), 0);
break;
}
closesocket(sock);
if (bytesRead == 0) {
printf("No response from STUN server\n");
return false;
}
else if (bytesRead == SOCKET_ERROR) {
printf("Failed to read STUN binding response: %d\n", WSAGetLastError());
return false;
}
else if (bytesRead < sizeof(resp.hdr)) {
printf("STUN message truncated: %d\n", bytesRead);
return false;
}
else if (htonl(resp.hdr.magicCookie) != STUN_MESSAGE_COOKIE) {
printf("Bad STUN cookie value: %x\n", htonl(resp.hdr.magicCookie));
return false;
}
else if (memcmp(reqMsg.transactionId, resp.hdr.transactionId, sizeof(reqMsg.transactionId))) {
printf("STUN transaction ID mismatch\n");
return false;
}
else if (htons(resp.hdr.messageType) != STUN_MESSAGE_BINDING_SUCCESS) {
printf("STUN message type mismatch: %x\n", htons(resp.hdr.messageType));
return false;
}
attribute = (PSTUN_ATTRIBUTE_HEADER)(&resp.hdr + 1);
bytesRead -= sizeof(resp.hdr);
while (bytesRead > sizeof(*attribute)) {
if (bytesRead < sizeof(*attribute) + htons(attribute->length)) {
printf("STUN attribute out of bounds: %d\n", htons(attribute->length));
return false;
}
else if (htons(attribute->type) != STUN_ATTRIBUTE_XOR_MAPPED_ADDRESS) {
// Continue searching if this wasn't our address
bytesRead -= sizeof(*attribute) + htons(attribute->length);
attribute = (PSTUN_ATTRIBUTE_HEADER)(((char*)attribute) + sizeof(*attribute) + htons(attribute->length));
continue;
}
ipv4Attrib = (PSTUN_MAPPED_IPV4_ADDRESS_ATTRIBUTE)attribute;
if (htons(ipv4Attrib->hdr.length) != 8) {
printf("STUN address length mismatch: %d\n", htons(ipv4Attrib->hdr.length));
return false;
}
else if (ipv4Attrib->addressFamily != 1) {
printf("STUN address family mismatch: %x\n", ipv4Attrib->addressFamily);
return false;
}
*wanAddr = {};
wanAddr->sin_family = AF_INET;
// The address and port are XORed with the cookie
wanAddr->sin_port = ipv4Attrib->port ^ (short)resp.hdr.magicCookie;
wanAddr->sin_addr.S_un.S_addr = ipv4Attrib->address ^ resp.hdr.magicCookie;
return true;
}
printf("No XOR mapped address found in STUN response!\n");
return false;
}
+4 -2
View File
@@ -1,5 +1,7 @@
#pragma once
#define VER_VERSION 2,1,0,0
#define VER_VERSION_STR "2.1.0.0"
#define VER_COMPANYNAME_STR "Moonlight Game Streaming Project"
#define VER_FILEVERSION 1,1,0,0
#define VER_FILEVERSION_STR "1.1.0.0\0"
#define VER_PRODUCTNAME_STR "Moonlight Internet Streaming Helper"