diff --git a/EvilClippy.csproj b/EvilClippy.csproj
new file mode 100644
index 0000000..9cbd92f
--- /dev/null
+++ b/EvilClippy.csproj
@@ -0,0 +1,77 @@
+
+
+
+
+
+ Debug
+ AnyCPU
+ {F0652120-9CF5-4F4C-BC7B-BA0921AA57CB}
+ Exe
+ EvilClippy
+ EvilClippy
+ v4.5
+ 512
+ true
+
+
+
+
+
+ AnyCPU
+ true
+ full
+ false
+ bin\Debug\
+ DEBUG;TRACE
+ prompt
+ 4
+ false
+
+
+ AnyCPU
+ pdbonly
+ true
+ bin\Release\
+ TRACE
+ prompt
+ 4
+ false
+
+
+
+
+
+
+
+
+
+
+
+
+
+ packages\Costura.Fody.3.3.3\lib\net40\Costura.dll
+
+
+ packages\OpenMcdf.2.2.1.3\lib\net40\OpenMcdf.dll
+
+
+
+
+ False
+ C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.ComponentModel.TypeConverter.dll
+
+
+
+
+
+
+
+
+
+
+ This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.
+
+
+
+
+
\ No newline at end of file
diff --git a/EvilClippy.sln b/EvilClippy.sln
new file mode 100644
index 0000000..56855b8
--- /dev/null
+++ b/EvilClippy.sln
@@ -0,0 +1,25 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio Version 16
+VisualStudioVersion = 16.0.31105.61
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EvilClippy", "EvilClippy.csproj", "{F0652120-9CF5-4F4C-BC7B-BA0921AA57CB}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Debug|Any CPU = Debug|Any CPU
+ Release|Any CPU = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {F0652120-9CF5-4F4C-BC7B-BA0921AA57CB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {F0652120-9CF5-4F4C-BC7B-BA0921AA57CB}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {F0652120-9CF5-4F4C-BC7B-BA0921AA57CB}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {F0652120-9CF5-4F4C-BC7B-BA0921AA57CB}.Release|Any CPU.Build.0 = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+ GlobalSection(ExtensibilityGlobals) = postSolution
+ SolutionGuid = {36EB9640-6923-4A99-84B3-E743C8361ACA}
+ EndGlobalSection
+EndGlobal
diff --git a/FodyWeavers.xml b/FodyWeavers.xml
new file mode 100644
index 0000000..a5dcf04
--- /dev/null
+++ b/FodyWeavers.xml
@@ -0,0 +1,4 @@
+
+
+
+
\ No newline at end of file
diff --git a/FodyWeavers.xsd b/FodyWeavers.xsd
new file mode 100644
index 0000000..44a5374
--- /dev/null
+++ b/FodyWeavers.xsd
@@ -0,0 +1,111 @@
+
+
+
+
+
+
+
+
+
+
+
+ A list of assembly names to exclude from the default action of "embed all Copy Local references", delimited with line breaks
+
+
+
+
+ A list of assembly names to include from the default action of "embed all Copy Local references", delimited with line breaks.
+
+
+
+
+ A list of unmanaged 32 bit assembly names to include, delimited with line breaks.
+
+
+
+
+ A list of unmanaged 64 bit assembly names to include, delimited with line breaks.
+
+
+
+
+ The order of preloaded assemblies, delimited with line breaks.
+
+
+
+
+
+ This will copy embedded files to disk before loading them into memory. This is helpful for some scenarios that expected an assembly to be loaded from a physical file.
+
+
+
+
+ Controls if .pdbs for reference assemblies are also embedded.
+
+
+
+
+ Embedded assemblies are compressed by default, and uncompressed when they are loaded. You can turn compression off with this option.
+
+
+
+
+ As part of Costura, embedded assemblies are no longer included as part of the build. This cleanup can be turned off.
+
+
+
+
+ Costura by default will load as part of the module initialization. This flag disables that behavior. Make sure you call CosturaUtility.Initialize() somewhere in your code.
+
+
+
+
+ Costura will by default use assemblies with a name like 'resources.dll' as a satellite resource and prepend the output path. This flag disables that behavior.
+
+
+
+
+ A list of assembly names to exclude from the default action of "embed all Copy Local references", delimited with |
+
+
+
+
+ A list of assembly names to include from the default action of "embed all Copy Local references", delimited with |.
+
+
+
+
+ A list of unmanaged 32 bit assembly names to include, delimited with |.
+
+
+
+
+ A list of unmanaged 64 bit assembly names to include, delimited with |.
+
+
+
+
+ The order of preloaded assemblies, delimited with |.
+
+
+
+
+
+
+
+ 'true' to run assembly verification (PEVerify) on the target assembly after all weavers have been executed.
+
+
+
+
+ A comma-separated list of error codes that can be safely ignored in assembly verification.
+
+
+
+
+ 'false' to turn off automatic generation of the XML Schema file.
+
+
+
+
+
\ No newline at end of file
diff --git a/LICENSE.md b/LICENSE.md
deleted file mode 100644
index f288702..0000000
--- a/LICENSE.md
+++ /dev/null
@@ -1,674 +0,0 @@
- GNU GENERAL PUBLIC LICENSE
- Version 3, 29 June 2007
-
- Copyright (C) 2007 Free Software Foundation, Inc.
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
- Preamble
-
- The GNU General Public License is a free, copyleft license for
-software and other kinds of works.
-
- The licenses for most software and other practical works are designed
-to take away your freedom to share and change the works. By contrast,
-the GNU General Public License is intended to guarantee your freedom to
-share and change all versions of a program--to make sure it remains free
-software for all its users. We, the Free Software Foundation, use the
-GNU General Public License for most of our software; it applies also to
-any other work released this way by its authors. You can apply it to
-your programs, too.
-
- When we speak of free software, we are referring to freedom, not
-price. Our General Public Licenses are designed to make sure that you
-have the freedom to distribute copies of free software (and charge for
-them if you wish), that you receive source code or can get it if you
-want it, that you can change the software or use pieces of it in new
-free programs, and that you know you can do these things.
-
- To protect your rights, we need to prevent others from denying you
-these rights or asking you to surrender the rights. Therefore, you have
-certain responsibilities if you distribute copies of the software, or if
-you modify it: responsibilities to respect the freedom of others.
-
- For example, if you distribute copies of such a program, whether
-gratis or for a fee, you must pass on to the recipients the same
-freedoms that you received. You must make sure that they, too, receive
-or can get the source code. And you must show them these terms so they
-know their rights.
-
- Developers that use the GNU GPL protect your rights with two steps:
-(1) assert copyright on the software, and (2) offer you this License
-giving you legal permission to copy, distribute and/or modify it.
-
- For the developers' and authors' protection, the GPL clearly explains
-that there is no warranty for this free software. For both users' and
-authors' sake, the GPL requires that modified versions be marked as
-changed, so that their problems will not be attributed erroneously to
-authors of previous versions.
-
- Some devices are designed to deny users access to install or run
-modified versions of the software inside them, although the manufacturer
-can do so. This is fundamentally incompatible with the aim of
-protecting users' freedom to change the software. The systematic
-pattern of such abuse occurs in the area of products for individuals to
-use, which is precisely where it is most unacceptable. Therefore, we
-have designed this version of the GPL to prohibit the practice for those
-products. If such problems arise substantially in other domains, we
-stand ready to extend this provision to those domains in future versions
-of the GPL, as needed to protect the freedom of users.
-
- Finally, every program is threatened constantly by software patents.
-States should not allow patents to restrict development and use of
-software on general-purpose computers, but in those that do, we wish to
-avoid the special danger that patents applied to a free program could
-make it effectively proprietary. To prevent this, the GPL assures that
-patents cannot be used to render the program non-free.
-
- The precise terms and conditions for copying, distribution and
-modification follow.
-
- TERMS AND CONDITIONS
-
- 0. Definitions.
-
- "This License" refers to version 3 of the GNU General Public License.
-
- "Copyright" also means copyright-like laws that apply to other kinds of
-works, such as semiconductor masks.
-
- "The Program" refers to any copyrightable work licensed under this
-License. Each licensee is addressed as "you". "Licensees" and
-"recipients" may be individuals or organizations.
-
- To "modify" a work means to copy from or adapt all or part of the work
-in a fashion requiring copyright permission, other than the making of an
-exact copy. The resulting work is called a "modified version" of the
-earlier work or a work "based on" the earlier work.
-
- A "covered work" means either the unmodified Program or a work based
-on the Program.
-
- To "propagate" a work means to do anything with it that, without
-permission, would make you directly or secondarily liable for
-infringement under applicable copyright law, except executing it on a
-computer or modifying a private copy. Propagation includes copying,
-distribution (with or without modification), making available to the
-public, and in some countries other activities as well.
-
- To "convey" a work means any kind of propagation that enables other
-parties to make or receive copies. Mere interaction with a user through
-a computer network, with no transfer of a copy, is not conveying.
-
- An interactive user interface displays "Appropriate Legal Notices"
-to the extent that it includes a convenient and prominently visible
-feature that (1) displays an appropriate copyright notice, and (2)
-tells the user that there is no warranty for the work (except to the
-extent that warranties are provided), that licensees may convey the
-work under this License, and how to view a copy of this License. If
-the interface presents a list of user commands or options, such as a
-menu, a prominent item in the list meets this criterion.
-
- 1. Source Code.
-
- The "source code" for a work means the preferred form of the work
-for making modifications to it. "Object code" means any non-source
-form of a work.
-
- A "Standard Interface" means an interface that either is an official
-standard defined by a recognized standards body, or, in the case of
-interfaces specified for a particular programming language, one that
-is widely used among developers working in that language.
-
- The "System Libraries" of an executable work include anything, other
-than the work as a whole, that (a) is included in the normal form of
-packaging a Major Component, but which is not part of that Major
-Component, and (b) serves only to enable use of the work with that
-Major Component, or to implement a Standard Interface for which an
-implementation is available to the public in source code form. A
-"Major Component", in this context, means a major essential component
-(kernel, window system, and so on) of the specific operating system
-(if any) on which the executable work runs, or a compiler used to
-produce the work, or an object code interpreter used to run it.
-
- The "Corresponding Source" for a work in object code form means all
-the source code needed to generate, install, and (for an executable
-work) run the object code and to modify the work, including scripts to
-control those activities. However, it does not include the work's
-System Libraries, or general-purpose tools or generally available free
-programs which are used unmodified in performing those activities but
-which are not part of the work. For example, Corresponding Source
-includes interface definition files associated with source files for
-the work, and the source code for shared libraries and dynamically
-linked subprograms that the work is specifically designed to require,
-such as by intimate data communication or control flow between those
-subprograms and other parts of the work.
-
- The Corresponding Source need not include anything that users
-can regenerate automatically from other parts of the Corresponding
-Source.
-
- The Corresponding Source for a work in source code form is that
-same work.
-
- 2. Basic Permissions.
-
- All rights granted under this License are granted for the term of
-copyright on the Program, and are irrevocable provided the stated
-conditions are met. This License explicitly affirms your unlimited
-permission to run the unmodified Program. The output from running a
-covered work is covered by this License only if the output, given its
-content, constitutes a covered work. This License acknowledges your
-rights of fair use or other equivalent, as provided by copyright law.
-
- You may make, run and propagate covered works that you do not
-convey, without conditions so long as your license otherwise remains
-in force. You may convey covered works to others for the sole purpose
-of having them make modifications exclusively for you, or provide you
-with facilities for running those works, provided that you comply with
-the terms of this License in conveying all material for which you do
-not control copyright. Those thus making or running the covered works
-for you must do so exclusively on your behalf, under your direction
-and control, on terms that prohibit them from making any copies of
-your copyrighted material outside their relationship with you.
-
- Conveying under any other circumstances is permitted solely under
-the conditions stated below. Sublicensing is not allowed; section 10
-makes it unnecessary.
-
- 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
-
- No covered work shall be deemed part of an effective technological
-measure under any applicable law fulfilling obligations under article
-11 of the WIPO copyright treaty adopted on 20 December 1996, or
-similar laws prohibiting or restricting circumvention of such
-measures.
-
- When you convey a covered work, you waive any legal power to forbid
-circumvention of technological measures to the extent such circumvention
-is effected by exercising rights under this License with respect to
-the covered work, and you disclaim any intention to limit operation or
-modification of the work as a means of enforcing, against the work's
-users, your or third parties' legal rights to forbid circumvention of
-technological measures.
-
- 4. Conveying Verbatim Copies.
-
- You may convey verbatim copies of the Program's source code as you
-receive it, in any medium, provided that you conspicuously and
-appropriately publish on each copy an appropriate copyright notice;
-keep intact all notices stating that this License and any
-non-permissive terms added in accord with section 7 apply to the code;
-keep intact all notices of the absence of any warranty; and give all
-recipients a copy of this License along with the Program.
-
- You may charge any price or no price for each copy that you convey,
-and you may offer support or warranty protection for a fee.
-
- 5. Conveying Modified Source Versions.
-
- You may convey a work based on the Program, or the modifications to
-produce it from the Program, in the form of source code under the
-terms of section 4, provided that you also meet all of these conditions:
-
- a) The work must carry prominent notices stating that you modified
- it, and giving a relevant date.
-
- b) The work must carry prominent notices stating that it is
- released under this License and any conditions added under section
- 7. This requirement modifies the requirement in section 4 to
- "keep intact all notices".
-
- c) You must license the entire work, as a whole, under this
- License to anyone who comes into possession of a copy. This
- License will therefore apply, along with any applicable section 7
- additional terms, to the whole of the work, and all its parts,
- regardless of how they are packaged. This License gives no
- permission to license the work in any other way, but it does not
- invalidate such permission if you have separately received it.
-
- d) If the work has interactive user interfaces, each must display
- Appropriate Legal Notices; however, if the Program has interactive
- interfaces that do not display Appropriate Legal Notices, your
- work need not make them do so.
-
- A compilation of a covered work with other separate and independent
-works, which are not by their nature extensions of the covered work,
-and which are not combined with it such as to form a larger program,
-in or on a volume of a storage or distribution medium, is called an
-"aggregate" if the compilation and its resulting copyright are not
-used to limit the access or legal rights of the compilation's users
-beyond what the individual works permit. Inclusion of a covered work
-in an aggregate does not cause this License to apply to the other
-parts of the aggregate.
-
- 6. Conveying Non-Source Forms.
-
- You may convey a covered work in object code form under the terms
-of sections 4 and 5, provided that you also convey the
-machine-readable Corresponding Source under the terms of this License,
-in one of these ways:
-
- a) Convey the object code in, or embodied in, a physical product
- (including a physical distribution medium), accompanied by the
- Corresponding Source fixed on a durable physical medium
- customarily used for software interchange.
-
- b) Convey the object code in, or embodied in, a physical product
- (including a physical distribution medium), accompanied by a
- written offer, valid for at least three years and valid for as
- long as you offer spare parts or customer support for that product
- model, to give anyone who possesses the object code either (1) a
- copy of the Corresponding Source for all the software in the
- product that is covered by this License, on a durable physical
- medium customarily used for software interchange, for a price no
- more than your reasonable cost of physically performing this
- conveying of source, or (2) access to copy the
- Corresponding Source from a network server at no charge.
-
- c) Convey individual copies of the object code with a copy of the
- written offer to provide the Corresponding Source. This
- alternative is allowed only occasionally and noncommercially, and
- only if you received the object code with such an offer, in accord
- with subsection 6b.
-
- d) Convey the object code by offering access from a designated
- place (gratis or for a charge), and offer equivalent access to the
- Corresponding Source in the same way through the same place at no
- further charge. You need not require recipients to copy the
- Corresponding Source along with the object code. If the place to
- copy the object code is a network server, the Corresponding Source
- may be on a different server (operated by you or a third party)
- that supports equivalent copying facilities, provided you maintain
- clear directions next to the object code saying where to find the
- Corresponding Source. Regardless of what server hosts the
- Corresponding Source, you remain obligated to ensure that it is
- available for as long as needed to satisfy these requirements.
-
- e) Convey the object code using peer-to-peer transmission, provided
- you inform other peers where the object code and Corresponding
- Source of the work are being offered to the general public at no
- charge under subsection 6d.
-
- A separable portion of the object code, whose source code is excluded
-from the Corresponding Source as a System Library, need not be
-included in conveying the object code work.
-
- A "User Product" is either (1) a "consumer product", which means any
-tangible personal property which is normally used for personal, family,
-or household purposes, or (2) anything designed or sold for incorporation
-into a dwelling. In determining whether a product is a consumer product,
-doubtful cases shall be resolved in favor of coverage. For a particular
-product received by a particular user, "normally used" refers to a
-typical or common use of that class of product, regardless of the status
-of the particular user or of the way in which the particular user
-actually uses, or expects or is expected to use, the product. A product
-is a consumer product regardless of whether the product has substantial
-commercial, industrial or non-consumer uses, unless such uses represent
-the only significant mode of use of the product.
-
- "Installation Information" for a User Product means any methods,
-procedures, authorization keys, or other information required to install
-and execute modified versions of a covered work in that User Product from
-a modified version of its Corresponding Source. The information must
-suffice to ensure that the continued functioning of the modified object
-code is in no case prevented or interfered with solely because
-modification has been made.
-
- If you convey an object code work under this section in, or with, or
-specifically for use in, a User Product, and the conveying occurs as
-part of a transaction in which the right of possession and use of the
-User Product is transferred to the recipient in perpetuity or for a
-fixed term (regardless of how the transaction is characterized), the
-Corresponding Source conveyed under this section must be accompanied
-by the Installation Information. But this requirement does not apply
-if neither you nor any third party retains the ability to install
-modified object code on the User Product (for example, the work has
-been installed in ROM).
-
- The requirement to provide Installation Information does not include a
-requirement to continue to provide support service, warranty, or updates
-for a work that has been modified or installed by the recipient, or for
-the User Product in which it has been modified or installed. Access to a
-network may be denied when the modification itself materially and
-adversely affects the operation of the network or violates the rules and
-protocols for communication across the network.
-
- Corresponding Source conveyed, and Installation Information provided,
-in accord with this section must be in a format that is publicly
-documented (and with an implementation available to the public in
-source code form), and must require no special password or key for
-unpacking, reading or copying.
-
- 7. Additional Terms.
-
- "Additional permissions" are terms that supplement the terms of this
-License by making exceptions from one or more of its conditions.
-Additional permissions that are applicable to the entire Program shall
-be treated as though they were included in this License, to the extent
-that they are valid under applicable law. If additional permissions
-apply only to part of the Program, that part may be used separately
-under those permissions, but the entire Program remains governed by
-this License without regard to the additional permissions.
-
- When you convey a copy of a covered work, you may at your option
-remove any additional permissions from that copy, or from any part of
-it. (Additional permissions may be written to require their own
-removal in certain cases when you modify the work.) You may place
-additional permissions on material, added by you to a covered work,
-for which you have or can give appropriate copyright permission.
-
- Notwithstanding any other provision of this License, for material you
-add to a covered work, you may (if authorized by the copyright holders of
-that material) supplement the terms of this License with terms:
-
- a) Disclaiming warranty or limiting liability differently from the
- terms of sections 15 and 16 of this License; or
-
- b) Requiring preservation of specified reasonable legal notices or
- author attributions in that material or in the Appropriate Legal
- Notices displayed by works containing it; or
-
- c) Prohibiting misrepresentation of the origin of that material, or
- requiring that modified versions of such material be marked in
- reasonable ways as different from the original version; or
-
- d) Limiting the use for publicity purposes of names of licensors or
- authors of the material; or
-
- e) Declining to grant rights under trademark law for use of some
- trade names, trademarks, or service marks; or
-
- f) Requiring indemnification of licensors and authors of that
- material by anyone who conveys the material (or modified versions of
- it) with contractual assumptions of liability to the recipient, for
- any liability that these contractual assumptions directly impose on
- those licensors and authors.
-
- All other non-permissive additional terms are considered "further
-restrictions" within the meaning of section 10. If the Program as you
-received it, or any part of it, contains a notice stating that it is
-governed by this License along with a term that is a further
-restriction, you may remove that term. If a license document contains
-a further restriction but permits relicensing or conveying under this
-License, you may add to a covered work material governed by the terms
-of that license document, provided that the further restriction does
-not survive such relicensing or conveying.
-
- If you add terms to a covered work in accord with this section, you
-must place, in the relevant source files, a statement of the
-additional terms that apply to those files, or a notice indicating
-where to find the applicable terms.
-
- Additional terms, permissive or non-permissive, may be stated in the
-form of a separately written license, or stated as exceptions;
-the above requirements apply either way.
-
- 8. Termination.
-
- You may not propagate or modify a covered work except as expressly
-provided under this License. Any attempt otherwise to propagate or
-modify it is void, and will automatically terminate your rights under
-this License (including any patent licenses granted under the third
-paragraph of section 11).
-
- However, if you cease all violation of this License, then your
-license from a particular copyright holder is reinstated (a)
-provisionally, unless and until the copyright holder explicitly and
-finally terminates your license, and (b) permanently, if the copyright
-holder fails to notify you of the violation by some reasonable means
-prior to 60 days after the cessation.
-
- Moreover, your license from a particular copyright holder is
-reinstated permanently if the copyright holder notifies you of the
-violation by some reasonable means, this is the first time you have
-received notice of violation of this License (for any work) from that
-copyright holder, and you cure the violation prior to 30 days after
-your receipt of the notice.
-
- Termination of your rights under this section does not terminate the
-licenses of parties who have received copies or rights from you under
-this License. If your rights have been terminated and not permanently
-reinstated, you do not qualify to receive new licenses for the same
-material under section 10.
-
- 9. Acceptance Not Required for Having Copies.
-
- You are not required to accept this License in order to receive or
-run a copy of the Program. Ancillary propagation of a covered work
-occurring solely as a consequence of using peer-to-peer transmission
-to receive a copy likewise does not require acceptance. However,
-nothing other than this License grants you permission to propagate or
-modify any covered work. These actions infringe copyright if you do
-not accept this License. Therefore, by modifying or propagating a
-covered work, you indicate your acceptance of this License to do so.
-
- 10. Automatic Licensing of Downstream Recipients.
-
- Each time you convey a covered work, the recipient automatically
-receives a license from the original licensors, to run, modify and
-propagate that work, subject to this License. You are not responsible
-for enforcing compliance by third parties with this License.
-
- An "entity transaction" is a transaction transferring control of an
-organization, or substantially all assets of one, or subdividing an
-organization, or merging organizations. If propagation of a covered
-work results from an entity transaction, each party to that
-transaction who receives a copy of the work also receives whatever
-licenses to the work the party's predecessor in interest had or could
-give under the previous paragraph, plus a right to possession of the
-Corresponding Source of the work from the predecessor in interest, if
-the predecessor has it or can get it with reasonable efforts.
-
- You may not impose any further restrictions on the exercise of the
-rights granted or affirmed under this License. For example, you may
-not impose a license fee, royalty, or other charge for exercise of
-rights granted under this License, and you may not initiate litigation
-(including a cross-claim or counterclaim in a lawsuit) alleging that
-any patent claim is infringed by making, using, selling, offering for
-sale, or importing the Program or any portion of it.
-
- 11. Patents.
-
- A "contributor" is a copyright holder who authorizes use under this
-License of the Program or a work on which the Program is based. The
-work thus licensed is called the contributor's "contributor version".
-
- A contributor's "essential patent claims" are all patent claims
-owned or controlled by the contributor, whether already acquired or
-hereafter acquired, that would be infringed by some manner, permitted
-by this License, of making, using, or selling its contributor version,
-but do not include claims that would be infringed only as a
-consequence of further modification of the contributor version. For
-purposes of this definition, "control" includes the right to grant
-patent sublicenses in a manner consistent with the requirements of
-this License.
-
- Each contributor grants you a non-exclusive, worldwide, royalty-free
-patent license under the contributor's essential patent claims, to
-make, use, sell, offer for sale, import and otherwise run, modify and
-propagate the contents of its contributor version.
-
- In the following three paragraphs, a "patent license" is any express
-agreement or commitment, however denominated, not to enforce a patent
-(such as an express permission to practice a patent or covenant not to
-sue for patent infringement). To "grant" such a patent license to a
-party means to make such an agreement or commitment not to enforce a
-patent against the party.
-
- If you convey a covered work, knowingly relying on a patent license,
-and the Corresponding Source of the work is not available for anyone
-to copy, free of charge and under the terms of this License, through a
-publicly available network server or other readily accessible means,
-then you must either (1) cause the Corresponding Source to be so
-available, or (2) arrange to deprive yourself of the benefit of the
-patent license for this particular work, or (3) arrange, in a manner
-consistent with the requirements of this License, to extend the patent
-license to downstream recipients. "Knowingly relying" means you have
-actual knowledge that, but for the patent license, your conveying the
-covered work in a country, or your recipient's use of the covered work
-in a country, would infringe one or more identifiable patents in that
-country that you have reason to believe are valid.
-
- If, pursuant to or in connection with a single transaction or
-arrangement, you convey, or propagate by procuring conveyance of, a
-covered work, and grant a patent license to some of the parties
-receiving the covered work authorizing them to use, propagate, modify
-or convey a specific copy of the covered work, then the patent license
-you grant is automatically extended to all recipients of the covered
-work and works based on it.
-
- A patent license is "discriminatory" if it does not include within
-the scope of its coverage, prohibits the exercise of, or is
-conditioned on the non-exercise of one or more of the rights that are
-specifically granted under this License. You may not convey a covered
-work if you are a party to an arrangement with a third party that is
-in the business of distributing software, under which you make payment
-to the third party based on the extent of your activity of conveying
-the work, and under which the third party grants, to any of the
-parties who would receive the covered work from you, a discriminatory
-patent license (a) in connection with copies of the covered work
-conveyed by you (or copies made from those copies), or (b) primarily
-for and in connection with specific products or compilations that
-contain the covered work, unless you entered into that arrangement,
-or that patent license was granted, prior to 28 March 2007.
-
- Nothing in this License shall be construed as excluding or limiting
-any implied license or other defenses to infringement that may
-otherwise be available to you under applicable patent law.
-
- 12. No Surrender of Others' Freedom.
-
- If conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License. If you cannot convey a
-covered work so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you may
-not convey it at all. For example, if you agree to terms that obligate you
-to collect a royalty for further conveying from those to whom you convey
-the Program, the only way you could satisfy both those terms and this
-License would be to refrain entirely from conveying the Program.
-
- 13. Use with the GNU Affero General Public License.
-
- Notwithstanding any other provision of this License, you have
-permission to link or combine any covered work with a work licensed
-under version 3 of the GNU Affero General Public License into a single
-combined work, and to convey the resulting work. The terms of this
-License will continue to apply to the part which is the covered work,
-but the special requirements of the GNU Affero General Public License,
-section 13, concerning interaction through a network will apply to the
-combination as such.
-
- 14. Revised Versions of this License.
-
- The Free Software Foundation may publish revised and/or new versions of
-the GNU General Public License from time to time. Such new versions will
-be similar in spirit to the present version, but may differ in detail to
-address new problems or concerns.
-
- Each version is given a distinguishing version number. If the
-Program specifies that a certain numbered version of the GNU General
-Public License "or any later version" applies to it, you have the
-option of following the terms and conditions either of that numbered
-version or of any later version published by the Free Software
-Foundation. If the Program does not specify a version number of the
-GNU General Public License, you may choose any version ever published
-by the Free Software Foundation.
-
- If the Program specifies that a proxy can decide which future
-versions of the GNU General Public License can be used, that proxy's
-public statement of acceptance of a version permanently authorizes you
-to choose that version for the Program.
-
- Later license versions may give you additional or different
-permissions. However, no additional obligations are imposed on any
-author or copyright holder as a result of your choosing to follow a
-later version.
-
- 15. Disclaimer of Warranty.
-
- THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
-APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
-HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
-OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
-THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
-IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
-ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
-
- 16. Limitation of Liability.
-
- IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
-THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
-GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
-USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
-DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
-PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
-EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
-SUCH DAMAGES.
-
- 17. Interpretation of Sections 15 and 16.
-
- If the disclaimer of warranty and limitation of liability provided
-above cannot be given local legal effect according to their terms,
-reviewing courts shall apply local law that most closely approximates
-an absolute waiver of all civil liability in connection with the
-Program, unless a warranty or assumption of liability accompanies a
-copy of the Program in return for a fee.
-
- END OF TERMS AND CONDITIONS
-
- How to Apply These Terms to Your New Programs
-
- If you develop a new program, and you want it to be of the greatest
-possible use to the public, the best way to achieve this is to make it
-free software which everyone can redistribute and change under these terms.
-
- To do so, attach the following notices to the program. It is safest
-to attach them to the start of each source file to most effectively
-state the exclusion of warranty; and each file should have at least
-the "copyright" line and a pointer to where the full notice is found.
-
-
- Copyright (C)
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see .
-
-Also add information on how to contact you by electronic and paper mail.
-
- If the program does terminal interaction, make it output a short
-notice like this when it starts in an interactive mode:
-
- Copyright (C)
- This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
- This is free software, and you are welcome to redistribute it
- under certain conditions; type `show c' for details.
-
-The hypothetical commands `show w' and `show c' should show the appropriate
-parts of the General Public License. Of course, your program's commands
-might be different; for a GUI interface, you would use an "about box".
-
- You should also get your employer (if you work as a programmer) or school,
-if any, to sign a "copyright disclaimer" for the program, if necessary.
-For more information on this, and how to apply and follow the GNU GPL, see
-.
-
- The GNU General Public License does not permit incorporating your program
-into proprietary programs. If your program is a subroutine library, you
-may consider it more useful to permit linking proprietary applications with
-the library. If this is what you want to do, use the GNU Lesser General
-Public License instead of this License. But first, please read
-.
diff --git a/OpenMcdf.dll b/OpenMcdf.dll
deleted file mode 100644
index ae49629..0000000
Binary files a/OpenMcdf.dll and /dev/null differ
diff --git a/app.config b/app.config
new file mode 100644
index 0000000..51278a4
--- /dev/null
+++ b/app.config
@@ -0,0 +1,3 @@
+
+
+
diff --git a/compression.cs b/compression.cs
index 337f833..83320b7 100644
--- a/compression.cs
+++ b/compression.cs
@@ -21,9 +21,9 @@ internal class CompressedChunk
{
internal CompressedChunk(DecompressedChunk decompressedChunk)
{
-// Contract.Requires(decompressedChunk != null);
-// Contract.Ensures(Header != null);
-// Contract.Ensures(ChunkData != null);
+ // Contract.Requires(decompressedChunk != null);
+ // Contract.Ensures(Header != null);
+ // Contract.Ensures(ChunkData != null);
ChunkData = new CompressedChunkData(decompressedChunk);
if (ChunkData.Size >= Globals.MaxBytesPerChunk)
@@ -35,9 +35,9 @@ internal CompressedChunk(DecompressedChunk decompressedChunk)
internal CompressedChunk(BinaryReader dataReader)
{
-// Contract.Requires(dataReader != null);
-// Contract.Ensures(Header != null);
-// Contract.Ensures(ChunkData != null);
+ // Contract.Requires(dataReader != null);
+ // Contract.Ensures(Header != null);
+ // Contract.Ensures(ChunkData != null);
Header = new CompressedChunkHeader(dataReader);
if (Header.IsCompressed)
@@ -86,8 +86,8 @@ internal class CompressedChunkData : IChunkData
internal CompressedChunkData(DecompressedChunk chunk)
{
-// Contract.Requires(chunk != null);
-
+ // Contract.Requires(chunk != null);
+
var tokens = Tokenizer.TokenizeUncompressedData(chunk.Data);
_tokensequences.AddRange(tokens.ToTokenSequences());
}
@@ -128,7 +128,7 @@ internal class CompressedChunkHeader
internal CompressedChunkHeader(IChunkData chunkData)
{
IsCompressed = chunkData is CompressedChunkData;
- CompressedChunkSize = (ushort) (chunkData.Size + 2);
+ CompressedChunkSize = (ushort)(chunkData.Size + 2);
}
internal CompressedChunkHeader(UInt16 header)
@@ -191,12 +191,12 @@ internal byte[] SerializeData()
private void ValidateChunkSizeAndCompressedFlag()
{
- if (IsCompressed
+ if (IsCompressed
&& CompressedChunkSize > 4098)
{
throw new Exception();
}
- if (!IsCompressed
+ if (!IsCompressed
&& CompressedChunkSize != 4098)
{
throw new Exception();
@@ -219,7 +219,7 @@ internal class CompressedContainer
private const byte SignatureByteSig = 0x1;
private readonly List _compressedChunks = new List();
-
+
internal CompressedContainer(byte[] compressedData)
{
var reader = new BinaryReader(new MemoryStream(compressedData));
@@ -259,7 +259,7 @@ internal byte[] SerializeData()
using (var reader = new BinaryReader(writer.BaseStream))
{
reader.BaseStream.Position = 0;
- return reader.ReadBytes((int) reader.BaseStream.Length);
+ return reader.ReadBytes((int)reader.BaseStream.Length);
}
}
}
@@ -530,7 +530,7 @@ internal byte[] Data
{
reader.BaseStream.Position = 0;
- return reader.ReadBytes((int) reader.BaseStream.Length);
+ return reader.ReadBytes((int)reader.BaseStream.Length);
}
}
}
@@ -578,7 +578,7 @@ internal DecompressedChunk(BinaryReader reader)
if (bytesToRead > Globals.MaxBytesPerChunk)
bytesToRead = Globals.MaxBytesPerChunk;
- Data = reader.ReadBytes((int) bytesToRead);
+ Data = reader.ReadBytes((int)bytesToRead);
}
internal byte[] Data { get; }
@@ -641,7 +641,7 @@ internal LiteralToken(BinaryReader dataReader)
internal LiteralToken(byte data)
{
- _data = new [] { data };
+ _data = new[] { data };
}
public void DecompressToken(BinaryWriter writer)
@@ -748,7 +748,7 @@ internal static bool OverlapsWith(this CopyToken thisToken, CopyToken otherToken
firstToken = otherToken;
secondToken = thisToken;
}
-// Contract.Assert(firstToken.Position <= secondToken.Position);
+ // Contract.Assert(firstToken.Position <= secondToken.Position);
return firstToken.Position + firstToken.Length > secondToken.Position;
}
@@ -805,7 +805,7 @@ private static IEnumerable AllPossibleCopyTokens(byte[] uncompressedD
UInt16 offset = 0;
UInt16 length = 0;
Match(uncompressedData, position, out offset, out length);
-
+
if (length > 0)
{
yield return new CopyToken(position, offset, length);
@@ -862,14 +862,14 @@ private static IEnumerable RemoveOverlappingTokens(IEnumerable(node != null);
+ // Contract.Requires(node != null);
// find any overlapping tokens
Node bestPath = null;
@@ -884,7 +884,7 @@ private static Node FindBestPath(Node node)
currentPath.NextNode = FindBestPath(nonOverlappingNode);
}
- if (bestPath == null
+ if (bestPath == null
|| bestPath.Length < currentPath.Length)
{
bestPath = currentPath;
@@ -895,11 +895,11 @@ private static Node FindBestPath(Node node)
private static IEnumerable GetOverlappingNodes(Node node)
{
-// Contract.Requires(node != null);
+ // Contract.Requires(node != null);
var firstNode = node;
- while (node != null
+ while (node != null
&& firstNode.Value.OverlapsWith(node.Value))
{
yield return node;
@@ -909,11 +909,11 @@ private static IEnumerable GetOverlappingNodes(Node node)
private static Node GetNextNonOverlappingNode(Node node)
{
-// Contract.Requires(node != null);
+ // Contract.Requires(node != null);
var firstNode = node;
- while (node != null
+ while (node != null
&& firstNode.Value.OverlapsWith(node.Value))
{
node = node.NextNode;
@@ -1018,7 +1018,7 @@ private class Node : IEnumerable
{
public Node(CopyToken value, Node nextNode)
{
-// Contract.Requires(value != null);
+ // Contract.Requires(value != null);
Value = value;
NextNode = nextNode;
@@ -1104,10 +1104,10 @@ internal class TokenSequence
public TokenSequence(IEnumerable enumerable) : this()
{
_tokens.AddRange(enumerable);
-
-// Contract.Assert(_tokens.Count > 0);
-// Contract.Assert(_tokens.Count <= 8);
-
+
+ // Contract.Assert(_tokens.Count > 0);
+ // Contract.Assert(_tokens.Count <= 8);
+
// set the flag byte.
for (var i = 0; i < _tokens.Count; i++)
{
diff --git a/evilclippy.cs b/evilclippy.cs
index a6ed0cf..8f911c1 100644
--- a/evilclippy.cs
+++ b/evilclippy.cs
@@ -1,4 +1,4 @@
-// EvilClippy
+// EvilClippy
// Cross-platform CFBF and MS-OVBA manipulation assistant
//
// Author: Stan Hegt (@StanHacked) / Outflank
@@ -33,19 +33,24 @@ public class MSOfficeManipulator
// Filename of the document that is about to be manipulated
static string filename = "";
- // Name of the generated output file.
- static string outFilename = "";
-
- // Compound file that is under editing
- static CompoundFile cf;
+ // Name of the generated output file.
+ static string outFilename = "";
+
+ static CFStorage vbaProjectCurStorage;
+ static CFStorage macrosStorage;
// Byte arrays for holding stream data of file
- static byte[] vbaProjectStream;
- static byte[] dirStream;
- static byte[] projectStream;
- static byte[] projectwmStream;
+ static CFStream vbaProjectStream;
+ static CFStream dirStream;
+ static CFStream projectStream;
+ static CFStream projectwmStream;
+
+ static byte[] vbaProjectStreamBytes;
+ static byte[] dirStreamBytes;
+ static byte[] projectStreamBytes;
+ static byte[] projectwmStreamBytes;
- static public void Main(string[] args)
+ static public void Main(string[] args)
{
// List of target VBA modules to stomp, if empty => all modules will be stomped
List targetModules = new List();
@@ -83,11 +88,11 @@ static public void Main(string[] args)
// Option to set locked/unviewable options in Project Stream
bool optionUnviewableVBA = false;
- // Option to set unlocked/viewable options in Project Stream
- bool optionViewableVBA = false;
+ // Option to set unlocked/viewable options in Project Stream
+ bool optionViewableVBA = false;
- // Temp path to unzip OpenXML files to
- String unzipTempPath = "";
+ // Temp path to unzip OpenXML files to
+ String unzipTempPath = "";
// Start parsing command line arguments
@@ -112,10 +117,10 @@ static public void Main(string[] args)
{ "rr|resetmodulenames", "Undo the set random module names by making the ASCII module names in the DIR stream match their Unicode counter parts",
v => optionResetModuleNames = v != null },
{ "u|unviewableVBA", "Make VBA Project unviewable/locked.",
- v => optionUnviewableVBA = v != null },
- { "uu|viewableVBA", "Make VBA Project viewable/unlocked.",
- v => optionViewableVBA = v != null },
- { "v", "Increase debug message verbosity.",
+ v => optionUnviewableVBA = v != null },
+ { "uu|viewableVBA", "Make VBA Project viewable/unlocked.",
+ v => optionViewableVBA = v != null },
+ { "v", "Increase debug message verbosity.",
v => { if (v != null) ++verbosity; } },
{ "h|help", "Show this message and exit.",
v => optionShowHelp = v != null },
@@ -149,135 +154,298 @@ static public void Main(string[] args)
}
// End parsing command line arguments
+ if(!File.Exists(filename))
+ {
+ Console.WriteLine($"[!] Input file does not exist: \"{filename}\" !");
+ return;
+ }
+
// OLE Filename (make a copy so we don't overwrite the original)
outFilename = getOutFilename(filename);
string oleFilename = outFilename;
- // Attempt to unzip as docm or xlsm OpenXML format
- try
- {
- unzipTempPath = CreateUniqueTempDirectory();
- ZipFile.ExtractToDirectory(filename, unzipTempPath);
- if (File.Exists(Path.Combine(unzipTempPath, "word", "vbaProject.bin"))) { oleFilename = Path.Combine(unzipTempPath, "word", "vbaProject.bin"); }
- else if (File.Exists(Path.Combine(unzipTempPath, "xl", "vbaProject.bin"))) { oleFilename = Path.Combine(unzipTempPath, "xl", "vbaProject.bin"); }
- is_OpenXML = true;
+ try
+ {
+ unzipTempPath = CreateUniqueTempDirectory();
+ ZipFile.ExtractToDirectory(filename, unzipTempPath);
+
+ if (File.Exists(Path.Combine(unzipTempPath, "word", "vbaProject.bin")))
+ {
+ oleFilename = Path.Combine(unzipTempPath, "word", "vbaProject.bin");
+ }
+ else if (File.Exists(Path.Combine(unzipTempPath, "xl", "vbaProject.bin")))
+ {
+ oleFilename = Path.Combine(unzipTempPath, "xl", "vbaProject.bin");
+ }
+ else if (File.Exists(Path.Combine(unzipTempPath, "ppt", "vbaProject.bin")))
+ {
+ oleFilename = Path.Combine(unzipTempPath, "ppt", "vbaProject.bin");
+ }
+
+ is_OpenXML = true;
+ }
+ catch (Exception e)
+ {
+ Console.WriteLine("Input file seems to be a 97-2003 Office document (OLE)");
+
+ // Not OpenXML format, Maybe 97-2003 format, Make a copy
+ if (File.Exists(outFilename)) File.Delete(outFilename);
+ File.Copy(filename, outFilename);
+ }
+
+ // Read relevant streams
+ CompoundFile cf = new CompoundFile(oleFilename, CFSUpdateMode.Update, 0);
+ CFStorage commonStorage = cf.RootStorage;
+
+ bool nestedVBA = false;
+ bool macrosStorageFlag = false;
+ bool vbaProjectCurHasProject = false;
+ CFStorage rootVbaStorage = null;
+
+ if (cf.RootStorage.TryGetStorage("Macros") != null)
+ {
+ commonStorage = cf.RootStorage.GetStorage("Macros");
+ macrosStorage = commonStorage;
+ macrosStorageFlag = true;
}
- catch (Exception)
+
+ else if (cf.RootStorage.TryGetStorage("_VBA_PROJECT_CUR") != null)
+ {
+ commonStorage = cf.RootStorage.GetStorage("_VBA_PROJECT_CUR");
+ vbaProjectCurStorage = commonStorage;
+
+ try
+ {
+ var foo = commonStorage.TryGetStorage("PROJECT");
+ vbaProjectCurHasProject = true;
+ }
+ catch (CFItemNotFound)
+ {
+ try
+ {
+ var foo = commonStorage.TryGetStorage("project");
+ vbaProjectCurHasProject = true;
+ }
+ catch (CFItemNotFound)
+ {
+ }
+
+ }
+ }
+
+ else if (cf.RootStorage.TryGetStorage("VBA") != null)
+ {
+ // Publisher: VBA -> VBA
+ rootVbaStorage = cf.RootStorage.GetStorage("VBA");
+
+ try
+ {
+ var foo = rootVbaStorage.GetStream("dir");
+ }
+ catch (CFItemNotFound ex) when (ex.Message.Contains("Cannot find item"))
+ {
+ nestedVBA = true;
+ commonStorage = rootVbaStorage;
+ }
+ }
+
+ var vbaStorage = commonStorage.GetStorage("VBA");
+ if (vbaStorage == null)
+ {
+ throw new CFItemNotFound("Cannot find item");
+ }
+
+ vbaProjectStream = vbaStorage.GetStream("_VBA_PROJECT");
+ byte[] vbaProjectStreamData = vbaProjectStream.GetData();
+
+ CFStorage storageForProject = (nestedVBA) ? rootVbaStorage : vbaStorage;
+
+ if (macrosStorageFlag)
{
- // Not OpenXML format, Maybe 97-2003 format, Make a copy
- if (File.Exists(outFilename)) File.Delete(outFilename);
- File.Copy(filename, outFilename);
+ storageForProject = commonStorage;
}
- // Open OLE compound file for editing
+ if(vbaProjectCurHasProject)
+ {
+ storageForProject = vbaProjectCurStorage;
+ }
+
try
{
- cf = new CompoundFile(oleFilename, CFSUpdateMode.Update, 0);
+ projectStream = storageForProject.GetStream("project");
+ projectStreamBytes = projectStream.GetData();
}
- catch (Exception e)
+ catch(Exception)
+ {
+ try
+ {
+ projectStream = storageForProject.GetStream("PROJECT");
+ projectStreamBytes = projectStream.GetData();
+ }
+ catch (Exception)
+ {
+ storageForProject = cf.RootStorage;
+ try
+ {
+ projectStream = storageForProject.GetStream("project");
+ projectStreamBytes = projectStream.GetData();
+ }
+ catch (Exception)
+ {
+ try
+ {
+ projectStream = storageForProject.GetStream("PROJECT");
+ projectStreamBytes = projectStream.GetData();
+ }
+ catch (Exception)
+ {
+ Console.WriteLine("[!] Giving up, could not find PROJECT stream! Format not recognized!");
+ System.Environment.Exit(1);
+ }
+ }
+ }
+ }
+
+ dirStream = vbaStorage.GetStream("dir");
+ dirStreamBytes = Decompress(dirStream.GetData());
+
+ // Read project streams as string
+ string projectStreamString = System.Text.Encoding.UTF8.GetString(projectStreamBytes);
+ string projectwmStreamString = "";
+
+ try
{
- Console.WriteLine("ERROR: Could not open file " + filename);
- Console.WriteLine("Please make sure this file exists and is .docm or .xlsm file or a .doc in the Office 97-2003 format.");
- Console.WriteLine();
- Console.WriteLine(e.Message);
- return;
+ try
+ {
+ projectwmStream = storageForProject.GetStream("projectwm");
+ projectwmStreamBytes = projectwmStream.GetData();
+ }
+ catch(Exception)
+ {
+ projectwmStream = storageForProject.GetStream("PROJECTwm");
+ projectwmStreamBytes = projectwmStream.GetData();
+ }
+
+ projectwmStreamString = System.Text.Encoding.UTF8.GetString(projectwmStreamBytes);
}
+ catch(System.Exception e)
+ {
+ Console.WriteLine("[-] Could not find projectwm stream.");
+ }
- // Read relevant streams
- CFStorage commonStorage = cf.RootStorage; // docm or xlsm
- if (cf.RootStorage.TryGetStorage("Macros") != null) commonStorage = cf.RootStorage.GetStorage("Macros"); // .doc
- if (cf.RootStorage.TryGetStorage("_VBA_PROJECT_CUR") != null) commonStorage = cf.RootStorage.GetStorage("_VBA_PROJECT_CUR"); // xls
- vbaProjectStream = commonStorage.GetStorage("VBA").GetStream("_VBA_PROJECT").GetData();
- projectStream = commonStorage.GetStream("project").GetData();
- projectwmStream = commonStorage.GetStream("projectwm").GetData();
- dirStream = Decompress(commonStorage.GetStorage("VBA").GetStream("dir").GetData());
- // Read project streams as string
- string projectStreamString = System.Text.Encoding.UTF8.GetString(projectStream);
- string projectwmStreamString = System.Text.Encoding.UTF8.GetString(projectwmStream);
- // Find all VBA modules in current file
- List vbaModules = ParseModulesFromDirStream(dirStream);
+ // Find all VBA modules in current file
+ List vbaModules = ParseModulesFromDirStream(dirStreamBytes);
// Write streams to debug log (if verbosity enabled)
- DebugLog("Hex dump of original _VBA_PROJECT stream:\n" + Utils.HexDump(vbaProjectStream));
- DebugLog("Hex dump of original dir stream:\n" + Utils.HexDump(dirStream));
- DebugLog("Hex dump of original project stream:\n" + Utils.HexDump(projectStream));
+ DebugLog("Hex dump of original _VBA_PROJECT stream:\n" + Utils.HexDump(vbaProjectStreamBytes));
+ DebugLog("Hex dump of original dir stream:\n" + Utils.HexDump(dirStreamBytes));
+ DebugLog("Hex dump of original PROJECT stream:\n" + Utils.HexDump(projectStreamBytes));
// Replace Office version in _VBA_PROJECT stream
if (targetOfficeVersion != "")
{
- ReplaceOfficeVersionInVBAProject(vbaProjectStream, targetOfficeVersion);
- commonStorage.GetStorage("VBA").GetStream("_VBA_PROJECT").SetData(vbaProjectStream);
+ ReplaceOfficeVersionInVBAProject(vbaProjectStreamBytes, targetOfficeVersion);
+ vbaProjectStream.SetData(vbaProjectStreamBytes);
+ }
+ //Set ProjectProtectionState and ProjectVisibilityState to locked/unviewable see https://docs.microsoft.com/en-us/openspecs/office_file_formats/ms-ovba/dfd72140-85a6-4f25-8a17-70a89c00db8c
+ if (optionUnviewableVBA)
+ {
+ string tmpStr = Regex.Replace(projectStreamString, "CMG=\".*\"", "CMG=\"\"");
+ string newProjectStreamString = Regex.Replace(tmpStr, "GC=\".*\"", "GC=\"\"");
+ // Write changes to project stream
+ projectStream.SetData(Encoding.UTF8.GetBytes(newProjectStreamString));
}
- //Set ProjectProtectionState and ProjectVisibilityState to locked/unviewable see https://docs.microsoft.com/en-us/openspecs/office_file_formats/ms-ovba/dfd72140-85a6-4f25-8a17-70a89c00db8c
- if (optionUnviewableVBA)
- {
- string tmpStr = Regex.Replace(projectStreamString, "CMG=\".*\"", "CMG=\"\"");
- string newProjectStreamString = Regex.Replace(tmpStr , "GC=\".*\"", "GC=\"\"" );
- // Write changes to project stream
- commonStorage.GetStream("project").SetData(Encoding.UTF8.GetBytes(newProjectStreamString));
- }
- //Set ProjectProtectionState and ProjectVisibilityState to be viewable see https://docs.microsoft.com/en-us/openspecs/office_file_formats/ms-ovba/dfd72140-85a6-4f25-8a17-70a89c00db8c
- if (optionViewableVBA)
- {
+ //Set ProjectProtectionState and ProjectVisibilityState to be viewable see https://docs.microsoft.com/en-us/openspecs/office_file_formats/ms-ovba/dfd72140-85a6-4f25-8a17-70a89c00db8c
+ if (optionViewableVBA)
+ {
Console.WriteLine("Making the project visible...");
// Console.WriteLine("Stream before: " + projectStreamString);
string tmpStr = projectStreamString;
- tmpStr = Regex.Replace(tmpStr, "CMG=\"?.*\"?", "CMG=\"CAC866BE34C234C230C630C6\"");
- tmpStr = Regex.Replace(tmpStr, "ID=\"?.*\"?", "ID=\"{00000000-0000-0000-0000-000000000000}\"");
- tmpStr = Regex.Replace(tmpStr, "DPB=\"?.*\"?", "DPB=\"94963888C84FE54FE5B01B50E59251526FE67A1CC76C84ED0DAD653FD058F324BFD9D38DED37\"");
- tmpStr = Regex.Replace(tmpStr, "GC=\"?.*\"?", "GC=\"5E5CF2C27646414741474\"");
+ tmpStr = Regex.Replace(tmpStr, "CMG=\"?.*\"?", "CMG=\"CAC866BE34C234C230C630C6\"");
+ tmpStr = Regex.Replace(tmpStr, "ID=\"?.*\"?", "ID=\"{00000000-0000-0000-0000-000000000000}\"");
+ tmpStr = Regex.Replace(tmpStr, "DPB=\"?.*\"?", "DPB=\"94963888C84FE54FE5B01B50E59251526FE67A1CC76C84ED0DAD653FD058F324BFD9D38DED37\"");
+ tmpStr = Regex.Replace(tmpStr, "GC=\"?.*\"?", "GC=\"5E5CF2C27646414741474\"");
string newProjectStreamString = tmpStr;
// Console.WriteLine("Stream afterw: " + newProjectStreamString);
- // Write changes to project stream
- commonStorage.GetStream("project").SetData(Encoding.UTF8.GetBytes(newProjectStreamString));
- }
+ // Write changes to project stream
+ projectStream.SetData(Encoding.UTF8.GetBytes(newProjectStreamString));
+ }
- // Hide modules from GUI
- if (optionHideInGUI)
+ // Hide modules from GUI
+ if (optionHideInGUI)
{
foreach (var vbaModule in vbaModules)
{
- if ((vbaModule.moduleName != "ThisDocument") && (vbaModule.moduleName != "ThisWorkbook"))
+ if (targetModules.Count > 0)
{
- Console.WriteLine("Hiding module: " + vbaModule.moduleName);
- projectStreamString = projectStreamString.Replace("Module=" + vbaModule.moduleName, "");
+ if (targetModules.Contains(vbaModule.moduleName) || !targetModules.Any())
+ {
+ Console.WriteLine("Hiding module: " + vbaModule.moduleName);
+ projectStreamString = projectStreamString.Replace("Module=" + vbaModule.moduleName, "");
+ }
+ }
+ else
+ {
+ if ((vbaModule.moduleName != "ThisDocument") && (vbaModule.moduleName != "ThisWorkbook"))
+ {
+ Console.WriteLine("Hiding module: " + vbaModule.moduleName);
+ projectStreamString = projectStreamString.Replace("Module=" + vbaModule.moduleName, "");
+ }
}
}
// Write changes to project stream
- commonStorage.GetStream("project").SetData(Encoding.UTF8.GetBytes(projectStreamString));
+ projectStream.SetData(Encoding.UTF8.GetBytes(projectStreamString));
}
// Undo the Hide modules from GUI effects
if (optionUnhideInGUI)
{
- ArrayList vbaModulesNamesFromProjectwm = getModulesNamesFromProjectwmStream(projectwmStreamString);
- Regex theregex = new Regex(@"(Document\=.*\/.{10})([\S\s]*?)(ExeName32\=|Name\=|ID\=|Class\=|BaseClass\=|Package\=|HelpFile\=|HelpContextID\=|Description\=|VersionCompatible32\=|CMG\=|DPB\=|GC\=)");
- Match m = theregex.Match(projectStreamString);
- if (m.Groups.Count != 4)
- {
- Console.WriteLine("Error, could not find the location to insert module names. Not able to unhide modules");
- }
- else
+ if (projectwmStreamString.Length > 0)
{
- string moduleString = "\r\n";
-
- foreach (var vbaModuleName in vbaModulesNamesFromProjectwm)
+ ArrayList vbaModulesNamesFromProjectwm = getModulesNamesFromProjectwmStream(projectwmStreamString);
+ Regex theregex = new Regex(@"(Document\=.*\/.{10})([\S\s]*?)(ExeName32\=|Name\=|ID\=|Class\=|BaseClass\=|Package\=|HelpFile\=|HelpContextID\=|Description\=|VersionCompatible32\=|CMG\=|DPB\=|GC\=)");
+ Match m = theregex.Match(projectStreamString);
+ if (m.Groups.Count != 4)
{
- Console.WriteLine("Unhiding module: " + vbaModuleName);
- moduleString = moduleString.Insert(moduleString.Length, "Module=" + vbaModuleName + "\r\n");
+ Console.WriteLine("Error, could not find the location to insert module names. Not able to unhide modules");
}
+ else
+ {
+ string moduleString = "\r\n";
+
+ foreach (var vbaModuleName in vbaModulesNamesFromProjectwm)
+ {
+ if (targetModules.Count > 0)
+ {
+ if (targetModules.Contains(vbaModuleName) || !targetModules.Any())
+ {
+ Console.WriteLine("Unhiding module: " + vbaModuleName);
+ moduleString = moduleString.Insert(moduleString.Length, "Module=" + vbaModuleName + "\r\n");
+ }
+ }
+ else
+ {
+ Console.WriteLine("Unhiding module: " + vbaModuleName);
+ moduleString = moduleString.Insert(moduleString.Length, "Module=" + vbaModuleName + "\r\n");
+ }
+ }
- projectStreamString = projectStreamString.Replace(m.Groups[0].Value, m.Groups[1].Value + moduleString + m.Groups[3].Value);
+ projectStreamString = projectStreamString.Replace(m.Groups[0].Value, m.Groups[1].Value + moduleString + m.Groups[3].Value);
- // write changes to project stream
- commonStorage.GetStream("project").SetData(Encoding.UTF8.GetBytes(projectStreamString));
+ // write changes to project stream
+ projectStream.SetData(Encoding.UTF8.GetBytes(projectStreamString));
+ }
}
+ else
+ {
+ Console.WriteLine("[-] Not available: Undo the Hide modules from GUI effects");
+ }
}
// Stomp VBA modules
@@ -290,11 +458,11 @@ static public void Main(string[] args)
DebugLog("VBA module name: " + vbaModule.moduleName + "\nOffset for code: " + vbaModule.textOffset);
// If this module is a target module, or if no targets are specified, then stomp
- if (targetModules.Contains(vbaModule.moduleName) || !targetModules.Any())
+ if ((targetModules.Count > 0 && targetModules.Contains(vbaModule.moduleName) ) || !targetModules.Any())
{
Console.WriteLine("Now stomping VBA code in module: " + vbaModule.moduleName);
- streamBytes = commonStorage.GetStorage("VBA").GetStream(vbaModule.moduleName).GetData();
+ streamBytes = vbaStorage.GetStream(vbaModule.moduleName).GetData();
DebugLog("Existing VBA source:\n" + GetVBATextFromModuleStream(streamBytes, vbaModule.textOffset));
@@ -322,7 +490,7 @@ static public void Main(string[] args)
DebugLog("Hex dump of VBA module stream " + vbaModule.moduleName + ":\n" + Utils.HexDump(streamBytes));
- commonStorage.GetStorage("VBA").GetStream(vbaModule.moduleName).SetData(streamBytes);
+ vbaStorage.GetStream(vbaModule.moduleName).SetData(streamBytes);
}
}
}
@@ -334,7 +502,7 @@ static public void Main(string[] args)
Console.WriteLine("Setting random ASCII names for VBA modules in dir stream (while leaving unicode names intact).");
// Recompress and write to dir stream
- commonStorage.GetStorage("VBA").GetStream("dir").SetData(Compress(SetRandomNamesInDirStream(dirStream)));
+ dirStream.SetData(Compress(SetRandomNamesInDirStream(dirStreamBytes)));
}
// Reset module names in dir stream so that the ASCII names match the Unicode names (undo SetRandomNames option)
@@ -343,7 +511,7 @@ static public void Main(string[] args)
Console.WriteLine("Resetting module names in dir stream to match names is _VBA_PROJECT stream (undo SetRandomNames option)");
// Recompress and write to dir stream
- commonStorage.GetStorage("VBA").GetStream("dir").SetData(Compress(ResetModuleNamesInDirStream(dirStream)));
+ dirStream.SetData(Compress(ResetModuleNamesInDirStream(dirStreamBytes)));
}
// Delete metadata from document
@@ -429,33 +597,33 @@ static public byte[] SendFile(HttpListenerRequest request)
{
Console.WriteLine("Serving request from " + request.RemoteEndPoint.ToString() + " with user agent " + request.UserAgent);
- CompoundFile cf = null;
- try
- {
- cf = new CompoundFile(outFilename, CFSUpdateMode.Update, 0);
- }
- catch (Exception e)
- {
- Console.WriteLine("ERROR: Could not open file " + outFilename);
- Console.WriteLine("Please make sure this file exists and is .docm or .xlsm file or a .doc in the Office 97-2003 format.");
- Console.WriteLine();
- Console.WriteLine(e.Message);
- }
-
- CFStream streamData = cf.RootStorage.GetStorage("Macros").GetStorage("VBA").GetStream("_VBA_PROJECT");
+ CompoundFile cf = null;
+ try
+ {
+ cf = new CompoundFile(outFilename, CFSUpdateMode.Update, 0);
+ }
+ catch (Exception e)
+ {
+ Console.WriteLine("ERROR: Could not open file " + outFilename);
+ Console.WriteLine("Please make sure this file exists and is .docm or .xlsm file or a .doc in the Office 97-2003 format.");
+ Console.WriteLine();
+ Console.WriteLine(e.Message);
+ }
+
+ CFStream streamData = vbaProjectStream;
byte[] streamBytes = streamData.GetData();
string targetOfficeVersion = UserAgentToOfficeVersion(request.UserAgent);
ReplaceOfficeVersionInVBAProject(streamBytes, targetOfficeVersion);
- cf.RootStorage.GetStorage("Macros").GetStorage("VBA").GetStream("_VBA_PROJECT").SetData(streamBytes);
+ vbaProjectStream.SetData(streamBytes);
// Commit changes and close file
cf.Commit();
cf.Close();
- Console.WriteLine("Serving out file '" + outFilename + "'");
+ Console.WriteLine("Serving out file '" + outFilename + "'");
return File.ReadAllBytes(outFilename);
}
@@ -488,7 +656,7 @@ static void ShowHelp(OptionSet p)
Console.WriteLine();
Console.WriteLine("Author: Stan Hegt");
Console.WriteLine("Email: stan@outflank.nl");
- Console.WriteLine();
+ Console.WriteLine();
Console.WriteLine("Options:");
p.WriteOptionDescriptions(Console.Out);
}
@@ -534,11 +702,11 @@ private static byte[] ReplaceOfficeVersionInVBAProject(byte[] moduleStream, stri
case "2016x64":
version[0] = 0xB2;
version[1] = 0x00;
- break;
+ break;
case "2019x64":
version[0] = 0xB2;
version[1] = 0x00;
- break;
+ break;
default:
Console.WriteLine("ERROR: Incorrect MS Office version specified - skipping this step.");
return moduleStream;
diff --git a/options.cs b/options.cs
index 9a43b19..1f7dba0 100644
--- a/options.cs
+++ b/options.cs
@@ -1,4 +1,4 @@
-//
+//
// Options.cs
//
// Authors:
@@ -143,551 +143,582 @@
using NDesk.Options;
#endif
-namespace NDesk.Options {
-
- public class OptionValueCollection : IList, IList {
-
- List values = new List ();
- OptionContext c;
-
- internal OptionValueCollection (OptionContext c)
- {
- this.c = c;
- }
-
- #region ICollection
- void ICollection.CopyTo (Array array, int index) {(values as ICollection).CopyTo (array, index);}
- bool ICollection.IsSynchronized {get {return (values as ICollection).IsSynchronized;}}
- object ICollection.SyncRoot {get {return (values as ICollection).SyncRoot;}}
- #endregion
-
- #region ICollection
- public void Add (string item) {values.Add (item);}
- public void Clear () {values.Clear ();}
- public bool Contains (string item) {return values.Contains (item);}
- public void CopyTo (string[] array, int arrayIndex) {values.CopyTo (array, arrayIndex);}
- public bool Remove (string item) {return values.Remove (item);}
- public int Count {get {return values.Count;}}
- public bool IsReadOnly {get {return false;}}
- #endregion
-
- #region IEnumerable
- IEnumerator IEnumerable.GetEnumerator () {return values.GetEnumerator ();}
- #endregion
-
- #region IEnumerable
- public IEnumerator GetEnumerator () {return values.GetEnumerator ();}
- #endregion
-
- #region IList
- int IList.Add (object value) {return (values as IList).Add (value);}
- bool IList.Contains (object value) {return (values as IList).Contains (value);}
- int IList.IndexOf (object value) {return (values as IList).IndexOf (value);}
- void IList.Insert (int index, object value) {(values as IList).Insert (index, value);}
- void IList.Remove (object value) {(values as IList).Remove (value);}
- void IList.RemoveAt (int index) {(values as IList).RemoveAt (index);}
- bool IList.IsFixedSize {get {return false;}}
- object IList.this [int index] {get {return this [index];} set {(values as IList)[index] = value;}}
- #endregion
-
- #region IList
- public int IndexOf (string item) {return values.IndexOf (item);}
- public void Insert (int index, string item) {values.Insert (index, item);}
- public void RemoveAt (int index) {values.RemoveAt (index);}
-
- private void AssertValid (int index)
- {
- if (c.Option == null)
- throw new InvalidOperationException ("OptionContext.Option is null.");
- if (index >= c.Option.MaxValueCount)
- throw new ArgumentOutOfRangeException ("index");
- if (c.Option.OptionValueType == OptionValueType.Required &&
- index >= values.Count)
- throw new OptionException (string.Format (
- c.OptionSet.MessageLocalizer ("Missing required value for option '{0}'."), c.OptionName),
- c.OptionName);
- }
-
- public string this [int index] {
- get {
- AssertValid (index);
- return index >= values.Count ? null : values [index];
- }
- set {
- values [index] = value;
- }
- }
- #endregion
-
- public List ToList ()
- {
- return new List (values);
- }
-
- public string[] ToArray ()
- {
- return values.ToArray ();
- }
-
- public override string ToString ()
- {
- return string.Join (", ", values.ToArray ());
- }
- }
-
- public class OptionContext {
- private Option option;
- private string name;
- private int index;
- private OptionSet set;
- private OptionValueCollection c;
-
- public OptionContext (OptionSet set)
- {
- this.set = set;
- this.c = new OptionValueCollection (this);
- }
-
- public Option Option {
- get {return option;}
- set {option = value;}
- }
-
- public string OptionName {
- get {return name;}
- set {name = value;}
- }
-
- public int OptionIndex {
- get {return index;}
- set {index = value;}
- }
-
- public OptionSet OptionSet {
- get {return set;}
- }
-
- public OptionValueCollection OptionValues {
- get {return c;}
- }
- }
-
- public enum OptionValueType {
- None,
- Optional,
- Required,
- }
-
- public abstract class Option {
- string prototype, description;
- string[] names;
- OptionValueType type;
- int count;
- string[] separators;
-
- protected Option (string prototype, string description)
- : this (prototype, description, 1)
- {
- }
-
- protected Option (string prototype, string description, int maxValueCount)
- {
- if (prototype == null)
- throw new ArgumentNullException ("prototype");
- if (prototype.Length == 0)
- throw new ArgumentException ("Cannot be the empty string.", "prototype");
- if (maxValueCount < 0)
- throw new ArgumentOutOfRangeException ("maxValueCount");
-
- this.prototype = prototype;
- this.names = prototype.Split ('|');
- this.description = description;
- this.count = maxValueCount;
- this.type = ParsePrototype ();
-
- if (this.count == 0 && type != OptionValueType.None)
- throw new ArgumentException (
- "Cannot provide maxValueCount of 0 for OptionValueType.Required or " +
- "OptionValueType.Optional.",
- "maxValueCount");
- if (this.type == OptionValueType.None && maxValueCount > 1)
- throw new ArgumentException (
- string.Format ("Cannot provide maxValueCount of {0} for OptionValueType.None.", maxValueCount),
- "maxValueCount");
- if (Array.IndexOf (names, "<>") >= 0 &&
- ((names.Length == 1 && this.type != OptionValueType.None) ||
- (names.Length > 1 && this.MaxValueCount > 1)))
- throw new ArgumentException (
- "The default option handler '<>' cannot require values.",
- "prototype");
- }
-
- public string Prototype {get {return prototype;}}
- public string Description {get {return description;}}
- public OptionValueType OptionValueType {get {return type;}}
- public int MaxValueCount {get {return count;}}
-
- public string[] GetNames ()
- {
- return (string[]) names.Clone ();
- }
-
- public string[] GetValueSeparators ()
- {
- if (separators == null)
- return new string [0];
- return (string[]) separators.Clone ();
- }
-
- protected static T Parse (string value, OptionContext c)
- {
- TypeConverter conv = TypeDescriptor.GetConverter (typeof (T));
- T t = default (T);
- try {
- if (value != null)
- t = (T) conv.ConvertFromString (value);
- }
- catch (Exception e) {
- throw new OptionException (
- string.Format (
- c.OptionSet.MessageLocalizer ("Could not convert string `{0}' to type {1} for option `{2}'."),
- value, typeof (T).Name, c.OptionName),
- c.OptionName, e);
- }
- return t;
- }
-
- internal string[] Names {get {return names;}}
- internal string[] ValueSeparators {get {return separators;}}
-
- static readonly char[] NameTerminator = new char[]{'=', ':'};
-
- private OptionValueType ParsePrototype ()
- {
- char type = '\0';
- List seps = new List ();
- for (int i = 0; i < names.Length; ++i) {
- string name = names [i];
- if (name.Length == 0)
- throw new ArgumentException ("Empty option names are not supported.", "prototype");
-
- int end = name.IndexOfAny (NameTerminator);
- if (end == -1)
- continue;
- names [i] = name.Substring (0, end);
- if (type == '\0' || type == name [end])
- type = name [end];
- else
- throw new ArgumentException (
- string.Format ("Conflicting option types: '{0}' vs. '{1}'.", type, name [end]),
- "prototype");
- AddSeparators (name, end, seps);
- }
-
- if (type == '\0')
- return OptionValueType.None;
-
- if (count <= 1 && seps.Count != 0)
- throw new ArgumentException (
- string.Format ("Cannot provide key/value separators for Options taking {0} value(s).", count),
- "prototype");
- if (count > 1) {
- if (seps.Count == 0)
- this.separators = new string[]{":", "="};
- else if (seps.Count == 1 && seps [0].Length == 0)
- this.separators = null;
- else
- this.separators = seps.ToArray ();
- }
-
- return type == '=' ? OptionValueType.Required : OptionValueType.Optional;
- }
-
- private static void AddSeparators (string name, int end, ICollection seps)
- {
- int start = -1;
- for (int i = end+1; i < name.Length; ++i) {
- switch (name [i]) {
- case '{':
- if (start != -1)
- throw new ArgumentException (
- string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
- "prototype");
- start = i+1;
- break;
- case '}':
- if (start == -1)
- throw new ArgumentException (
- string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
- "prototype");
- seps.Add (name.Substring (start, i-start));
- start = -1;
- break;
- default:
- if (start == -1)
- seps.Add (name [i].ToString ());
- break;
- }
- }
- if (start != -1)
- throw new ArgumentException (
- string.Format ("Ill-formed name/value separator found in \"{0}\".", name),
- "prototype");
- }
-
- public void Invoke (OptionContext c)
- {
- OnParseComplete (c);
- c.OptionName = null;
- c.Option = null;
- c.OptionValues.Clear ();
- }
-
- protected abstract void OnParseComplete (OptionContext c);
-
- public override string ToString ()
- {
- return Prototype;
- }
- }
-
- [Serializable]
- public class OptionException : Exception {
- private string option;
-
- public OptionException ()
- {
- }
-
- public OptionException (string message, string optionName)
- : base (message)
- {
- this.option = optionName;
- }
-
- public OptionException (string message, string optionName, Exception innerException)
- : base (message, innerException)
- {
- this.option = optionName;
- }
-
- protected OptionException (SerializationInfo info, StreamingContext context)
- : base (info, context)
- {
- this.option = info.GetString ("OptionName");
- }
-
- public string OptionName {
- get {return this.option;}
- }
-
- [SecurityPermission (SecurityAction.LinkDemand, SerializationFormatter = true)]
- public override void GetObjectData (SerializationInfo info, StreamingContext context)
- {
- base.GetObjectData (info, context);
- info.AddValue ("OptionName", option);
- }
- }
-
- public delegate void OptionAction (TKey key, TValue value);
-
- public class OptionSet : KeyedCollection
- {
- public OptionSet ()
- : this (delegate (string f) {return f;})
- {
- }
-
- public OptionSet (Converter localizer)
- {
- this.localizer = localizer;
- }
-
- Converter localizer;
-
- public Converter MessageLocalizer {
- get {return localizer;}
- }
-
- protected override string GetKeyForItem (Option item)
- {
- if (item == null)
- throw new ArgumentNullException ("option");
- if (item.Names != null && item.Names.Length > 0)
- return item.Names [0];
- // This should never happen, as it's invalid for Option to be
- // constructed w/o any names.
- throw new InvalidOperationException ("Option has no names!");
- }
-
- [Obsolete ("Use KeyedCollection.this[string]")]
- protected Option GetOptionForName (string option)
- {
- if (option == null)
- throw new ArgumentNullException ("option");
- try {
- return base [option];
- }
- catch (KeyNotFoundException) {
- return null;
- }
- }
-
- protected override void InsertItem (int index, Option item)
- {
- base.InsertItem (index, item);
- AddImpl (item);
- }
-
- protected override void RemoveItem (int index)
- {
- base.RemoveItem (index);
- Option p = Items [index];
- // KeyedCollection.RemoveItem() handles the 0th item
- for (int i = 1; i < p.Names.Length; ++i) {
- Dictionary.Remove (p.Names [i]);
- }
- }
-
- protected override void SetItem (int index, Option item)
- {
- base.SetItem (index, item);
- RemoveItem (index);
- AddImpl (item);
- }
-
- private void AddImpl (Option option)
- {
- if (option == null)
- throw new ArgumentNullException ("option");
- List added = new List (option.Names.Length);
- try {
- // KeyedCollection.InsertItem/SetItem handle the 0th name.
- for (int i = 1; i < option.Names.Length; ++i) {
- Dictionary.Add (option.Names [i], option);
- added.Add (option.Names [i]);
- }
- }
- catch (Exception) {
- foreach (string name in added)
- Dictionary.Remove (name);
- throw;
- }
- }
-
- public new OptionSet Add (Option option)
- {
- base.Add (option);
- return this;
- }
-
- sealed class ActionOption : Option {
- Action action;
-
- public ActionOption (string prototype, string description, int count, Action action)
- : base (prototype, description, count)
- {
- if (action == null)
- throw new ArgumentNullException ("action");
- this.action = action;
- }
-
- protected override void OnParseComplete (OptionContext c)
- {
- action (c.OptionValues);
- }
- }
-
- public OptionSet Add (string prototype, Action action)
- {
- return Add (prototype, null, action);
- }
-
- public OptionSet Add (string prototype, string description, Action action)
- {
- if (action == null)
- throw new ArgumentNullException ("action");
- Option p = new ActionOption (prototype, description, 1,
- delegate (OptionValueCollection v) { action (v [0]); });
- base.Add (p);
- return this;
- }
-
- public OptionSet Add (string prototype, OptionAction action)
- {
- return Add (prototype, null, action);
- }
-
- public OptionSet Add (string prototype, string description, OptionAction action)
- {
- if (action == null)
- throw new ArgumentNullException ("action");
- Option p = new ActionOption (prototype, description, 2,
- delegate (OptionValueCollection v) {action (v [0], v [1]);});
- base.Add (p);
- return this;
- }
-
- sealed class ActionOption : Option {
- Action action;
-
- public ActionOption (string prototype, string description, Action action)
- : base (prototype, description, 1)
- {
- if (action == null)
- throw new ArgumentNullException ("action");
- this.action = action;
- }
-
- protected override void OnParseComplete (OptionContext c)
- {
- action (Parse (c.OptionValues [0], c));
- }
- }
-
- sealed class ActionOption : Option {
- OptionAction action;
-
- public ActionOption (string prototype, string description, OptionAction action)
- : base (prototype, description, 2)
- {
- if (action == null)
- throw new ArgumentNullException ("action");
- this.action = action;
- }
-
- protected override void OnParseComplete (OptionContext c)
- {
- action (
- Parse (c.OptionValues [0], c),
- Parse (c.OptionValues [1], c));
- }
- }
-
- public OptionSet Add (string prototype, Action action)
- {
- return Add (prototype, null, action);
- }
-
- public OptionSet Add (string prototype, string description, Action action)
- {
- return Add (new ActionOption (prototype, description, action));
- }
-
- public OptionSet Add (string prototype, OptionAction action)
- {
- return Add (prototype, null, action);
- }
-
- public OptionSet Add (string prototype, string description, OptionAction action)
- {
- return Add (new ActionOption (prototype, description, action));
- }
-
- protected virtual OptionContext CreateOptionContext ()
- {
- return new OptionContext (this);
- }
+namespace NDesk.Options
+{
+
+ public class OptionValueCollection : IList, IList
+ {
+
+ List values = new List();
+ OptionContext c;
+
+ internal OptionValueCollection(OptionContext c)
+ {
+ this.c = c;
+ }
+
+ #region ICollection
+ void ICollection.CopyTo(Array array, int index) { (values as ICollection).CopyTo(array, index); }
+ bool ICollection.IsSynchronized { get { return (values as ICollection).IsSynchronized; } }
+ object ICollection.SyncRoot { get { return (values as ICollection).SyncRoot; } }
+ #endregion
+
+ #region ICollection
+ public void Add(string item) { values.Add(item); }
+ public void Clear() { values.Clear(); }
+ public bool Contains(string item) { return values.Contains(item); }
+ public void CopyTo(string[] array, int arrayIndex) { values.CopyTo(array, arrayIndex); }
+ public bool Remove(string item) { return values.Remove(item); }
+ public int Count { get { return values.Count; } }
+ public bool IsReadOnly { get { return false; } }
+ #endregion
+
+ #region IEnumerable
+ IEnumerator IEnumerable.GetEnumerator() { return values.GetEnumerator(); }
+ #endregion
+
+ #region IEnumerable
+ public IEnumerator GetEnumerator() { return values.GetEnumerator(); }
+ #endregion
+
+ #region IList
+ int IList.Add(object value) { return (values as IList).Add(value); }
+ bool IList.Contains(object value) { return (values as IList).Contains(value); }
+ int IList.IndexOf(object value) { return (values as IList).IndexOf(value); }
+ void IList.Insert(int index, object value) { (values as IList).Insert(index, value); }
+ void IList.Remove(object value) { (values as IList).Remove(value); }
+ void IList.RemoveAt(int index) { (values as IList).RemoveAt(index); }
+ bool IList.IsFixedSize { get { return false; } }
+ object IList.this[int index] { get { return this[index]; } set { (values as IList)[index] = value; } }
+ #endregion
+
+ #region IList
+ public int IndexOf(string item) { return values.IndexOf(item); }
+ public void Insert(int index, string item) { values.Insert(index, item); }
+ public void RemoveAt(int index) { values.RemoveAt(index); }
+
+ private void AssertValid(int index)
+ {
+ if (c.Option == null)
+ throw new InvalidOperationException("OptionContext.Option is null.");
+ if (index >= c.Option.MaxValueCount)
+ throw new ArgumentOutOfRangeException("index");
+ if (c.Option.OptionValueType == OptionValueType.Required &&
+ index >= values.Count)
+ throw new OptionException(string.Format(
+ c.OptionSet.MessageLocalizer("Missing required value for option '{0}'."), c.OptionName),
+ c.OptionName);
+ }
+
+ public string this[int index]
+ {
+ get
+ {
+ AssertValid(index);
+ return index >= values.Count ? null : values[index];
+ }
+ set
+ {
+ values[index] = value;
+ }
+ }
+ #endregion
+
+ public List ToList()
+ {
+ return new List(values);
+ }
+
+ public string[] ToArray()
+ {
+ return values.ToArray();
+ }
+
+ public override string ToString()
+ {
+ return string.Join(", ", values.ToArray());
+ }
+ }
+
+ public class OptionContext
+ {
+ private Option option;
+ private string name;
+ private int index;
+ private OptionSet set;
+ private OptionValueCollection c;
+
+ public OptionContext(OptionSet set)
+ {
+ this.set = set;
+ this.c = new OptionValueCollection(this);
+ }
+
+ public Option Option
+ {
+ get { return option; }
+ set { option = value; }
+ }
+
+ public string OptionName
+ {
+ get { return name; }
+ set { name = value; }
+ }
+
+ public int OptionIndex
+ {
+ get { return index; }
+ set { index = value; }
+ }
+
+ public OptionSet OptionSet
+ {
+ get { return set; }
+ }
+
+ public OptionValueCollection OptionValues
+ {
+ get { return c; }
+ }
+ }
+
+ public enum OptionValueType
+ {
+ None,
+ Optional,
+ Required,
+ }
+
+ public abstract class Option
+ {
+ string prototype, description;
+ string[] names;
+ OptionValueType type;
+ int count;
+ string[] separators;
+
+ protected Option(string prototype, string description)
+ : this(prototype, description, 1)
+ {
+ }
+
+ protected Option(string prototype, string description, int maxValueCount)
+ {
+ if (prototype == null)
+ throw new ArgumentNullException("prototype");
+ if (prototype.Length == 0)
+ throw new ArgumentException("Cannot be the empty string.", "prototype");
+ if (maxValueCount < 0)
+ throw new ArgumentOutOfRangeException("maxValueCount");
+
+ this.prototype = prototype;
+ this.names = prototype.Split('|');
+ this.description = description;
+ this.count = maxValueCount;
+ this.type = ParsePrototype();
+
+ if (this.count == 0 && type != OptionValueType.None)
+ throw new ArgumentException(
+ "Cannot provide maxValueCount of 0 for OptionValueType.Required or " +
+ "OptionValueType.Optional.",
+ "maxValueCount");
+ if (this.type == OptionValueType.None && maxValueCount > 1)
+ throw new ArgumentException(
+ string.Format("Cannot provide maxValueCount of {0} for OptionValueType.None.", maxValueCount),
+ "maxValueCount");
+ if (Array.IndexOf(names, "<>") >= 0 &&
+ ((names.Length == 1 && this.type != OptionValueType.None) ||
+ (names.Length > 1 && this.MaxValueCount > 1)))
+ throw new ArgumentException(
+ "The default option handler '<>' cannot require values.",
+ "prototype");
+ }
+
+ public string Prototype { get { return prototype; } }
+ public string Description { get { return description; } }
+ public OptionValueType OptionValueType { get { return type; } }
+ public int MaxValueCount { get { return count; } }
+
+ public string[] GetNames()
+ {
+ return (string[])names.Clone();
+ }
+
+ public string[] GetValueSeparators()
+ {
+ if (separators == null)
+ return new string[0];
+ return (string[])separators.Clone();
+ }
+
+ protected static T Parse(string value, OptionContext c)
+ {
+ TypeConverter conv = TypeDescriptor.GetConverter(typeof(T));
+ T t = default(T);
+ try
+ {
+ if (value != null)
+ t = (T)conv.ConvertFromString(value);
+ }
+ catch (Exception e)
+ {
+ throw new OptionException(
+ string.Format(
+ c.OptionSet.MessageLocalizer("Could not convert string `{0}' to type {1} for option `{2}'."),
+ value, typeof(T).Name, c.OptionName),
+ c.OptionName, e);
+ }
+ return t;
+ }
+
+ internal string[] Names { get { return names; } }
+ internal string[] ValueSeparators { get { return separators; } }
+
+ static readonly char[] NameTerminator = new char[] { '=', ':' };
+
+ private OptionValueType ParsePrototype()
+ {
+ char type = '\0';
+ List seps = new List();
+ for (int i = 0; i < names.Length; ++i)
+ {
+ string name = names[i];
+ if (name.Length == 0)
+ throw new ArgumentException("Empty option names are not supported.", "prototype");
+
+ int end = name.IndexOfAny(NameTerminator);
+ if (end == -1)
+ continue;
+ names[i] = name.Substring(0, end);
+ if (type == '\0' || type == name[end])
+ type = name[end];
+ else
+ throw new ArgumentException(
+ string.Format("Conflicting option types: '{0}' vs. '{1}'.", type, name[end]),
+ "prototype");
+ AddSeparators(name, end, seps);
+ }
+
+ if (type == '\0')
+ return OptionValueType.None;
+
+ if (count <= 1 && seps.Count != 0)
+ throw new ArgumentException(
+ string.Format("Cannot provide key/value separators for Options taking {0} value(s).", count),
+ "prototype");
+ if (count > 1)
+ {
+ if (seps.Count == 0)
+ this.separators = new string[] { ":", "=" };
+ else if (seps.Count == 1 && seps[0].Length == 0)
+ this.separators = null;
+ else
+ this.separators = seps.ToArray();
+ }
+
+ return type == '=' ? OptionValueType.Required : OptionValueType.Optional;
+ }
+
+ private static void AddSeparators(string name, int end, ICollection seps)
+ {
+ int start = -1;
+ for (int i = end + 1; i < name.Length; ++i)
+ {
+ switch (name[i])
+ {
+ case '{':
+ if (start != -1)
+ throw new ArgumentException(
+ string.Format("Ill-formed name/value separator found in \"{0}\".", name),
+ "prototype");
+ start = i + 1;
+ break;
+ case '}':
+ if (start == -1)
+ throw new ArgumentException(
+ string.Format("Ill-formed name/value separator found in \"{0}\".", name),
+ "prototype");
+ seps.Add(name.Substring(start, i - start));
+ start = -1;
+ break;
+ default:
+ if (start == -1)
+ seps.Add(name[i].ToString());
+ break;
+ }
+ }
+ if (start != -1)
+ throw new ArgumentException(
+ string.Format("Ill-formed name/value separator found in \"{0}\".", name),
+ "prototype");
+ }
+
+ public void Invoke(OptionContext c)
+ {
+ OnParseComplete(c);
+ c.OptionName = null;
+ c.Option = null;
+ c.OptionValues.Clear();
+ }
+
+ protected abstract void OnParseComplete(OptionContext c);
+
+ public override string ToString()
+ {
+ return Prototype;
+ }
+ }
+
+ [Serializable]
+ public class OptionException : Exception
+ {
+ private string option;
+
+ public OptionException()
+ {
+ }
+
+ public OptionException(string message, string optionName)
+ : base(message)
+ {
+ this.option = optionName;
+ }
+
+ public OptionException(string message, string optionName, Exception innerException)
+ : base(message, innerException)
+ {
+ this.option = optionName;
+ }
+
+ protected OptionException(SerializationInfo info, StreamingContext context)
+ : base(info, context)
+ {
+ this.option = info.GetString("OptionName");
+ }
+
+ public string OptionName
+ {
+ get { return this.option; }
+ }
+
+ [SecurityPermission(SecurityAction.LinkDemand, SerializationFormatter = true)]
+ public override void GetObjectData(SerializationInfo info, StreamingContext context)
+ {
+ base.GetObjectData(info, context);
+ info.AddValue("OptionName", option);
+ }
+ }
+
+ public delegate void OptionAction(TKey key, TValue value);
+
+ public class OptionSet : KeyedCollection
+ {
+ public OptionSet()
+ : this(delegate (string f) { return f; })
+ {
+ }
+
+ public OptionSet(Converter localizer)
+ {
+ this.localizer = localizer;
+ }
+
+ Converter localizer;
+
+ public Converter MessageLocalizer
+ {
+ get { return localizer; }
+ }
+
+ protected override string GetKeyForItem(Option item)
+ {
+ if (item == null)
+ throw new ArgumentNullException("option");
+ if (item.Names != null && item.Names.Length > 0)
+ return item.Names[0];
+ // This should never happen, as it's invalid for Option to be
+ // constructed w/o any names.
+ throw new InvalidOperationException("Option has no names!");
+ }
+
+ [Obsolete("Use KeyedCollection.this[string]")]
+ protected Option GetOptionForName(string option)
+ {
+ if (option == null)
+ throw new ArgumentNullException("option");
+ try
+ {
+ return base[option];
+ }
+ catch (KeyNotFoundException)
+ {
+ return null;
+ }
+ }
+
+ protected override void InsertItem(int index, Option item)
+ {
+ base.InsertItem(index, item);
+ AddImpl(item);
+ }
+
+ protected override void RemoveItem(int index)
+ {
+ base.RemoveItem(index);
+ Option p = Items[index];
+ // KeyedCollection.RemoveItem() handles the 0th item
+ for (int i = 1; i < p.Names.Length; ++i)
+ {
+ Dictionary.Remove(p.Names[i]);
+ }
+ }
+
+ protected override void SetItem(int index, Option item)
+ {
+ base.SetItem(index, item);
+ RemoveItem(index);
+ AddImpl(item);
+ }
+
+ private void AddImpl(Option option)
+ {
+ if (option == null)
+ throw new ArgumentNullException("option");
+ List added = new List(option.Names.Length);
+ try
+ {
+ // KeyedCollection.InsertItem/SetItem handle the 0th name.
+ for (int i = 1; i < option.Names.Length; ++i)
+ {
+ Dictionary.Add(option.Names[i], option);
+ added.Add(option.Names[i]);
+ }
+ }
+ catch (Exception)
+ {
+ foreach (string name in added)
+ Dictionary.Remove(name);
+ throw;
+ }
+ }
+
+ public new OptionSet Add(Option option)
+ {
+ base.Add(option);
+ return this;
+ }
+
+ sealed class ActionOption : Option
+ {
+ Action action;
+
+ public ActionOption(string prototype, string description, int count, Action action)
+ : base(prototype, description, count)
+ {
+ if (action == null)
+ throw new ArgumentNullException("action");
+ this.action = action;
+ }
+
+ protected override void OnParseComplete(OptionContext c)
+ {
+ action(c.OptionValues);
+ }
+ }
+
+ public OptionSet Add(string prototype, Action action)
+ {
+ return Add(prototype, null, action);
+ }
+
+ public OptionSet Add(string prototype, string description, Action action)
+ {
+ if (action == null)
+ throw new ArgumentNullException("action");
+ Option p = new ActionOption(prototype, description, 1,
+ delegate (OptionValueCollection v) { action(v[0]); });
+ base.Add(p);
+ return this;
+ }
+
+ public OptionSet Add(string prototype, OptionAction action)
+ {
+ return Add(prototype, null, action);
+ }
+
+ public OptionSet Add(string prototype, string description, OptionAction action)
+ {
+ if (action == null)
+ throw new ArgumentNullException("action");
+ Option p = new ActionOption(prototype, description, 2,
+ delegate (OptionValueCollection v) { action(v[0], v[1]); });
+ base.Add(p);
+ return this;
+ }
+
+ sealed class ActionOption : Option
+ {
+ Action action;
+
+ public ActionOption(string prototype, string description, Action action)
+ : base(prototype, description, 1)
+ {
+ if (action == null)
+ throw new ArgumentNullException("action");
+ this.action = action;
+ }
+
+ protected override void OnParseComplete(OptionContext c)
+ {
+ action(Parse(c.OptionValues[0], c));
+ }
+ }
+
+ sealed class ActionOption : Option
+ {
+ OptionAction action;
+
+ public ActionOption(string prototype, string description, OptionAction action)
+ : base(prototype, description, 2)
+ {
+ if (action == null)
+ throw new ArgumentNullException("action");
+ this.action = action;
+ }
+
+ protected override void OnParseComplete(OptionContext c)
+ {
+ action(
+ Parse(c.OptionValues[0], c),
+ Parse(c.OptionValues[1], c));
+ }
+ }
+
+ public OptionSet Add(string prototype, Action action)
+ {
+ return Add(prototype, null, action);
+ }
+
+ public OptionSet Add(string prototype, string description, Action action)
+ {
+ return Add(new ActionOption(prototype, description, action));
+ }
+
+ public OptionSet Add(string prototype, OptionAction action)
+ {
+ return Add(prototype, null, action);
+ }
+
+ public OptionSet Add(string prototype, string description, OptionAction action)
+ {
+ return Add(new ActionOption(prototype, description, action));
+ }
+
+ protected virtual OptionContext CreateOptionContext()
+ {
+ return new OptionContext(this);
+ }
#if LINQ
public List Parse (IEnumerable arguments)
@@ -718,386 +749,427 @@ from argument in arguments
return r;
}
#else
- public List Parse (IEnumerable arguments)
- {
- OptionContext c = CreateOptionContext ();
- c.OptionIndex = -1;
- bool process = true;
- List unprocessed = new List ();
- Option def = Contains ("<>") ? this ["<>"] : null;
- foreach (string argument in arguments) {
- ++c.OptionIndex;
- if (argument == "--") {
- process = false;
- continue;
- }
- if (!process) {
- Unprocessed (unprocessed, def, c, argument);
- continue;
- }
- if (!Parse (argument, c))
- Unprocessed (unprocessed, def, c, argument);
- }
- if (c.Option != null)
- c.Option.Invoke (c);
- return unprocessed;
- }
+ public List Parse(IEnumerable arguments)
+ {
+ OptionContext c = CreateOptionContext();
+ c.OptionIndex = -1;
+ bool process = true;
+ List unprocessed = new List();
+ Option def = Contains("<>") ? this["<>"] : null;
+ foreach (string argument in arguments)
+ {
+ ++c.OptionIndex;
+ if (argument == "--")
+ {
+ process = false;
+ continue;
+ }
+ if (!process)
+ {
+ Unprocessed(unprocessed, def, c, argument);
+ continue;
+ }
+ if (!Parse(argument, c))
+ Unprocessed(unprocessed, def, c, argument);
+ }
+ if (c.Option != null)
+ c.Option.Invoke(c);
+ return unprocessed;
+ }
#endif
- private static bool Unprocessed (ICollection extra, Option def, OptionContext c, string argument)
- {
- if (def == null) {
- extra.Add (argument);
- return false;
- }
- c.OptionValues.Add (argument);
- c.Option = def;
- c.Option.Invoke (c);
- return false;
- }
-
- private readonly Regex ValueOption = new Regex (
- @"^(?--|-|/)(?[^:=]+)((?[:=])(?.*))?$");
-
- protected bool GetOptionParts (string argument, out string flag, out string name, out string sep, out string value)
- {
- if (argument == null)
- throw new ArgumentNullException ("argument");
-
- flag = name = sep = value = null;
- Match m = ValueOption.Match (argument);
- if (!m.Success) {
- return false;
- }
- flag = m.Groups ["flag"].Value;
- name = m.Groups ["name"].Value;
- if (m.Groups ["sep"].Success && m.Groups ["value"].Success) {
- sep = m.Groups ["sep"].Value;
- value = m.Groups ["value"].Value;
- }
- return true;
- }
-
- protected virtual bool Parse (string argument, OptionContext c)
- {
- if (c.Option != null) {
- ParseValue (argument, c);
- return true;
- }
-
- string f, n, s, v;
- if (!GetOptionParts (argument, out f, out n, out s, out v))
- return false;
-
- Option p;
- if (Contains (n)) {
- p = this [n];
- c.OptionName = f + n;
- c.Option = p;
- switch (p.OptionValueType) {
- case OptionValueType.None:
- c.OptionValues.Add (n);
- c.Option.Invoke (c);
- break;
- case OptionValueType.Optional:
- case OptionValueType.Required:
- ParseValue (v, c);
- break;
- }
- return true;
- }
- // no match; is it a bool option?
- if (ParseBool (argument, n, c))
- return true;
- // is it a bundled option?
- if (ParseBundledValue (f, string.Concat (n + s + v), c))
- return true;
-
- return false;
- }
-
- private void ParseValue (string option, OptionContext c)
- {
- if (option != null)
- foreach (string o in c.Option.ValueSeparators != null
- ? option.Split (c.Option.ValueSeparators, StringSplitOptions.None)
- : new string[]{option}) {
- c.OptionValues.Add (o);
- }
- if (c.OptionValues.Count == c.Option.MaxValueCount ||
- c.Option.OptionValueType == OptionValueType.Optional)
- c.Option.Invoke (c);
- else if (c.OptionValues.Count > c.Option.MaxValueCount) {
- throw new OptionException (localizer (string.Format (
- "Error: Found {0} option values when expecting {1}.",
- c.OptionValues.Count, c.Option.MaxValueCount)),
- c.OptionName);
- }
- }
-
- private bool ParseBool (string option, string n, OptionContext c)
- {
- Option p;
- string rn;
- if (n.Length >= 1 && (n [n.Length-1] == '+' || n [n.Length-1] == '-') &&
- Contains ((rn = n.Substring (0, n.Length-1)))) {
- p = this [rn];
- string v = n [n.Length-1] == '+' ? option : null;
- c.OptionName = option;
- c.Option = p;
- c.OptionValues.Add (v);
- p.Invoke (c);
- return true;
- }
- return false;
- }
-
- private bool ParseBundledValue (string f, string n, OptionContext c)
- {
- if (f != "-")
- return false;
- for (int i = 0; i < n.Length; ++i) {
- Option p;
- string opt = f + n [i].ToString ();
- string rn = n [i].ToString ();
- if (!Contains (rn)) {
- if (i == 0)
- return false;
- throw new OptionException (string.Format (localizer (
- "Cannot bundle unregistered option '{0}'."), opt), opt);
- }
- p = this [rn];
- switch (p.OptionValueType) {
- case OptionValueType.None:
- Invoke (c, opt, n, p);
- break;
- case OptionValueType.Optional:
- case OptionValueType.Required: {
- string v = n.Substring (i+1);
- c.Option = p;
- c.OptionName = opt;
- ParseValue (v.Length != 0 ? v : null, c);
- return true;
- }
- default:
- throw new InvalidOperationException ("Unknown OptionValueType: " + p.OptionValueType);
- }
- }
- return true;
- }
-
- private static void Invoke (OptionContext c, string name, string value, Option option)
- {
- c.OptionName = name;
- c.Option = option;
- c.OptionValues.Add (value);
- option.Invoke (c);
- }
-
- private const int OptionWidth = 29;
-
- public void WriteOptionDescriptions (TextWriter o)
- {
- foreach (Option p in this) {
- int written = 0;
- if (!WriteOptionPrototype (o, p, ref written))
- continue;
-
- if (written < OptionWidth)
- o.Write (new string (' ', OptionWidth - written));
- else {
- o.WriteLine ();
- o.Write (new string (' ', OptionWidth));
- }
-
- List lines = GetLines (localizer (GetDescription (p.Description)));
- o.WriteLine (lines [0]);
- string prefix = new string (' ', OptionWidth+2);
- for (int i = 1; i < lines.Count; ++i) {
- o.Write (prefix);
- o.WriteLine (lines [i]);
- }
- }
- }
-
- bool WriteOptionPrototype (TextWriter o, Option p, ref int written)
- {
- string[] names = p.Names;
-
- int i = GetNextOptionIndex (names, 0);
- if (i == names.Length)
- return false;
-
- if (names [i].Length == 1) {
- Write (o, ref written, " -");
- Write (o, ref written, names [0]);
- }
- else {
- Write (o, ref written, " --");
- Write (o, ref written, names [0]);
- }
-
- for ( i = GetNextOptionIndex (names, i+1);
- i < names.Length; i = GetNextOptionIndex (names, i+1)) {
- Write (o, ref written, ", ");
- Write (o, ref written, names [i].Length == 1 ? "-" : "--");
- Write (o, ref written, names [i]);
- }
-
- if (p.OptionValueType == OptionValueType.Optional ||
- p.OptionValueType == OptionValueType.Required) {
- if (p.OptionValueType == OptionValueType.Optional) {
- Write (o, ref written, localizer ("["));
- }
- Write (o, ref written, localizer ("=" + GetArgumentName (0, p.MaxValueCount, p.Description)));
- string sep = p.ValueSeparators != null && p.ValueSeparators.Length > 0
- ? p.ValueSeparators [0]
- : " ";
- for (int c = 1; c < p.MaxValueCount; ++c) {
- Write (o, ref written, localizer (sep + GetArgumentName (c, p.MaxValueCount, p.Description)));
- }
- if (p.OptionValueType == OptionValueType.Optional) {
- Write (o, ref written, localizer ("]"));
- }
- }
- return true;
- }
-
- static int GetNextOptionIndex (string[] names, int i)
- {
- while (i < names.Length && names [i] == "<>") {
- ++i;
- }
- return i;
- }
-
- static void Write (TextWriter o, ref int n, string s)
- {
- n += s.Length;
- o.Write (s);
- }
-
- private static string GetArgumentName (int index, int maxIndex, string description)
- {
- if (description == null)
- return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1);
- string[] nameStart;
- if (maxIndex == 1)
- nameStart = new string[]{"{0:", "{"};
- else
- nameStart = new string[]{"{" + index + ":"};
- for (int i = 0; i < nameStart.Length; ++i) {
- int start, j = 0;
- do {
- start = description.IndexOf (nameStart [i], j);
- } while (start >= 0 && j != 0 ? description [j++ - 1] == '{' : false);
- if (start == -1)
- continue;
- int end = description.IndexOf ("}", start);
- if (end == -1)
- continue;
- return description.Substring (start + nameStart [i].Length, end - start - nameStart [i].Length);
- }
- return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1);
- }
-
- private static string GetDescription (string description)
- {
- if (description == null)
- return string.Empty;
- StringBuilder sb = new StringBuilder (description.Length);
- int start = -1;
- for (int i = 0; i < description.Length; ++i) {
- switch (description [i]) {
- case '{':
- if (i == start) {
- sb.Append ('{');
- start = -1;
- }
- else if (start < 0)
- start = i + 1;
- break;
- case '}':
- if (start < 0) {
- if ((i+1) == description.Length || description [i+1] != '}')
- throw new InvalidOperationException ("Invalid option description: " + description);
- ++i;
- sb.Append ("}");
- }
- else {
- sb.Append (description.Substring (start, i - start));
- start = -1;
- }
- break;
- case ':':
- if (start < 0)
- goto default;
- start = i + 1;
- break;
- default:
- if (start < 0)
- sb.Append (description [i]);
- break;
- }
- }
- return sb.ToString ();
- }
-
- private static List GetLines (string description)
- {
- List lines = new List ();
- if (string.IsNullOrEmpty (description)) {
- lines.Add (string.Empty);
- return lines;
- }
- int length = 80 - OptionWidth - 2;
- int start = 0, end;
- do {
- end = GetLineEnd (start, length, description);
- bool cont = false;
- if (end < description.Length) {
- char c = description [end];
- if (c == '-' || (char.IsWhiteSpace (c) && c != '\n'))
- ++end;
- else if (c != '\n') {
- cont = true;
- --end;
- }
- }
- lines.Add (description.Substring (start, end - start));
- if (cont) {
- lines [lines.Count-1] += "-";
- }
- start = end;
- if (start < description.Length && description [start] == '\n')
- ++start;
- } while (end < description.Length);
- return lines;
- }
-
- private static int GetLineEnd (int start, int length, string description)
- {
- int end = Math.Min (start + length, description.Length);
- int sep = -1;
- for (int i = start; i < end; ++i) {
- switch (description [i]) {
- case ' ':
- case '\t':
- case '\v':
- case '-':
- case ',':
- case '.':
- case ';':
- sep = i;
- break;
- case '\n':
- return i;
- }
- }
- if (sep == -1 || end == description.Length)
- return end;
- return sep;
- }
- }
+ private static bool Unprocessed(ICollection extra, Option def, OptionContext c, string argument)
+ {
+ if (def == null)
+ {
+ extra.Add(argument);
+ return false;
+ }
+ c.OptionValues.Add(argument);
+ c.Option = def;
+ c.Option.Invoke(c);
+ return false;
+ }
+
+ private readonly Regex ValueOption = new Regex(
+ @"^(?--|-|/)(?[^:=]+)((?[:=])(?.*))?$");
+
+ protected bool GetOptionParts(string argument, out string flag, out string name, out string sep, out string value)
+ {
+ if (argument == null)
+ throw new ArgumentNullException("argument");
+
+ flag = name = sep = value = null;
+ Match m = ValueOption.Match(argument);
+ if (!m.Success)
+ {
+ return false;
+ }
+ flag = m.Groups["flag"].Value;
+ name = m.Groups["name"].Value;
+ if (m.Groups["sep"].Success && m.Groups["value"].Success)
+ {
+ sep = m.Groups["sep"].Value;
+ value = m.Groups["value"].Value;
+ }
+ return true;
+ }
+
+ protected virtual bool Parse(string argument, OptionContext c)
+ {
+ if (c.Option != null)
+ {
+ ParseValue(argument, c);
+ return true;
+ }
+
+ string f, n, s, v;
+ if (!GetOptionParts(argument, out f, out n, out s, out v))
+ return false;
+
+ Option p;
+ if (Contains(n))
+ {
+ p = this[n];
+ c.OptionName = f + n;
+ c.Option = p;
+ switch (p.OptionValueType)
+ {
+ case OptionValueType.None:
+ c.OptionValues.Add(n);
+ c.Option.Invoke(c);
+ break;
+ case OptionValueType.Optional:
+ case OptionValueType.Required:
+ ParseValue(v, c);
+ break;
+ }
+ return true;
+ }
+ // no match; is it a bool option?
+ if (ParseBool(argument, n, c))
+ return true;
+ // is it a bundled option?
+ if (ParseBundledValue(f, string.Concat(n + s + v), c))
+ return true;
+
+ return false;
+ }
+
+ private void ParseValue(string option, OptionContext c)
+ {
+ if (option != null)
+ foreach (string o in c.Option.ValueSeparators != null
+ ? option.Split(c.Option.ValueSeparators, StringSplitOptions.None)
+ : new string[] { option })
+ {
+ c.OptionValues.Add(o);
+ }
+ if (c.OptionValues.Count == c.Option.MaxValueCount ||
+ c.Option.OptionValueType == OptionValueType.Optional)
+ c.Option.Invoke(c);
+ else if (c.OptionValues.Count > c.Option.MaxValueCount)
+ {
+ throw new OptionException(localizer(string.Format(
+ "Error: Found {0} option values when expecting {1}.",
+ c.OptionValues.Count, c.Option.MaxValueCount)),
+ c.OptionName);
+ }
+ }
+
+ private bool ParseBool(string option, string n, OptionContext c)
+ {
+ Option p;
+ string rn;
+ if (n.Length >= 1 && (n[n.Length - 1] == '+' || n[n.Length - 1] == '-') &&
+ Contains((rn = n.Substring(0, n.Length - 1))))
+ {
+ p = this[rn];
+ string v = n[n.Length - 1] == '+' ? option : null;
+ c.OptionName = option;
+ c.Option = p;
+ c.OptionValues.Add(v);
+ p.Invoke(c);
+ return true;
+ }
+ return false;
+ }
+
+ private bool ParseBundledValue(string f, string n, OptionContext c)
+ {
+ if (f != "-")
+ return false;
+ for (int i = 0; i < n.Length; ++i)
+ {
+ Option p;
+ string opt = f + n[i].ToString();
+ string rn = n[i].ToString();
+ if (!Contains(rn))
+ {
+ if (i == 0)
+ return false;
+ throw new OptionException(string.Format(localizer(
+ "Cannot bundle unregistered option '{0}'."), opt), opt);
+ }
+ p = this[rn];
+ switch (p.OptionValueType)
+ {
+ case OptionValueType.None:
+ Invoke(c, opt, n, p);
+ break;
+ case OptionValueType.Optional:
+ case OptionValueType.Required:
+ {
+ string v = n.Substring(i + 1);
+ c.Option = p;
+ c.OptionName = opt;
+ ParseValue(v.Length != 0 ? v : null, c);
+ return true;
+ }
+ default:
+ throw new InvalidOperationException("Unknown OptionValueType: " + p.OptionValueType);
+ }
+ }
+ return true;
+ }
+
+ private static void Invoke(OptionContext c, string name, string value, Option option)
+ {
+ c.OptionName = name;
+ c.Option = option;
+ c.OptionValues.Add(value);
+ option.Invoke(c);
+ }
+
+ private const int OptionWidth = 29;
+
+ public void WriteOptionDescriptions(TextWriter o)
+ {
+ foreach (Option p in this)
+ {
+ int written = 0;
+ if (!WriteOptionPrototype(o, p, ref written))
+ continue;
+
+ if (written < OptionWidth)
+ o.Write(new string(' ', OptionWidth - written));
+ else
+ {
+ o.WriteLine();
+ o.Write(new string(' ', OptionWidth));
+ }
+
+ List lines = GetLines(localizer(GetDescription(p.Description)));
+ o.WriteLine(lines[0]);
+ string prefix = new string(' ', OptionWidth + 2);
+ for (int i = 1; i < lines.Count; ++i)
+ {
+ o.Write(prefix);
+ o.WriteLine(lines[i]);
+ }
+ }
+ }
+
+ bool WriteOptionPrototype(TextWriter o, Option p, ref int written)
+ {
+ string[] names = p.Names;
+
+ int i = GetNextOptionIndex(names, 0);
+ if (i == names.Length)
+ return false;
+
+ if (names[i].Length == 1)
+ {
+ Write(o, ref written, " -");
+ Write(o, ref written, names[0]);
+ }
+ else
+ {
+ Write(o, ref written, " --");
+ Write(o, ref written, names[0]);
+ }
+
+ for (i = GetNextOptionIndex(names, i + 1);
+ i < names.Length; i = GetNextOptionIndex(names, i + 1))
+ {
+ Write(o, ref written, ", ");
+ Write(o, ref written, names[i].Length == 1 ? "-" : "--");
+ Write(o, ref written, names[i]);
+ }
+
+ if (p.OptionValueType == OptionValueType.Optional ||
+ p.OptionValueType == OptionValueType.Required)
+ {
+ if (p.OptionValueType == OptionValueType.Optional)
+ {
+ Write(o, ref written, localizer("["));
+ }
+ Write(o, ref written, localizer("=" + GetArgumentName(0, p.MaxValueCount, p.Description)));
+ string sep = p.ValueSeparators != null && p.ValueSeparators.Length > 0
+ ? p.ValueSeparators[0]
+ : " ";
+ for (int c = 1; c < p.MaxValueCount; ++c)
+ {
+ Write(o, ref written, localizer(sep + GetArgumentName(c, p.MaxValueCount, p.Description)));
+ }
+ if (p.OptionValueType == OptionValueType.Optional)
+ {
+ Write(o, ref written, localizer("]"));
+ }
+ }
+ return true;
+ }
+
+ static int GetNextOptionIndex(string[] names, int i)
+ {
+ while (i < names.Length && names[i] == "<>")
+ {
+ ++i;
+ }
+ return i;
+ }
+
+ static void Write(TextWriter o, ref int n, string s)
+ {
+ n += s.Length;
+ o.Write(s);
+ }
+
+ private static string GetArgumentName(int index, int maxIndex, string description)
+ {
+ if (description == null)
+ return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1);
+ string[] nameStart;
+ if (maxIndex == 1)
+ nameStart = new string[] { "{0:", "{" };
+ else
+ nameStart = new string[] { "{" + index + ":" };
+ for (int i = 0; i < nameStart.Length; ++i)
+ {
+ int start, j = 0;
+ do
+ {
+ start = description.IndexOf(nameStart[i], j);
+ } while (start >= 0 && j != 0 ? description[j++ - 1] == '{' : false);
+ if (start == -1)
+ continue;
+ int end = description.IndexOf("}", start);
+ if (end == -1)
+ continue;
+ return description.Substring(start + nameStart[i].Length, end - start - nameStart[i].Length);
+ }
+ return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1);
+ }
+
+ private static string GetDescription(string description)
+ {
+ if (description == null)
+ return string.Empty;
+ StringBuilder sb = new StringBuilder(description.Length);
+ int start = -1;
+ for (int i = 0; i < description.Length; ++i)
+ {
+ switch (description[i])
+ {
+ case '{':
+ if (i == start)
+ {
+ sb.Append('{');
+ start = -1;
+ }
+ else if (start < 0)
+ start = i + 1;
+ break;
+ case '}':
+ if (start < 0)
+ {
+ if ((i + 1) == description.Length || description[i + 1] != '}')
+ throw new InvalidOperationException("Invalid option description: " + description);
+ ++i;
+ sb.Append("}");
+ }
+ else
+ {
+ sb.Append(description.Substring(start, i - start));
+ start = -1;
+ }
+ break;
+ case ':':
+ if (start < 0)
+ goto default;
+ start = i + 1;
+ break;
+ default:
+ if (start < 0)
+ sb.Append(description[i]);
+ break;
+ }
+ }
+ return sb.ToString();
+ }
+
+ private static List GetLines(string description)
+ {
+ List lines = new List();
+ if (string.IsNullOrEmpty(description))
+ {
+ lines.Add(string.Empty);
+ return lines;
+ }
+ int length = 80 - OptionWidth - 2;
+ int start = 0, end;
+ do
+ {
+ end = GetLineEnd(start, length, description);
+ bool cont = false;
+ if (end < description.Length)
+ {
+ char c = description[end];
+ if (c == '-' || (char.IsWhiteSpace(c) && c != '\n'))
+ ++end;
+ else if (c != '\n')
+ {
+ cont = true;
+ --end;
+ }
+ }
+ lines.Add(description.Substring(start, end - start));
+ if (cont)
+ {
+ lines[lines.Count - 1] += "-";
+ }
+ start = end;
+ if (start < description.Length && description[start] == '\n')
+ ++start;
+ } while (end < description.Length);
+ return lines;
+ }
+
+ private static int GetLineEnd(int start, int length, string description)
+ {
+ int end = Math.Min(start + length, description.Length);
+ int sep = -1;
+ for (int i = start; i < end; ++i)
+ {
+ switch (description[i])
+ {
+ case ' ':
+ case '\t':
+ case '\v':
+ case '-':
+ case ',':
+ case '.':
+ case ';':
+ sep = i;
+ break;
+ case '\n':
+ return i;
+ }
+ }
+ if (sep == -1 || end == description.Length)
+ return end;
+ return sep;
+ }
+ }
}
diff --git a/packages.config b/packages.config
new file mode 100644
index 0000000..44aa00e
--- /dev/null
+++ b/packages.config
@@ -0,0 +1,10 @@
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/utils.cs b/utils.cs
index e030cc6..dbcf974 100644
--- a/utils.cs
+++ b/utils.cs
@@ -1,76 +1,76 @@
-using System;
+using System;
using System.Text;
using System.Linq;
class Utils
-{
- // Copied from https://www.codeproject.com/Articles/36747/%2FArticles%2F36747%2FQuick-and-Dirty-HexDump-of-a-Byte-Array
- public static string HexDump(byte[] bytes, int bytesPerLine = 16)
- {
- if (bytes == null) return "";
- int bytesLength = bytes.Length;
+{
+ // Copied from https://www.codeproject.com/Articles/36747/%2FArticles%2F36747%2FQuick-and-Dirty-HexDump-of-a-Byte-Array
+ public static string HexDump(byte[] bytes, int bytesPerLine = 16)
+ {
+ if (bytes == null) return "";
+ int bytesLength = bytes.Length;
- char[] HexChars = "0123456789ABCDEF".ToCharArray();
+ char[] HexChars = "0123456789ABCDEF".ToCharArray();
- int firstHexColumn =
- 8 // 8 characters for the address
- + 3; // 3 spaces
+ int firstHexColumn =
+ 8 // 8 characters for the address
+ + 3; // 3 spaces
- int firstCharColumn = firstHexColumn
- + bytesPerLine * 3 // - 2 digit for the hexadecimal value and 1 space
- + (bytesPerLine - 1) / 8 // - 1 extra space every 8 characters from the 9th
- + 2; // 2 spaces
+ int firstCharColumn = firstHexColumn
+ + bytesPerLine * 3 // - 2 digit for the hexadecimal value and 1 space
+ + (bytesPerLine - 1) / 8 // - 1 extra space every 8 characters from the 9th
+ + 2; // 2 spaces
- int lineLength = firstCharColumn
- + bytesPerLine // - characters to show the ascii value
- + Environment.NewLine.Length; // Carriage return and line feed (should normally be 2)
+ int lineLength = firstCharColumn
+ + bytesPerLine // - characters to show the ascii value
+ + Environment.NewLine.Length; // Carriage return and line feed (should normally be 2)
- char[] line = (new String(' ', lineLength - Environment.NewLine.Length) + Environment.NewLine).ToCharArray();
- int expectedLines = (bytesLength + bytesPerLine - 1) / bytesPerLine;
- StringBuilder result = new StringBuilder(expectedLines * lineLength);
+ char[] line = (new String(' ', lineLength - Environment.NewLine.Length) + Environment.NewLine).ToCharArray();
+ int expectedLines = (bytesLength + bytesPerLine - 1) / bytesPerLine;
+ StringBuilder result = new StringBuilder(expectedLines * lineLength);
- for (int i = 0; i < bytesLength; i += bytesPerLine)
- {
- line[0] = HexChars[(i >> 28) & 0xF];
- line[1] = HexChars[(i >> 24) & 0xF];
- line[2] = HexChars[(i >> 20) & 0xF];
- line[3] = HexChars[(i >> 16) & 0xF];
- line[4] = HexChars[(i >> 12) & 0xF];
- line[5] = HexChars[(i >> 8) & 0xF];
- line[6] = HexChars[(i >> 4) & 0xF];
- line[7] = HexChars[(i >> 0) & 0xF];
+ for (int i = 0; i < bytesLength; i += bytesPerLine)
+ {
+ line[0] = HexChars[(i >> 28) & 0xF];
+ line[1] = HexChars[(i >> 24) & 0xF];
+ line[2] = HexChars[(i >> 20) & 0xF];
+ line[3] = HexChars[(i >> 16) & 0xF];
+ line[4] = HexChars[(i >> 12) & 0xF];
+ line[5] = HexChars[(i >> 8) & 0xF];
+ line[6] = HexChars[(i >> 4) & 0xF];
+ line[7] = HexChars[(i >> 0) & 0xF];
- int hexColumn = firstHexColumn;
- int charColumn = firstCharColumn;
+ int hexColumn = firstHexColumn;
+ int charColumn = firstCharColumn;
- for (int j = 0; j < bytesPerLine; j++)
- {
- if (j > 0 && (j & 7) == 0) hexColumn++;
- if (i + j >= bytesLength)
- {
- line[hexColumn] = ' ';
- line[hexColumn + 1] = ' ';
- line[charColumn] = ' ';
- }
- else
- {
- byte b = bytes[i + j];
- line[hexColumn] = HexChars[(b >> 4) & 0xF];
- line[hexColumn + 1] = HexChars[b & 0xF];
- line[charColumn] = (b < 32 ? '·' : (char)b);
- }
- hexColumn += 3;
- charColumn++;
- }
- result.Append(line);
- }
- return result.ToString();
- }
-
- public static string RandomString(int length)
- {
- var random = new Random();
- const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
- return new string(Enumerable.Repeat(chars, length).Select(s => s[random.Next(s.Length)]).ToArray());
- }
+ for (int j = 0; j < bytesPerLine; j++)
+ {
+ if (j > 0 && (j & 7) == 0) hexColumn++;
+ if (i + j >= bytesLength)
+ {
+ line[hexColumn] = ' ';
+ line[hexColumn + 1] = ' ';
+ line[charColumn] = ' ';
+ }
+ else
+ {
+ byte b = bytes[i + j];
+ line[hexColumn] = HexChars[(b >> 4) & 0xF];
+ line[hexColumn + 1] = HexChars[b & 0xF];
+ line[charColumn] = (b < 32 ? '·' : (char)b);
+ }
+ hexColumn += 3;
+ charColumn++;
+ }
+ result.Append(line);
+ }
+ return result.ToString();
+ }
+
+ public static string RandomString(int length)
+ {
+ var random = new Random();
+ const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
+ return new string(Enumerable.Repeat(chars, length).Select(s => s[random.Next(s.Length)]).ToArray());
+ }
}
\ No newline at end of file